发布于 2016-08-08 22:48:33 | 136 次阅读 | 评论: 0 | 来源: 网友投递
MyBatis 基于Java的持久层框架
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
因为mybatis好使,所以几乎需要操作数据库的时候,我都会使用mybatis,而且在一个正式的项目中,同时存在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>
根据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("数据库信息配置失败!");
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} finally{
try {
inputStream.close();
} catch (Exception e) {
}
}
}
public static InputStream getXMLIS(){
InputStream inputStream = null;
try {
//对资源进行加密,解密后处理
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;
}
}
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;
}