使用MyBatis进行Dao层开发

2019-02-19  本文已影响0人  花无缺_0159

【目录】
1 普通Dao层开发
2 Mapper动态代理开发

1 普通Dao层开发

准备数据库:

创建User表 插入一些数据

在Eclipse里新建项目目录如下:

项目目录结构

给出项目代码。

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>

  <environments default="development">
    <environment id="development">
    <!-- 使用jdbc的事务 -->
      <transactionManager type="JDBC"/>
      <!-- 使用连接池 连接数据库 -->
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/database?useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
      </dataSource>
    </environment>
  </environments>
  
 <!-- 配置映射器的位置 -->
  <mappers>
    <mapper resource="mapper/UserMapper.xml"/> 
   </mappers> 
   
</configuration>    

User.java:

package com.test.bean;

import java.util.Date;

public class User {

    /**
     * CREATE TABLE `user` (
      `u_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
      `u_username` VARCHAR(64) NOT NULL COMMENT '用户名',
      `u_password` VARCHAR(64) NOT NULL COMMENT '用户密码',
      `u_sex` VARCHAR(16) DEFAULT NULL COMMENT '用户性别',
      `u_createTime` DATETIME DEFAULT NULL COMMENT '用户创建时间',
      `u_cid` INT(11) NOT NULL COMMENT '用户国家id',
     */
    
    private Integer u_id;
    private String u_username;
    private String u_password;
    private String u_sex;
    private Date u_createTime;
    private Integer u_cid;
    
    public Integer getU_id() {
        return u_id;
    }
    public void setU_id(Integer u_id) {
        this.u_id = u_id;
    }
    public String getU_username() {
        return u_username;
    }
    public void setU_username(String u_username) {
        this.u_username = u_username;
    }
    public String getU_password() {
        return u_password;
    }
    public void setU_password(String u_password) {
        this.u_password = u_password;
    }
    public String getU_sex() {
        return u_sex;
    }
    public void setU_sex(String u_sex) {
        this.u_sex = u_sex;
    }
    public Date getU_createTime() {
        return u_createTime;
    }
    public void setU_createTime(Date u_createTime) {
        this.u_createTime = u_createTime;
    }
    public Integer getU_cid() {
        return u_cid;
    }
    public void setU_cid(Integer u_cid) {
        this.u_cid = u_cid;
    }
    @Override
    public String toString() {
        return "User [u_id=" + u_id + ", u_username=" + u_username + ", u_password=" + u_password + ", u_sex=" + u_sex
                + ", u_createTime=" + u_createTime + ", u_cid=" + u_cid + "]";
    }
}

UserDAO.java:

package com.test.dao;

import com.test.bean.User;

public interface UserDao {
    
    //根据id查询用户
    public User getUserById(Integer id);
    
}

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="UserMapper">
    
    <!-- 根据id查询用户 -->
    <select id="selectUserById" parameterType="Integer" resultType="com.test.bean.User">
         select * from user where u_id = #{id}
    </select>
</mapper>

UserDaoImpl.java:

package com.test.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.test.bean.User;

public class UserDaoImpl implements UserDao {
    //sqlSession工厂
    private SqlSessionFactory ssf;
    
    //通过构造器给ssf 赋值
    public UserDaoImpl(SqlSessionFactory ssf) {
        this.ssf = ssf;
    }


    public User getUserById(Integer id) {
        //生产一个sqlSession
        SqlSession session = ssf.openSession();
        //操作数据库
        return session.selectOne("UserMapper.selectUserById", id);
    }
}

UserDaoTest.java:

package com.test.test;


import java.io.IOException;
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.Test;

import com.test.bean.User;
import com.test.dao.UserDao;
import com.test.dao.UserDaoImpl;

public class UserDaoTest {
    
    //sqlSession工厂
    private static SqlSessionFactory ssf;
    
    static {
        String resource = "sqlMapConfig.xml";
        InputStream in;
        try {
            in = Resources.getResourceAsStream(resource );
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
             ssf = ssfb.build(in);
             in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void DaoTest() {
        UserDao dao = new UserDaoImpl(ssf);
        User user = dao.getUserById(1);
        System.out.println(user);
    }
    
}

进行测试。

测试结果

2 Mapper动态代理开发

复制上面的项目,命名为HelloMyBatisMapper。删除dao包及包内所有文件、com.test/test/UserDaoTest.java,新建动态代理接口类mapper/UserMapper.java、测试类com.test/test/MapperTest.java,整理项目目录如下所示:

项目目录

mapper动态代理开发四大原则 + 一个注意
1、接口方法名需要与mapper.xml的要调用的sql语句的id一致
2、接口的形参类型需要与mapper.xml parameterType 一致
3、接口的返回值需要与mapper.xml resultType一致
4、mapper.xml 中namespace要与接口的全包名一致
5、注意mapper动态代理开发中,动态代理对象调用,根据返回值类型来自动选择,如果返回的是list则调用的是selectList方法,如果返回的是单个值或者是对象那么调用的是selectOne方法。(selectOne: 查询一条记录、selectList: 查询一条或多条记录。)

一个小tips:在UserMapper.xml中选中全包名+ctrl,可以检查链接是否正确。

给出相关代码。
UserMapper.java:

package com.test.mapper;

import com.test.bean.User;

public interface UserMapper {
    //mapper动态代理开发四大原则 + 一个注意
    //1、接口方法名需要与mapper.xml的要调用的sql语句的id一致
    //2、接口的形参类型需要与mapper.xml parameterType 一致
    //3、接口的返回值需要与mapper.xml resultType一致
    //4、mapper.xml 中namespace要与接口的全包名一致
    //5、注意mapper动态代理开发中,根据返回值类型来自动选择
    
    //通过id查询一个用户
    public User selectUserById(Integer id);
}

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">
<!-- 注意 namespace的修改 -->
<mapper namespace="com.test.mapper.UserMapper">
    
    <!-- 根据id查询用户 -->
    <select id="selectUserById" parameterType="Integer" resultType="com.test.bean.User">
         select * from user where u_id = #{id}
    </select>

</mapper>

MapperTest.java:

package com.test.test;

import java.io.IOException;
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.Test;

import com.test.bean.User;
import com.test.mapper.UserMapper;

public class MapperTest {
    
    @Test
    public void Test1() throws IOException {
        String resource = "sqlMapConfig.xml";
        //读取配置文件
        InputStream in = Resources.getResourceAsStream(resource );
        
        //创建sqlSessionfactory
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(in);
         
        //生产一个sqlSession
        SqlSession session = ssf.openSession();
        
        UserMapper mapper = session.getMapper(UserMapper.class);
        
        User user = mapper.selectUserById(1);
        System.out.println(user);
        
    }
}

进行测试。

测试结果

可以看出,使用Mapper动态代理提高了开发效率,推荐使用。

上一篇下一篇

猜你喜欢

热点阅读