Spring整合MyBaytis

Posted 我亦是行人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring整合MyBaytis相关的知识,希望对你有一定的参考价值。

1、准备jar包

A、第一种方式:配置SqlSessionFactoryBean+配置SqlSessionTemplate

a、项目结构

b、applicationContext.xml  带详细注释

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans
 8     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 9     http://www.springframework.org/schema/aop
10     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
11     http://www.springframework.org/schema/tx
12     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
13 
14     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
15         destroy-method="close">
16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
17         <!-- <property name="url">
18             <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?
19                     useUnicode=true&characterEncoding=utf-8]]></value>
20         </property> -->
21         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
22                         useUnicode=true&amp;characterEncoding=utf-8" />
23         <property name="username" value="root" />
24         <property name="password" value="root" />
25     </bean>
26 
27     <!-- 配置SqlSessionFactoryBean --><!-- 为整合应用提供SqlSession对象资源 -->
28     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
29         <!-- 引用数据源组件 -->
30         <property name="dataSource" ref="dataSource" />
31         <!-- 引用MyBatis配置文件中的配置 -->
32         <property name="configLocation" value="classpath:mybatis-config.xml" />
33         <!-- 配置SQL映射文件信息 -->
34         <property name="mapperLocations">
35             <list>
36                 <value>classpath:cn/smbms/dao/*/*.xml</value><!-- 映射文件    之前在mybatis配置文件中-->
37             </list>
38         </property>
39     </bean>
40     
41     <!-- 配置SqlSessionTemplate --><!-- 负责管理MyBatis的SqlSession,调用SQL映射语句,实现对数据库的访问-->
42     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
43         <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /><!-- 整合好的对象资源赋值给SqlSessionTemplate -->
44     </bean>
45     <!-- 配置DAO -->
46     <bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl"><!-- Dao层声明的对象是SqlSessionTemplate来获得SqlSession -->
47         <property name="sqlSession" ref="sqlSessionTemplate" /><!-- 把管理的SqlSession赋值给Dao层set方法 -->
48     </bean>
49     <!-- 配置业务Bean -->
50     <bean id="userService" class="cn.smbms.service.user.UserServiceImpl">
51         <property name="userMapper" ref="userMapper" /><!-- 把Dao层对象赋值给Server层set方法 -->
52     </bean>
53 </beans>
View Code

c、mybatis-config.xml

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3     "http://mybatis.org/dtd/mybatis-3-config.dtd">
4 <configuration>
5     <!--类型别名 -->
6     <typeAliases>
7         <package name="cn.smbms.pojo" />
8     </typeAliases>
9 </configuration>
View Code

d、log4j

 1 log4j.rootLogger=DEBUG,CONSOLE,file
 2 #log4j.rootLogger=ERROR,ROLLING_FILE
 3 log4j.logger.cn.smbms.dao=debug
 4 log4j.logger.com.ibatis=debug 
 5 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
 6 log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
 7 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
 8 log4j.logger.java.sql.Connection=debug 
 9 log4j.logger.java.sql.Statement=debug 
10 log4j.logger.java.sql.PreparedStatement=debug 
11 log4j.logger.java.sql.ResultSet=debug 
12 log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
13 
14 ######################################################################################
15 # Console Appender  \\u65e5\\u5fd7\\u5728\\u63a7\\u5236\\u8f93\\u51fa\\u914d\\u7f6e
16 ######################################################################################
17 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
18 log4j.appender.Threshold=error
19 log4j.appender.CONSOLE.Target=System.out
20 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
21 log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
22 
23 
24 ######################################################################################
25 # DailyRolling File  \\u6bcf\\u5929\\u4ea7\\u751f\\u4e00\\u4e2a\\u65e5\\u5fd7\\u6587\\u4ef6\\uff0c\\u6587\\u4ef6\\u540d\\u683c\\u5f0f:log2009-09-11
26 ######################################################################################
27 log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
28 log4j.appender.file.DatePattern=yyyy-MM-dd
29 log4j.appender.file.File=log.log
30 log4j.appender.file.Append=true
31 log4j.appender.file.Threshold=error
32 log4j.appender.file.layout=org.apache.log4j.PatternLayout
33 log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
34 
35 
36 log4j.logger.com.opensymphony.xwork2=error  
View Code

e、UserMapper.java

 1 package cn.smbms.dao.user;
 2 
 3 import java.util.List;
 4 import cn.smbms.pojo.User;
 5 
 6 public interface UserMapper {
 7     /**
 8      * 查询用户列表(参数:对象入参)
 9      * @return
10      */
11     public List<User> getUserList(User user);
12 }
View Code

f、UserMapperImpl.java

 1 package cn.smbms.dao.user;
 2 
 3 import java.util.List;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.mybatis.spring.SqlSessionTemplate;
 6 
 7 import cn.smbms.pojo.User;
 8 
 9 public class UserMapperImpl implements UserMapper {
10     private SqlSessionTemplate sqlSession;
11 
12     @Override
13     public List<User> getUserList(User user) {
14         return sqlSession.selectList(
15                 "cn.smbms.dao.user.UserMapper.getUserList", user);
16     }
17 
18     public SqlSessionTemplate getSqlSession() {
19         return sqlSession;
20     }
21 
22     public void setSqlSession(SqlSessionTemplate sqlSession) {
23         this.sqlSession = sqlSession;
24     }
25 
26 }
View Code

g、UserMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 <mapper namespace="cn.smbms.dao.user.UserMapper">
 5     <!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 -->
 6     <resultMap type="User" id="userList">
 7         <!-- <result property="id" column="id" />
 8         <result property="userCode" column="userCode" />
 9         <result property="userName" column="userName" />
10         <result property="phone" column="phone" />
11         <result property="birthday" column="birthday" />
12         <result property="gender" column="gender" />
13         <result property="userRole" column="userRole" /> -->
14         <result property="userRoleName" column="roleName" />
15     </resultMap>
16     <!-- 查询用户列表(参数:对象入参) -->
17     <select id="getUserList" resultMap="userList" parameterType="User">
18         select u.*,r.roleName from smbms_user u,smbms_role r
19         where u.userName like CONCAT (\'%\',#{userName},\'%\')
20         and u.userRole = #{userRole} and u.userRole = r.id
21     </select>
22 </mapper>
View Code

h、User.java

  1 package cn.smbms.pojo;
  2 
  3 import java.util.Date;
  4 
  5 public class User {
  6     private Integer id;           // id
  7     private String  userCode;     // 用户编码
  8     private String  userName;     // 用户名称
  9     private String  userPassword; // 用户密码
 10     private Integer gender;       // 性别
 11     private Date    birthday;     // 出生日期
 12     private String  phone;        // 电话
 13     private String  address;      // 地址
 14     private Integer userRole;     // 用户角色ID
 15     private Integer createdBy;    // 创建者
 16     private Date    creationDate; // 创建时间
 17     private Integer modifyBy;     // 更新者
 18     private Date    modifyDate;   // 更新时间
 19     private String  userRoleName; // 用户角色名称
 20 
 21     public Integer getId() {
 22         return id;
 23     }
 24 
 25     public void setId(Integer id) {
 26         this.id = id;
 27     }
 28 
 29     public String getUserCode() {
 30         return userCode;
 31     }
 32 
 33     public void setUserCode(String userCode) {
 34         this.userCode = userCode;
 35     }
 36 
 37     public String getUserName() {
 38         return userName;
 39     }
 40 
 41     public void setUserName(String userName) {
 42         this.userName = userName;
 43     }
 44 
 45     public String getUserPassword() {
 46         return userPassword;
 47     }
 48 
 49     public void setUserPassword(String userPassword) {
 50         this.userPassword = userPassword;
 51     }
 52 
 53     public Integer getGender() {
 54         return gender;
 55     }
 56 
 57     public void setGender(Integer gender) {
 58         this.gender = gender;
 59     }
 60 
 61     public Date getBirthday() {
 62         return birthday;
 63     }
 64 
 65     public void setBirthday(Date birthday) {
 66         this.birthday = birthday;
 67     }
 68 
 69     public String getPhone() {
 70         return phone;
 71     }
 72 
 73     public void setPhone(String phone) {
 74         this.phone = phone;
 75     }
 76 
 77     public String getAddress() {
 78         return address;
 79     }
 80 
 81     public void setAddress(String address) {
 82         this.address = address;
 83     }
 84 
 85     public Integer getUserRole() {
 86         return userRole;
 87     }
 88 
 89     public void setUserRole(Integer userRole) {
 90         this.userRole = userRole;
 91     }
 92 
 93     public Integer getCreatedBy() {
 94         return createdBy;
 95     }
 96 
 97     public void setCreatedBy(Integer createdBy) {
 98         this.createdBy = createdBy;
 99     }
100 
101     public Date getCreationDate() {
102         return creationDate;
103     }
104 
105     public void setCreationDate(Date creationDate) {
106         this.creationDate = creationDate;
107     }
108 
109     public Integer getModifyBy() {
110         return modifyBy;
111     }
112 
113     public void setModifyBy(Integer modifyBy) {
114         this.modifyBy = modifyBy;
115     }
116 
117     public Date getModifyDate() {
118         return modifyDate;
119     }
120 
121     public void setModifyDate(Date modifyDate) {
122         this.modifyDate = modifyDate;
123     }
124 
125     public String getUserRoleName() {
126         return userRoleName;
127     }
128 
129     public void setUserRoleName(String userRoleName) {
130         this.userRoleName = userRoleName;
131     }
132 }
View Code

i、UserService.java

1 package cn.smbms.service.user;
2 
3 import java.util.List;
4 import cn.smbms.pojo.User;
5 
6 public interface UserService {
7     public List<User> findUsersWithConditions(User user);
8 }
View Code

J、UserServiceImpl.java

 1 package cn.smbms.service.user;
 2 
 3 import java.util.List;
 4 
 5 import cn.smbms.dao.user.UserMapper;
 6 import cn.smbms.pojo.User;
 7 
 8 public class UserServiceImpl implements UserService {
 9     private UserMapper userMapper;
10 
11     @Override
12     public List<User> findUsersWithConditions(User user) {
13         try {
14             return userMapper.getUserList(user);
15         } catch (RuntimeException e) {
16             e.printStackTrace();
17             throw e;
18         }
19     }
20 
21     public UserMapper getUserMapper() {
22         return userMapper;
23     }
24 
25     public void setUserMapper(UserMapper userMapper) {
26         this.userMapper = userMapper;
27     }
28 
29 }
View Code

k、test

 

 1 package cn.smbms.test.user;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.apache.log4j.Logger;
 7 import org.junit.Before;
 8 import org.junit.Test;
 9 import org.springframework.context.ApplicationContext;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11 
12 import cn.smbms.pojo.User;
13 import cn.smbms.service.user.UserService;
14 
15 public class UserTest {
16 
17     private Logger logger = Logger.getLogger(UserTest.class);
18 
19     @Before
20     public void setUp() throws Exception {
21     }
22 
23     @Test
24     public void testGetUserList() {
25         ApplicationContext ctx = new ClassPathXmlApplicationContext(
26                 "applicationContext.xml");
27         UserService userService = (UserService) ctx.getBean("userService");
28         List<User> userList = new ArrayList<User>();
29         User userCondition = new User();
30         userCondition.setUserName("赵");
31         userCondition.setUserRole(3);
32         userList = userService.findUsersWithConditions(userCondition);
33 
34         for (User userResult : userList) {
35 //            logger.debug("testGetUserList userCode: "
36 //                    + userResult.getUserCode() + " and userName: "
37 //                    + userResult.getUserName() + " and userRole: "
38 //                    + userResult.getUserRole() + " and userRoleName: "
39 //                    + userResult.getUserRoleName() + " and address: "
40 //                    + userResult.getAddress());
41             System.out.println(userResult.getUserName());
42         }
43     }
44 
45 }
View Code

 

 

 

B、第一种方式:配置SqlSessionFactoryBean+采用数据映射器(MapperFactoryBean)

a、项目结构(dao层少了impl)

b、applicationContext.xml(主要变化在xml文件里)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 7     http://www.springframework.org/schema/aop
 8     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
 9     http://www.springframework.org/schema/tx
10     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
11 
12     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
13         destroy-method="close">
14         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
15 
16         <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?
17                         useUnicode=true&amp;characterEncoding=utf-8" />
18         <property name="username" value="root" />
19         <property name="password" value="root" />
20     </bean>
21 
22     <!-- 配置SqlSessionFactoryBean -->
23     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
24         <!-- 引用数据源组件 -->
25         <property name="dataSource" ref="dataSource" />
26         <!-- 引用MyBatis配置文件中的配置 -->
27         <property name="configLocation" value="classpath:mybatis-config.xml" />
28         <!-- 配置SQL映射文件信息 -->
29         <!-- <property name="mapperLocations">
30             <list>
31                 <value>classpath:cn/smbms/dao/**/*.xml</value>
32             </list>
33         </property> -->
34     </bean>
35     <!-- 配置DAO --><!-- 采用数据映射器(MapperFactoryBean)的方式完成对数据库操作-->
36     <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
37     <!-- 根据Mapper接口获取Mapper对象,它封装了原有的SqlSession.getMapper()功能的实现-->
38         <property name="mapperInterface" value="cn.smbms.dao.user.UserMapper" /><!-- 指定映射器,只能是接口类型 -->
39         <property name="sqlSessionFactory" ref="sqlSessionFactory" />
40     </bean>                                    <!-- 注入SqlSessionFactory以提供SqlSessionTemplate实例 -->    
41     
42     <!-- 配置业务Bean -->
43     <bea

以上是关于Spring整合MyBaytis的主要内容,如果未能解决你的问题,请参考以下文章

spring boot 整合 redis

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Spring整合junit测试

Spring整合junit测试

请教mybatis+spring+atomikos的整合问题

cxf整合spring代码