Dao开发方法

来源:互联网 发布:蜂群算法 matlab 编辑:程序博客网 时间:2024/06/02 04:08
1 Dao开发方法    使用Mybatis开发Dao,通常有两个方法,即原始Dao开发方法和Mapper接口开发方法。1.1 需求将下边的功能实现Dao:根据用户id查询一个用户信息根据用户名称模糊查询用户信息列表添加用户信息1.2 SqlSession的使用范围    SqlSession中封装了对数据库的操作,如:查询、插入、更新、删除等。通过SqlSessionFactory创建SqlSession,而SqlSessionFactory是通过SqlSessionFactoryBuilder进行创建。1.2.1 SqlSessionFactoryBuilderSqlSessionFactoryBuilder用于创建SqlSessionFacoty,SqlSessionFacoty一旦创建完成就不需要SqlSessionFactoryBuilder了,因为SqlSession是通过SqlSessionFactory生产,所以可以将SqlSessionFactoryBuilder当成一个工具类使用,最佳使用范围是方法范围即方法体内局部变量。1.2.2 SqlSessionFactory    SqlSessionFactory是一个接口,接口中定义了openSession的不同重载方法,SqlSessionFactory的最佳使用范围是整个应用运行期间,一旦创建后可以重复使用,通常以单例模式管理SqlSessionFactory。1.2.3 SqlSession    SqlSession是一个面向用户的接口, sqlSession中定义了数据库操作,默认使用DefaultSqlSession实现类。执行过程如下:1、 加载数据源等配置信息Environment environment = configuration.getEnvironment();2、 创建数据库链接3、 创建事务对象4、 创建Executor,SqlSession所有操作都是通过Executor完成,mybatis源码如下:if (ExecutorType.BATCH == executorType) {      executor = newBatchExecutor(this, transaction);    } elseif (ExecutorType.REUSE == executorType) {      executor = new ReuseExecutor(this, transaction);    } else {      executor = new SimpleExecutor(this, transaction);    }if (cacheEnabled) {      executor = new CachingExecutor(executor, autoCommit);    }5、 SqlSession的实现类即DefaultSqlSession,此对象中对操作数据库实质上用的是Executor结论:    每个线程都应该有它自己的SqlSession实例。SqlSession的实例不能共享使用,它也是线程不安全的。因此最佳的范围是请求或方法范围。绝对不能将SqlSession实例的引用放在一个类的静态字段或实例字段中。    打开一个 SqlSession;使用完毕就要关闭它。通常把这个关闭操作放到 finally 块中以确保每次都能执行关闭。如下:    SqlSession session = sqlSessionFactory.openSession();    try {         // do work    } finally {        session.close();    }1.3 原始Dao开发方式    原始Dao开发方法需要程序员编写Dao接口和Dao实现类。1.3.1 映射文件<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="test"><!-- 根据id获取用户信息 -->    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">        select * from user where id = #{id}    </select><!-- 添加用户 -->    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select LAST_INSERT_ID()     </selectKey>      insert into user(username,birthday,sex,address)       values(#{username},#{birthday},#{sex},#{address})    </insert></mapper>1.3.2 Dao接口Public interface UserDao {    public User getUserById(int id) throws Exception;    public void insertUser(User user) throws Exception;}Public class UserDaoImpl implements UserDao {    //注入SqlSessionFactory    public UserDaoImpl(SqlSessionFactory sqlSessionFactory){        this.setSqlSessionFactory(sqlSessionFactory);    }    private SqlSessionFactory sqlSessionFactory;    @Override    public User getUserById(int id) throws Exception {        SqlSession session = sqlSessionFactory.openSession();        User user = null;        try {            //通过sqlsession调用selectOne方法获取一条结果集            //参数1:指定定义的statement的id,参数2:指定向statement中传递的参数            user = session.selectOne("test.findUserById", 1);            System.out.println(user);        } finally{            session.close();        }        return user;    }    @Override    Public void insertUser(User user) throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        try {            sqlSession.insert("insertUser", user);            sqlSession.commit();        } finally{            session.close();        }    }}1.3.3 问题原始Dao开发中存在以下问题:u Dao方法体存在重复代码:通过SqlSessionFactory创建SqlSession,调用SqlSession的数据库操作方法u 调用sqlSession的数据库操作方法需要指定statement的id,这里存在硬编码,不得于开发维护。1.4 Mapper动态代理方式    1.4.1 实现原理    Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边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的类型相同1.4.2 Mapper.xml(映射文件)    定义mapper映射文件UserMapper.xml(内容同Users.xml),需要修改namespace的值为 UserMapper接口路径。将UserMapper.xml放在classpath 下mapper目录 下。<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.itcast.mybatis.mapper.UserMapper"><!-- 根据id获取用户信息 -->    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">        select * from user where id = #{id}    </select><!-- 自定义条件查询用户列表 -->    <select id="findUserByUsername" parameterType="java.lang.String"             resultType="cn.itcast.mybatis.po.User">       select * from user where username like '%${value}%'     </select><!-- 添加用户 -->    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select LAST_INSERT_ID()     </selectKey>      insert into user(username,birthday,sex,address)       values(#{username},#{birthday},#{sex},#{address})    </insert></mapper>1.4.3 Mapper.java(接口文件)/** * 用户管理mapper */Public interface UserMapper {    //根据用户id查询用户信息    public User findUserById(int id) throws Exception;    //查询用户列表    public List<User> findUserByUsername(String username) throws Exception;    //添加用户信息    public void insertUser(User user)throws Exception; }接口定义有如下特点:1、 Mapper接口方法名和Mapper.xml中定义的statement的id相同2、 Mapper接口方法的输入参数类型和mapper.xml中定义的statement的parameterType的类型相同3、 Mapper接口方法的输出参数类型和mapper.xml中定义的statement的resultType的类型相同1.4.4 加载UserMapper.xml文件修改SqlMapConfig.xml文件:  <!-- 加载映射文件 -->  <mappers>    <mapper resource="mapper/UserMapper.xml"/>  </mappers>1.4.5 测试Public class UserMapperTest extends TestCase {    private SqlSessionFactory sqlSessionFactory;    protected void setUp() throws Exception {        //mybatis配置文件        String resource = "sqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        //使用SqlSessionFactoryBuilder创建sessionFactory        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);    }    Public void testFindUserById() throws Exception {        //获取session        SqlSession session = sqlSessionFactory.openSession();        //获取mapper接口的代理对象        UserMapper userMapper = session.getMapper(UserMapper.class);        //调用代理对象方法        User user = userMapper.findUserById(1);        System.out.println(user);        //关闭session        session.close();    }    @Test    public void testFindUserByUsername() throws Exception {        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);        List<User> list = userMapper.findUserByUsername("张");        System.out.println(list.size());    }Public void testInsertUser() throws Exception {        //获取session        SqlSession session = sqlSessionFactory.openSession();        //获取mapper接口的代理对象        UserMapper userMapper = session.getMapper(UserMapper.class);        //要添加的数据        User user = new User();        user.setUsername("张三");        user.setBirthday(new Date());        user.setSex("1");        user.setAddress("北京市");        //通过mapper接口添加用户        userMapper.insertUser(user);        //提交        session.commit();        //关闭session        session.close();    }}1.4.6 总结u selectOne和selectList动态代理对象调用sqlSession.selectOne()和sqlSession.selectList()是根据mapper接口方法的返回值决定,如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法。u namespacemybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。
0 0
原创粉丝点击