iBatis的xml中sql语句含中文时出现乱码

谭骏
2023-12-01

  iBatis的xml中sql语句含中文时出现乱码的问题

 

在ibatis项目中有时候会在xml的sql语句中加入中文查询条件,例如 select * from user where name = '小明'  这种形式,在运行项目时会出现乱码问题,解决办法如下:

 

最近在iBatis网站上看到解决办法了
是读xml的时候出了问题,需要在java文件读取ibatis配置xml 时,对Reader文件流设置编码
要求 ibatis 版本2.3  
Resources.setCharset(Charset.forName("UTF-8"));
Reader reader = Resources.geResources.setCharset(Charset.forName("UTF-8"));

 

 

实例代码:

 

	private static final DaoManager daoManager; 
	private static final String resource = "com/myProject/database/dao.xml";
	static
	{
		Properties props = new Properties();
	 
		props.put("driver", C.DB_DRIVER);
		props.put("url", C.DB_URL);
		props.put("username",C.DB_USERNAME);
		props.put("password",C.DB_PASSWORD);
		daoManager = newDaoManager(props);
	}
	private static DaoManager newDaoManager(Properties props) 
	{
		try 
		{    
			com.ibatis.common.resources.Resources.setCharset(Charset.forName("utf-8"));
			Reader reader = Resources.getResourceAsReader(resource);
			return DaoManagerBuilder.buildDaoManager(reader, props);
		} 
		catch (Exception e)
		{
			throw new RuntimeException("get new manager error: " + e, e);  
		}
	}

 

 

 

 类似资料: