码迷,mamicode.com
首页 > 编程语言 > 详细

Spring和mybatis的整合

时间:2017-10-22 22:11:34      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:src   实例化   实例   pom   其他   ase   png   doctype   运行   

一、搭建项目开发环境

1. 新建一个maven项目SpringMybatis,项目结构如下:

                                                                               技术分享

说明:

src/main/java 存放java代码和映射文件:

         com.study.springmybatis.dao 存放mapper接口

         com.study.springmybatis.mapper 存放mapper映射文件

         com.study.springmybatis.model 存放pojo类

         com.study.springmybatis.service 存放service接口和对应的实现类

src/test/java存放测试代码

src/main/resources 存放数据库配置文件和xml配置文件

2. 在pom.xml文件引入spring和mybatis相关的依赖,这里用的是阿里的maven远程仓库http://maven.aliyun.com/nexus/content/groups/public/

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4 
  5   <groupId>com.study.springmybatis</groupId>
  6   <artifactId>SpringMybatis</artifactId>
  7   <version>0.0.1-SNAPSHOT</version>
  8   <packaging>jar</packaging>
  9 
 10   <name>SpringMybatis</name>
 11   <url>http://maven.apache.org</url>
 12 
 13   <properties>
 14     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15   </properties>
 16 
 17   <dependencies>
 18     <!-- 添加Spring相关的依赖 begin-->
 19         <dependency>
 20             <groupId>org.springframework</groupId>
 21             <artifactId>spring-core</artifactId>
 22             <version>4.3.12.RELEASE</version>
 23         </dependency>
 24         
 25         <dependency>
 26             <groupId>org.springframework</groupId>
 27             <artifactId>spring-context</artifactId>
 28             <version>4.3.12.RELEASE</version>
 29         </dependency>
 30         
 31         <dependency>
 32             <groupId>org.springframework</groupId>
 33             <artifactId>spring-tx</artifactId>
 34             <version>4.3.12.RELEASE</version>
 35         </dependency>
 36         
 37         <dependency>
 38             <groupId>org.springframework</groupId>
 39             <artifactId>spring-jdbc</artifactId>
 40             <version>4.3.12.RELEASE</version>
 41         </dependency>
 42         
 43         <dependency>
 44             <groupId>org.springframework</groupId>
 45             <artifactId>spring-test</artifactId>
 46             <version>4.3.12.RELEASE</version>
 47         </dependency>
 48         
 49         <dependency>
 50           <groupId>org.springframework</groupId>
 51           <artifactId>spring-aop</artifactId>
 52           <version>4.3.12.RELEASE</version>
 53         </dependency>
 54         
 55         <dependency>
 56           <groupId>org.springframework</groupId>
 57           <artifactId>spring-beans</artifactId>
 58           <version>4.3.12.RELEASE</version>
 59         </dependency>
 60 
 61         <dependency>
 62           <groupId>org.apache.geronimo.bundles</groupId>
 63           <artifactId>aspectjweaver</artifactId>
 64           <version>1.6.8_2</version>
 65         </dependency>
 66    <!-- 添加Spring相关的依赖 end-->
 67          
 68    <!-- 添加mybatis的核心包 begin-->
 69         <dependency>
 70             <groupId>org.mybatis</groupId>
 71             <artifactId>mybatis</artifactId>
 72             <version>3.2.8</version>
 73         </dependency>
 74    <!-- 添加mybatis的核心包 end-->
 75         
 76    <!-- 添加mybatis与Spring整合的核心包 begin -->
 77         <dependency>
 78             <groupId>org.mybatis</groupId>
 79             <artifactId>mybatis-spring</artifactId>
 80             <version>1.2.0</version>
 81         </dependency>
 82    <!-- 添加mybatis与Spring整合的核心包 end -->
 83         
 84    <!--数据库连接相关包 begin  -->
 85         <dependency>
 86           <groupId>org.wisdom-framework</groupId>
 87           <artifactId>mysql-connector-java</artifactId>
 88           <version>5.1.34_1</version>
 89         </dependency>
 90         
 91         <dependency>
 92           <groupId>commons-dbcp</groupId>
 93           <artifactId>commons-dbcp</artifactId>
 94           <version>1.4</version>
 95         </dependency>
 96         
 97         <dependency>
 98           <groupId>commons-pool</groupId>
 99           <artifactId>commons-pool</artifactId>
100           <version>1.6</version>
101         </dependency>
102             
103         <dependency>
104           <groupId>c3p0</groupId>
105           <artifactId>c3p0</artifactId>
106           <version>0.9.1.2</version>
107         </dependency>
108    <!--数据库连接相关包 end  -->
109         
110    <!-- 其他附加包 begin-->
118         <dependency>
119           <groupId>commons-logging</groupId>
120           <artifactId>commons-logging</artifactId>
121           <version>1.1.3</version>
122         </dependency>    
123         
124         <dependency>
125             <groupId>junit</groupId>
126             <artifactId>junit</artifactId>
127             <version>4.12</version>
128             <scope>test</scope>
129         </dependency>
130     <!-- 其他附加包 end-->
131             
132   </dependencies>
133 </project>

二、创建表SQL和使用mybatis逆向工程生成代码

1.建表

1 CREATE TABLE `t_user` (
2   `id` int(11) NOT NULL AUTO_INCREMENT,
3   `username` varchar(30) NOT NULL COMMENT 用户名称,
4   `birthday` date DEFAULT NULL COMMENT 生日,
5   `sex` char(2) DEFAULT NULL COMMENT 性别,
6   `address` varchar(256) DEFAULT NULL COMMENT 地址,
7   PRIMARY KEY (`id`)
8 ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT=用户信息表;

2. 使用mybatis逆向工程生成代码

   mybatis逆向工程能根据数据库的表结构生成对应的mapper映射文件,接口,实体类,具体操作方法可以看我的前一篇文章:mybatis逆向工程,然后修改生成文件的名称为符合java命名规范的名称

3. 生成逆向工程后的代码目录结构如下,这里使用的是spring的注解管理bean

技术分享

   生成的mapper接口UserDao.java代码

 1 package com.study.springmybatis.dao;
 2 
 3 import org.springframework.stereotype.Repository;
 4 
 5 import com.study.springmybatis.model.UserModel;
 6 
 7 /**
 8  * 用户接口
 9  * 
10  * @author lgs
11  *
12  */
13 @Repository("userDao")
14 public interface UserDao {
15     int deleteByPrimaryKey(Integer id);
16 
17     int insert(UserModel record);
18 
19     int insertSelective(UserModel record);
20 
21     UserModel selectByPrimaryKey(Integer id);
22 
23     int updateByPrimaryKeySelective(UserModel record);
24 
25     int updateByPrimaryKey(UserModel record);
26 }

生成的mapper映射文件mapper-user.xml,因为之前对生成的实体和接口做了名称修改,所以这里也要对mapper-user.xml里面的内容做对应的修改,修改后的内容如下

  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 <mapper namespace="com.study.springmybatis.dao.UserDao" >
  4 
  5     <resultMap id="BaseResultMap" type="com.study.springmybatis.model.UserModel" >
  6         <id column="id" property="id" jdbcType="INTEGER" />
  7         <result column="username" property="username" jdbcType="VARCHAR" />
  8         <result column="birthday" property="birthday" jdbcType="DATE" />
  9         <result column="sex" property="sex" jdbcType="CHAR" />
 10         <result column="address" property="address" jdbcType="VARCHAR" />
 11     </resultMap>
 12 
 13     <sql id="Base_Column_List" >
 14         id, username, birthday, sex, address
 15     </sql>
 16 
 17     <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
 18         select 
 19         <include refid="Base_Column_List" />
 20         from t_user
 21         where id = #{id,jdbcType=INTEGER}
 22     </select>
 23 
 24     <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
 25         delete from t_user
 26         where id = #{id,jdbcType=INTEGER}
 27     </delete>
 28 
 29     <insert id="insert" parameterType="com.study.springmybatis.model.UserModel" >
 30         insert into t_user (id, username, birthday, 
 31             sex, address)
 32         values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, 
 33             #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR})
 34     </insert>
 35 
 36     <insert id="insertSelective" parameterType="com.study.springmybatis.model.UserModel" >
 37         insert into t_user
 38         <trim prefix="(" suffix=")" suffixOverrides="," >
 39             <if test="id != null" >
 40                 id,
 41             </if>
 42             <if test="username != null" >
 43                 username,
 44             </if>
 45             <if test="birthday != null" >
 46                 birthday,
 47             </if>
 48             <if test="sex != null" >
 49                 sex,
 50             </if>
 51             <if test="address != null" >
 52                 address,
 53             </if>
 54         </trim>
 55         <trim prefix="values (" suffix=")" suffixOverrides="," >
 56             <if test="id != null" >
 57                 #{id,jdbcType=INTEGER},
 58             </if>
 59             <if test="username != null" >
 60                 #{username,jdbcType=VARCHAR},
 61             </if>
 62             <if test="birthday != null" >
 63                 #{birthday,jdbcType=DATE},
 64             </if>
 65             <if test="sex != null" >
 66                 #{sex,jdbcType=CHAR},
 67             </if>
 68             <if test="address != null" >
 69                 #{address,jdbcType=VARCHAR},
 70             </if>
 71         </trim>
 72     </insert>
 73 
 74     <update id="updateByPrimaryKeySelective" parameterType="com.study.springmybatis.model.UserModel" >
 75         update t_user
 76         <set >
 77             <if test="username != null" >
 78                 username = #{username,jdbcType=VARCHAR},
 79             </if>
 80             <if test="birthday != null" >
 81                 birthday = #{birthday,jdbcType=DATE},
 82             </if>
 83             <if test="sex != null" >
 84                 sex = #{sex,jdbcType=CHAR},
 85             </if>
 86             <if test="address != null" >
 87                 address = #{address,jdbcType=VARCHAR},
 88             </if>
 89         </set>
 90         where id = #{id,jdbcType=INTEGER}
 91     </update>
 92 
 93     <update id="updateByPrimaryKey" parameterType="com.study.springmybatis.model.UserModel" >
 94         update t_user
 95         set username = #{username,jdbcType=VARCHAR},
 96             birthday = #{birthday,jdbcType=DATE},
 97             sex = #{sex,jdbcType=CHAR},
 98             address = #{address,jdbcType=VARCHAR}
 99         where id = #{id,jdbcType=INTEGER}
100     </update>
101 </mapper>

生成的pojo即实体类UserModel.java

 1 package com.study.springmybatis.model;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * 用户信息表
 7  * 
 8  * @author lgs
 9  * 
10  * @date 2017-10-21
11  */
12 public class UserModel {
13     private Integer id;
14 
15     /**
16      * 用户名称
17      */
18     private String username;
19 
20     /**
21      * 生日
22      */
23     private Date birthday;
24 
25     /**
26      * 性别
27      */
28     private String sex;
29 
30     /**
31      * 地址
32      */
33     private String address;
34 
35     public Integer getId() {
36         return id;
37     }
38 
39     public void setId(Integer id) {
40         this.id = id;
41     }
42 
43     public String getUsername() {
44         return username;
45     }
46 
47     public void setUsername(String username) {
48         this.username = username == null ? null : username.trim();
49     }
50 
51     public Date getBirthday() {
52         return birthday;
53     }
54 
55     public void setBirthday(Date birthday) {
56         this.birthday = birthday;
57     }
58 
59     public String getSex() {
60         return sex;
61     }
62 
63     public void setSex(String sex) {
64         this.sex = sex == null ? null : sex.trim();
65     }
66 
67     public String getAddress() {
68         return address;
69     }
70 
71     public void setAddress(String address) {
72         this.address = address == null ? null : address.trim();
73     }
74 }

业务的接口UserServiceI.java和实现类UserService.java

 1 package com.study.springmybatis.service;
 2 
 3 import com.study.springmybatis.model.UserModel;
 4 
 5 /**
 6  * 业务接口
 7  * @author lgs
 8  *
 9  */
10 public interface UserServiceI {
11 
12     /**
13      * 根据用户id获取用户
14      * @param userId
15      * @return
16      */
17     UserModel getUserById(Integer userId);
18 }
 1 package com.study.springmybatis.service;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.study.springmybatis.dao.UserDao;
 8 import com.study.springmybatis.model.UserModel;
 9 
10 /**
11  * 业务实现类
12  * @author lgs
13  *
14  */
15 @Service("userService")
16 public class UserService implements UserServiceI {
17 
18     /**
19      * 使用Resource注解注入userDao实例,
20      * 当需要使用userDao时,Spring就会自动注入UserDao
21      */
22     @Resource
23     private UserDao userDao;
24 
25     public UserModel getUserById(Integer userId) {
26         return userDao.selectByPrimaryKey(userId);
27     }
28 }

三、在src/main/resources目录下编写配置文件

1. 数据库配置dbconfig.properties

1 driver=com.mysql.jdbc.Driver
2 jdbc_url=jdbc:mysql://192.168.152.1:3306/study?characterEncoding=utf-8
3 jdbc_username=root
4 jdbc_password=123456
5 validationQuery=SELECT 1

2. Spring框架的核心配置文件spring.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2  <beans
 3      xmlns="http://www.springframework.org/schema/beans"
 4      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5      xmlns:p="http://www.springframework.org/schema/p"
 6      xmlns:context="http://www.springframework.org/schema/context"
 7      xsi:schemaLocation="http://www.springframework.org/schema/beans
 8      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9      http://www.springframework.org/schema/context
10      http://www.springframework.org/schema/context/spring-context-3.0.xsd
11      ">
12     <!--spring框架的配置文件  -->
13     
14     <!-- 引入dbconfig.properties属性文件 -->
15     <context:property-placeholder location="classpath:dbconfig.properties" />
16     <!-- 自动扫描(自动注入),扫描com.study.springmybatis这个包以及它的子包的所有使用spring注解标注的类 -->
17     <context:component-scan base-package="com.study" />
18 </beans>

3. Spring框架与Mybatis框架整合的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
 3 http://www.springframework.org/schema/beans 
 4 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 5 http://www.springframework.org/schema/tx 
 6 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 7 http://www.springframework.org/schema/aop 
 8 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 9 ">
10    <!--spring与mybatis整合的配置文件  -->
11    
12      <!--配置数据源 -->
13     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
14         destroy-method="close">
15         <property name="driverClassName">
16            <value>${driver}</value>
17         </property>
18         <property name="url">
19             <value>${jdbc_url}</value>
20         </property>
21         <property name="username">
22             <value>${jdbc_username}</value>
23         </property>
24         <property name="password">
25             <value>${jdbc_password}</value>
26         </property>
27         <property name="maxActive" value="100"></property>
28         <property name="maxIdle" value="30"></property>
29         <property name="maxWait" value="500"></property>
30         <property name="defaultAutoCommit" value="true"></property>
31     </bean>
32     
33     <!-- ========================================分隔线========================================= -->
34     
35     <!-- ========================================针对myBatis的配置项============================== -->
36     <!-- 配置sqlSessionFactory -->
37     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
38         <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
39         <property name="dataSource" ref="dataSource" />
40         <!-- 自动扫描com/study/springmybatis/mapper/目录下的所有SQL映射的xml文件, 省掉SqlMapConfig.xml里的手工配置
41         value="com/study/springmybatis/mapper/*.xml"指的是classpath(类路径)下com.study.springmybatis.mapper包中的所有xml文件
42         SQL映射的xml文件位于com.study.springmybatis.mapper包下,这样就可以被自动扫描
43          -->
44         <property name="mapperLocations" value="classpath:com/study/springmybatis/mapper/*.xml" />
45     </bean>
46     <!-- 配置扫描器 -->
47     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
48         <!-- 扫描com.study.springmybatis.dao这个包以及它的子包下的所有映射接口类 -->
49         <property name="basePackage" value="com.study.springmybatis.dao" />
50         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
51     </bean>
52     
53     <!-- ========================================分隔线========================================= -->
54     <!-- 配置Spring的事务管理器 -->
55     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
56         <property name="dataSource" ref="dataSource" />
57     </bean>
58 
59     <!-- 注解方式配置事物 -->
60     <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
61 
62     <!-- 拦截器方式配置事物 -->
63     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
64         <tx:attributes>
65             <tx:method name="add*" propagation="REQUIRED" />
66             <tx:method name="append*" propagation="REQUIRED" />
67             <tx:method name="insert*" propagation="REQUIRED" />
68             <tx:method name="save*" propagation="REQUIRED" />
69             <tx:method name="update*" propagation="REQUIRED" />
70             <tx:method name="modify*" propagation="REQUIRED" />
71             <tx:method name="edit*" propagation="REQUIRED" />
72             <tx:method name="delete*" propagation="REQUIRED" />
73             <tx:method name="remove*" propagation="REQUIRED" />
74             <tx:method name="repair" propagation="REQUIRED" />
75             <tx:method name="delAndRepair" propagation="REQUIRED" />
76 
77             <tx:method name="get*" propagation="SUPPORTS" />
78             <tx:method name="find*" propagation="SUPPORTS" />
79             <tx:method name="load*" propagation="SUPPORTS" />
80             <tx:method name="search*" propagation="SUPPORTS" />
81             <tx:method name="datagrid*" propagation="SUPPORTS" />
82 
83             <tx:method name="*" propagation="SUPPORTS" />
84         </tx:attributes>
85     </tx:advice>
86     <!--Spring事物切面配置  -->
87     <aop:config>
88         <aop:pointcut id="transactionPointcut" expression="execution(* com.study.springmybatis.service.*.*(..))" />
89         <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
90     </aop:config>
91 
92 </beans>

四、在src/test/java编写测试类SpringMyBatisTest,本来测试类是放在src/test/java目录下面的。但是不知道为啥找不到junit的注解@Test,这里就偷了一下懒移到src/main/java目录的com.study.springmybatis.test包下面了

 1 package com.study.springmybatis.test;
 2 
 3 
 4 import javax.annotation.Resource;
 5 
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import com.study.springmybatis.model.UserModel;
12 import com.study.springmybatis.service.UserServiceI;
13 
14 
15 @RunWith(SpringJUnit4ClassRunner.class)
16 //配置了@ContextConfiguration注解并使用该注解的locations属性指明spring和配置文件之后,
17 @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml" })
18 public class SpringMyBatisTest {
19 
20     //注入userService
21     @Resource
22     private UserServiceI userService;
23     
24     
25     @Test
26     public void testGetUserById(){
27         int userId = 1;
28         UserModel user = userService.getUserById(userId);
29         System.out.println("查询到的用户名为:"+user.getUsername());
30     }
31 }

运行测试类的结果为:

 1 十月 22, 2017 3:08:00 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
 2 信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
 3 十月 22, 2017 3:08:00 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
 4 信息: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
 5 十月 22, 2017 3:08:00 下午 org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
 6 信息: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3b6eb2ec, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1e643faf, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6e8dacdf, org.springframework.test.context.transaction.TransactionalTestExecutionListener@7a79be86, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@34ce8af7]
 7 十月 22, 2017 3:08:00 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
 8 信息: Loading XML bean definitions from class path resource [spring.xml]
 9 十月 22, 2017 3:08:00 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
10 信息: Loading XML bean definitions from class path resource [spring-mybatis.xml]
11 十月 22, 2017 3:08:00 下午 org.springframework.context.support.GenericApplicationContext prepareRefresh
12 信息: Refreshing org.springframework.context.support.GenericApplicationContext@5a61f5df: startup date [Sun Oct 22 15:08:00 CST 2017]; root of context hierarchy
13 查询到的用户名为:lgs

五、需要完整工程代码的同学去我的githup上下载https://github.com/leeSmall/SpringMybatis

Spring和mybatis的整合

标签:src   实例化   实例   pom   其他   ase   png   doctype   运行   

原文地址:http://www.cnblogs.com/leeSmall/p/7709983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!