基于Mybatis的Dao层开发
转自:https://www.cnblogs.com/rodge-run/p/6528398.html
基于Mybatis的Dao层开发
SqlSessionFactoryBuilder用于创建 SqlSessionFacoty,SqlSessionFacoty一旦创建完成就不需要SqlSessionFactoryBuilder了,因为 SqlSession是通过SqlSessionFactory生产,所以可以将SqlSessionFactoryBuilder当成一个工具类使用, 最佳使用范围是方法范围即方法体内局部变量。
SqlSessionFactory是一个接口,接口中定义了openSession的不同重载方法,SqlSessionFactory的最佳使用范围是整个应用运行期间,一旦创建后可以重复使用,通常以单例模式管理SqlSessionFactory。
SqlSession是一个面向用户的接口, sqlSession中定义了数据库操作方法。
每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能共享使用,它也是线程不安全的。因此最佳的范围是请求或方法范围。绝对不能将SqlSession实例的引用放在一个类的静态字段或实例字段中。
打开一个 SqlSession;使用完毕就要关闭它。通常把这个关闭操作放到 finally 块中以确保每次都能执行关闭。
1 传统的dao层开发(编写dao接口, 编写dao接口的实现类)
1>配置mapper映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.rodge.dao.UserMapper">
<!-- 根据id查询 -->
<select id="findUserByIdDao" parameterType="int" resultType="user">
SELECT * FROM `user` WHERE id= #{id}
</select>
</mapper>
2>在sqlMapConfig.xml文件中配置map映射
<?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>
<!-- 配置属性 -->
<properties resource="databases.properties">
<!-- <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="luoji1025"/> -->
</properties>
<!-- 配置别名扫描 -->
<typeAliases>
<package name="cn.rodge"/>
</typeAliases>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 配置mapper映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
<package name="cn.rodge.dao"/>
</mappers>
</configuration>
3>创建dao层接口
package cn.rodge.dao;
import cn.rodge.entity.User;
public interface UserMapper {
public User findUserByIdDao (int id) throws Exception;
}
4>创建dao的实现类
package cn.rodge.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import cn.rodge.dao.UserMapper;
import cn.rodge.entity.User;
public class UserMapperImpl implements UserMapper {
private SqlSessionFactory sqlSessionFactory;
//有参数的都在方法
public UserMapperImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
//无参数的构造方法
public UserMapperImpl() {
super();
}
@Override
public User findUserByIdDao(int id) throws Exception {
//获取sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//调用sqlsession中的查询单个结果的方法
User user = sqlSession.selectOne("findUserByIdDao", id);
//释放资源
sqlSession.close();
return user;
}
}
5>创建测试类
package cn.rodge.dao.impl;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import cn.rodge.entity.User;
public class UserMapperImplTest {
private UserMapperImpl userMapper;
@Before
public void init () throws Exception {
//创建sqlsessionfactorybuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取mabatis核心配置文件输入流
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//加载配置文件,并创建sqlsessionfactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//创建userMapper实体类, 通过有参数的构造方法
userMapper = new UserMapperImpl(sqlSessionFactory);
}
@Test
public void testFindUserById() throws Exception {
User user = userMapper.findUserByIdDao(1);
System.out.println(user);
}
}
2 Mapper动态代理的方法开发dao层
Mapper接口开发需要遵循以下规范:
1. Mapper.xml文件中的namespace与mapper接口的类路径相同。
2. Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3. Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4. Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
5. Mapper接口和Mapper映射文件在同一目录下
1>配置UserMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.rodge.dao.UserMapper">
<!-- 根据id查询 -->
<select id="findUserByIdDao" parameterType="int" resultType="user">
SELECT * FROM `user` WHERE id= #{id}
</select>
</mapper>
2>创建UserMapper.java接口
package cn.rodge.dao;
import cn.rodge.entity.User;
public interface UserMapper {
public User findUserByIdDao (int id) throws Exception;
}
3>在sqlMapConfig.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>
<!-- 配置属性 -->
<properties resource="databases.properties">
<!-- <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="luoji1025"/> -->
</properties>
<!-- 配置别名扫描 -->
<typeAliases>
<package name="cn.rodge"/>
</typeAliases>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC" />
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 配置mapper映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
<package name="cn.rodge.dao"/>
</mappers>
</configuration>
4>创建测试类
package cn.rodge.dao;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import cn.rodge.entity.User;
public class UserMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init () throws Exception {
//创建sqlsessionfactorybuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取mabatis核心配置文件输入流
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//加载配置文件,并创建sqlsessionfactory
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//创建userMapper实体类, 通过有参数的构造方法
}
@Test
public void testFindUserById() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findUserByIdDao(1);
System.out.println(user);
sqlSession.close();
}
}
UserMapper接口中如何区分调用selectOne和selectList方法
动态代理对象调用sqlSession.selectOne()和sqlSession.selectList()是根据mapper接口方法的返回值决定,如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法.