Spring框架(3)整合MyBatis框架

基本整合方式

Spring框架整合其他框架的本质其实就是把其他框架交给Spring框架管理。Spring框架通过IOC、AOP等机制实现与其他框架的连接,最终建立一个低耦合的应用架构,这大大增强了系统的灵活性,便于功能扩展。

整合思路梳理

        MyBatis框架主要是通过SqlSession实例实现对数据的操作,而SqlSession实例是通过SqlSessionFactory创建的,SqlSessionFactory实例又是由SqlSessionFactoryBuilder依据MyBatis配置文件中的数据源、SQL映射文件等信息构建的。

        Spring框架整合MyBatis框架的主要流程包括添加依赖jar包、编写MyBatis配置文件及在Spring框架配置文件中做整合配置三个方面的操作。

整合所需的依赖及配置

maven依赖


    
      commons-dbcp
      commons-dbcp
      1.4
    
    
      commons-pool
      commons-pool
      1.6
    

    
      org.mybatis
      mybatis-spring
      2.0.6
    

    
    
      org.springframework
      spring-jdbc
      5.2.2.RELEASE
    

    
      org.springframework
      spring-tx
      5.2.2.RELEASE
    

首先我们先完成MyBatis框架配置、实体类、映射接口以及映射文件

示例代码

实体类

public class SysUser implements Serializable {

    private static final long serialVersionUID = 42L;

    private Integer id;             // id
    private String account;         // 用户编码
    private String realName;        // 用户名称
    private String password;        // 用户密码
    private Integer sex;            // 性别
    private Date birthday;          // 出生日期
    private String phone;           // 电话
    private String address;         // 地址
    private Integer roleId;         // 用户角色ID
    private Integer createdUserId;  // 创建者
    private Date createdTime;       // 创建时间
    private Integer updatedUserId;  // 更新者
    private Date updatedTime;       // 更新时间

    private Integer age;            // 年龄
    private String roleName;        // 角色名称

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public Integer getCreatedUserId() {
        return createdUserId;
    }

    public void setCreatedUserId(Integer createdUserId) {
        this.createdUserId = createdUserId;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    public Integer getUpdatedUserId() {
        return updatedUserId;
    }

    public void setUpdatedUserId(Integer updatedUserId) {
        this.updatedUserId = updatedUserId;
    }

    public Date getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(Date updatedTime) {
        this.updatedTime = updatedTime;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

映射接口

public interface SysUserMapper {

    List selectSysUserList(SysUser sysUser);

    /**
     * 保存用户
     * @param sysUser
     * @return
     */
    public int add(SysUser sysUser);
}

SQL映射文件




    
    
        
    
    
    

    
        insert into t_sys_user (account,realName,password,sex,birthday,phone,address,roleId,createdUserId,createdTime)
        values (#{account},#{realName},#{password},#{sex},#{birthday},#{phone},#{address},#{roleId},#{createdUserId},#{createdTime})
    
  

MyBatis核心配置文件






    
    
        
        
    
    
        
    

使用Spring配置文件配置数据源

    
        
        
        
        
    

通过Spring配置文件创建SqlSessionFactory


    
        
        
        
        
        
        
            
                classpath:mapper/*.xml
            
        
    

通过SqlSessionTemplate操作数据库

public class SysUserMapperImpl implements SysUserMapper {

    private SqlSessionTemplate sqlSession;
    @Override
    public List selectSysUserList(SysUser sysUser) {
        return sqlSession.selectList("dao.sysUser.SysUserMapper.selectSysUserList",sysUser);
    }

    /**
     * 保存用户
     *
     * @param sysUser
     * @return
     */
    @Override
    public int add(SysUser sysUser) {
        return sqlSession.insert("dao.sysUser.SysUserMapper.add",sysUser);
    }


    public SqlSessionTemplate getSqlSession(){
        return sqlSession;
    }

    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession = sqlSession;
    }
}

通过Spring配置文件对SqlSessionTemplate进行注入,配置文件如下

    
    
        
    

编写相关业务代码以及Spring配置文件中的配置信息

SysUserService类中的关键代码

public interface SysUserService {

    List getList(SysUser sysUser);

    /**
     * 保存用户
     * @param sysUser
     * @return
     */
    public boolean add(SysUser sysUser);
}

SysUserServiceImpl类中的关键代码

public class SysUserServiceImpl implements SysUserService {

    private SysUserMapper sysUserMapper;
    @Override
    public List getList(SysUser sysUser) {
        try {
            return sysUserMapper.selectSysUserList(sysUser);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 保存用户
     *
     * @param sysUser
     * @return
     */
    @Override
    public boolean add(SysUser sysUser) {
        boolean result = false;
        try {
            if (sysUserMapper.add(sysUser) == 1){
                result = true;
                // 测试事务回滚时,打开注释
                throw new RuntimeException();
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    public SysUserMapper getSysUserMapper() {
        return sysUserMapper;
    }

    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }
}

Spring配置文件中关键代码

    
    
        
    

通过以上配置讲SysUserMapper注入SysUserService中。编写测试代码

public class SysUserTest {

    private Logger logger = LogManager.getLogger(SysUserTest.class);

    @Before
    public void setUp() throws Exception{}

    @Test
    public void testGetUserList(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SysUserService userService = (SysUserService) ctx.getBean("sysUserService");
        List userList = new ArrayList();
        SysUser userCondition = new SysUser();
        userCondition.setRealName("赵");
        userCondition.setRoleId(2);
        userList = userService.getList(userCondition);

        for (SysUser userResult : userList) {
            logger.debug("testGetUserList account:"
                    + userResult.getAccount() + " and realName:"
                    + userResult.getRealName() + " and roleId:"
                    + userResult.getRoleId() + " and roleName:"
                    + userResult.getRoleName() + " and address:"
                    + userResult.getAddress()
            );
        }
    }


    @Test
    public void testAddUser() throws ParseException{
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        SysUserService userService = (SysUserService) ctx.getBean("sysUserService");

        SysUser user = new SysUser();
        user.setAccount("test002");
        user.setRealName("测试用户002");
        user.setPassword("1234567");
        Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse("2003-10-22");
        user.setBirthday(birthday);
        user.setAddress("测试地址abc");
        user.setSex(1);
        user.setPhone("13411110000");
        user.setRoleId(1);
        user.setCreatedUserId(1);
        user.setCreatedTime(new Date());

        boolean result = userService.add(user);
        logger.debug("testAdd result:" + result);
    }
}

使用SqlSesssionDaoSupport简化编码

SysUserMapperImpl类中的关键代码

public class SysUserMapperImpl extends SqlSessionDaoSupport implements SysUserMapper {

    @Override
    public List selectSysUserList(SysUser sysUser) {
this.getSqlSession().selectList("dao.sysUser.SysUserMapper.selectSysUserList",sysUser);
    }

    /**
     * 保存用户
     *
     * @param sysUser
     * @return
     */
    @Override
    public int add(SysUser sysUser) {
        return this.getSqlSession().insert("dao.sysUser.SysUserMapper.add",sysUser);
    }
}

Spring配置文件中的关键代码

    
        
    

SqlSessionDaoSupport类中提供了setSqlSessionFactory()方法用来注入SqlSessionFactory并创建SqlSessionTemplate实例,同时还提供getSqlSession()方法将创建好的SqlSessionTemplate实例返回。这样Dao实现类只需要继承SqlSessionDaoSupport类即可通过getSqlSession()方法活得创建好的SqlSessionTemplate实例,无需额外定义SqlSession属性和setter方法。而Spring配置文件也无需再配置SqlSessionTemplate,只需要通过该Dao对象的setSqlSessionFactory()方法为其注入SqlSessionFactory即可,这一定程度上进一步简化了Dao组件的开发工作。

映射器整合方式

在实例代码中SysUserMapperImpl中主要使用SqlSessionTemplate类实现Dao层的相关操作。但是这种方式不仅需要编写Mapper接口的实现类,还需要使用字符串定义方法的位置,这样不仅代码繁多,还容易出错、不易维护,如果命名空间发生变化,改起来会很麻烦。

在MyBatis中可以使用SqlSession的getMapper(Classtype)方法,根据指定的映射器和映射文件直接生成实现类,大大减少工作量。SqlSessionTemplate类实现了SqlSession接口,所以,其也具备同样的功能,且利用MyBatis-Spring提供的组件可以通过配置的方式直接为业务对象注入映射器实现类,无需额外的编码,对于不包含其他非MyBatis框架工作的数据访问操作,这是首选的做法。

使用MapperFactoryBean注入映射器

Spring配置文件


    
        
        
        
        
        





    

    
        
        
    

使用MapperScannerConfigurer注入映射器

Spring配置文件


    
        
        
        
        
    
    
    
        
    

你可能感兴趣的:(spring,mybatis,java)