二、编码实现

2018-08-30  本文已影响0人  lifeline张

一、示例

需求:
1、实现Spring整合MyBatis
2、使用SqlSessionTemplate实现根据天健(用户名称、角色ID)查询用户列表
分析:
1、配置数据源
2、配置SqlSessionFactoryBean
3、使用SqlSessionTemplate实现数据库的操作
4、编写业务逻辑代码并测试

二、具体实现步骤代码

logger4j配置文件:

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug

######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n


######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n


log4j.logger.com.opensymphony.xwork2=error  

spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
                        useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="41312019"></property>
    </bean>
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:cn/smbms/dao/**/*.xml</value>
            </list>
        </property>
    </bean>

    <!-- 配置SqlSessionTemplate -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean>
    
    <bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"></property>
    </bean>
    
    <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
        <property name="userMapper" ref="userMapper"></property>
    </bean>
</beans>

mybatis配置文件:

<?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>
        <package name="cn.smbms.pojo" />
    </typeAliases>
</configuration>

实体类:

package cn.smbms.pojo;

import java.util.Date;

public class User {
    private Integer id;           // id
    private String  userCode;     // 用户编码
    private String  userName;     // 用户名称
    private String  userPassword; // 用户密码
    private Integer gender;       // 性别
    private Date    birthday;     // 出生日期
    private String  phone;        // 电话
    private String  address;      // 地址
    private Integer userRole;     // 用户角色ID
    private Integer createdBy;    // 创建者
    private Date    creationDate; // 创建时间
    private Integer modifyBy;     // 更新者
    private Date    modifyDate;   // 更新时间
    private String  userRoleName; // 用户角色名称

    public Integer getId() {
        return id;
    }

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

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    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 getUserRole() {
        return userRole;
    }

    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }
}

dao层:
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.smbms.dao.user.UserMapper">
    <!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 -->
    <resultMap type="User" id="userList">
        <result property="id" column="id" />
        <result property="userCode" column="userCode" />
        <result property="userName" column="userName" />
        <result property="phone" column="phone" />
        <result property="birthday" column="birthday" />
        <result property="gender" column="gender" />
        <result property="userRole" column="userRole" />
        <result property="userRoleName" column="roleName" />
    </resultMap>
    <!-- 查询用户列表(参数:对象入参) -->
    <select id="getUserList" resultMap="userList" parameterType="User">
        select u.*,r.roleName from smbms_user u,smbms_role r
        where u.userName like CONCAT ('%',#{userName},'%')
        and u.userRole = #{userRole} and u.userRole = r.id
    </select>
</mapper>
package cn.smbms.dao.user;

import java.util.List;
import cn.smbms.pojo.User;

public interface UserMapper {
    /**
     * 查询用户列表(参数:对象入参)
     * @return
     */
    public List<User> getUserList(User user);
}
package cn.smbms.dao.user;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

import cn.smbms.pojo.User;

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    @Override
    public List<User> getUserList(User user) {
        return sqlSession.selectList(
                "cn.smbms.dao.user.UserMapper.getUserList", user);
    }

    public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

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

}

service层:

package cn.smbms.service.user;

import java.util.List;
import cn.smbms.pojo.User;

public interface UserService {
    public List<User> findUsersWithConditions(User user);
}
package cn.smbms.service.user;

import java.util.List;

import cn.smbms.dao.user.UserMapper;
import cn.smbms.pojo.User;

public class UserServiceImpl implements UserService {
    private UserMapper userMapper;

    @Override
    public List<User> findUsersWithConditions(User user) {
        try {
            return userMapper.getUserList(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }

    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

}

测试类:

package cn.smbms.test.user;

import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;

public class UserTest {

    private Logger logger = Logger.getLogger(UserTest.class);

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testGetUserList() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        List<User> userList = new ArrayList<User>();
        User userCondition = new User();
        userCondition.setUserName("赵");
        userCondition.setUserRole(3);
        userList = userService.findUsersWithConditions(userCondition);

        for (User userResult : userList) {
            logger.debug("testGetUserList userCode: "
                    + userResult.getUserCode() + " and userName: "
                    + userResult.getUserName() + " and userRole: "
                    + userResult.getUserRole() + " and userRoleName: "
                    + userResult.getUserRoleName() + " and address: "
                    + userResult.getAddress());
        }
    }

}

配置步骤:
1、首先把mybatis配置文件中的数据源的信息以及mapper映射文件的信息转移到了spring配置文件中,在spring配置文件中,使用dbcp下面的BasicDatasource类来配置数据源。
2、在spring配置文件中使用SqlSessionFactoryBean来创建SqlSessionFactory。
3、有了SqlSessionFactory对象之后,可以通过这个对象创建SqlSession,SqlSession在spring里面对应的类是SqlSessionTeplate,使用bean标签创建SqlSession对象。
4、有了sqlSession之后,就可以在测试类里面使用sqlsession来调用dao里面的方法来做测试了。

也可以通过继承SqlSessionDaoSupport来获取SqlSession:
UserMapperImpl:

package cn.smbms.dao.user;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import cn.smbms.pojo.User;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
  //  private SqlSessionTemplate sqlSession;

    @Override
    public List<User> getUserList(User user) {
        return this.getSqlSession().selectList(
                "cn.smbms.dao.user.UserMapper.getUserList", user);
    }

   /* public SqlSessionTemplate getSqlSession() {
        return sqlSession;
    }

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

}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
                        useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="41312019"></property>
    </bean>
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:cn/smbms/dao/**/*.xml</value>
            </list>
        </property>
    </bean>

    <!-- 配置SqlSessionTemplate -->
    <!-- <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean> -->
    
    <bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
    <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
        <property name="userMapper" ref="userMapper"></property>
    </bean>
</beans>

注:在继承SqlSessionDaoSupport 的时候,这个类里面存在sqlSessionFactory这个属性,只要这个属性设置了,就能直接调用其getSqlSession方法获取SqlSession,所以在配置文件中传入的是sqlSessionFactory。

上一篇 下一篇

猜你喜欢

热点阅读