说明
配置pom.xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
配置mybatis-config.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>
<typeAliases>
<typeAlias type="com.yan.po.Role" alias="role"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value="mysql"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/yan/mapper/RoleMapper.xml"/>
</mappers>
</configuration>
获取SqlSessionFactory
- SqlSessionFactory是单例的,因此编写类SqlSessionFactoryUtil来控制
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory=null;
private static final Class<SqlSessionFactoryUtil> CLASS_LOCK=SqlSessionFactoryUtil.class;
/**
* 私有化构造参数
*/
private SqlSessionFactoryUtil(){};
public static SqlSessionFactory initSqlSessionFactory(){
String resource="mybatis-config.xml";
InputStream is=null;
try{
is=Resources.getResourceAsStream(resource);
}catch(Exception e){
Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(Level.SEVERE, null,e);
}
synchronized (CLASS_LOCK) {
if(sqlSessionFactory==null){
sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
}
}
return sqlSessionFactory;
}
public static SqlSession openSqlSession() {
if(sqlSessionFactory==null){
initSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
重写POJO的toString方法
@Override
public String toString() {
return "Role [id=" + id + ", roleName=" + roleName + ", note=" + note + "]";
}
测试
public class MybatisTest {
public static void main(String[] args) {
SqlSession sqlSession=null;
try{
sqlSession = SqlSessionFactoryUtil.openSqlSession();
RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);
Role r =new Role();
r=roleMapper.selectByPrimaryKey(1);
System.out.println(r);
}catch(Exception e){
System.out.println(e.getMessage());
sqlSession.rollback();
}finally{
if(sqlSession!=null){
sqlSession.close();
}
}
}
}
代码结构
![](http://image18-c.poco.cn/mypoco/myphoto/20161210/14/18404036720161210142520083_640.jpg?327x442_130)