因?yàn)閙ybatis好使,所以幾乎需要操作數(shù)據(jù)庫的時(shí)候,我都會(huì)使用mybatis,而且在一個(gè)正式的項(xiàng)目中,同時(shí)存在BS和CS的程序,都使用的Mybatis,使用的相同mapper文件。
Mybatis的XML配置文件正常如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="driver" />
<property name="url" value="url" />
<property name="username" value="username" />
<property name="password" value="password" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/isea/dao/YouMapper.xml" />
</mappers>
</configuration>
為了防止數(shù)據(jù)庫用戶名密碼泄漏,我將XML進(jìn)行雙向加密,變成了一個(gè)字節(jié)文件,而且文件名后綴隨意。
例如:basic.data,內(nèi)容局部如下:
根據(jù)XML生成Mybatis的SqlSessionFactory,代碼如下:
public class MyBatis {
private static final String CONFIG = "basic.data";
private SqlSessionFactory sqlSessionFactory;
private static MyBatis instance = new MyBatis();
private MyBatis(){
InputStream inputStream = null;
try {
inputStream = getXMLIS();
if(inputStream==null){
throw new RuntimeException("數(shù)據(jù)庫信息配置失敗!");
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} finally{
try {
inputStream.close();
} catch (Exception e) {
}
}
}
public static InputStream getXMLIS(){
InputStream inputStream = null;
try {
//對(duì)資源進(jìn)行加密,解密后處理
BufferedReader reader = new BufferedReader(new FileReader(new File(Config.LOCATION+"/"+CONFIG)));
String str = null;
StringBuffer sbBuffer = new StringBuffer();
while((str=reader.readLine())!=null){
sbBuffer.append(str);
}
EncrypDES encrypDES = new EncrypDES();
String result = encrypDES.Decryptor(sbBuffer.toString());
inputStream = new ByteArrayInputStream(result.getBytes());
return inputStream;
} catch (Exception e) {
}
return null;
}
public SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
public static MyBatis getInstance(){
return instance;
}
}
這里的data文件是在src下。
代碼中的EncrypDES是一個(gè)使用DES的加密解密類。
代碼中的Config.LOCATION代碼如下:
public static String getRealPath() throws Exception {
String realPath = Config.class.getClassLoader().getResource("").getFile();
java.io.File file = new java.io.File(realPath);
realPath = file.getAbsolutePath();
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
return realPath;
}
getRealPath()返回的值賦給LOCATION.
上面代碼的主要流程:讀取data文件,解密,以流的形式返回給mybatis.
通過Mybatis類就可以在程序的任意地方進(jìn)行調(diào)用了。
除了使用XML方式配置Mybatis外,還可以完全使用JAVA代碼進(jìn)行配置,這種方式比較麻煩,需要?jiǎng)?chuàng)建一個(gè)DataSource,然后用Mybatis配置類加載所有需要的mapper.class,這里就不詳細(xì)介紹了(除非有需要)。