github同步更新
博客同步更新
简书同步更新
项目地址:传送门
1.1、使用IDEA新建一个项目,项目结构如下:
其中用到的pox.xml内容:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.shigroupId>
<artifactId>spring4-mybatis3artifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>spring4-mybatis3name>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.1.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.5version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.2-b01version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.34version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.12version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
<build>
<finalName>spring4-mybatis3finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.2version>
<configuration>
<verbose>trueverbose>
<overwrite>trueoverwrite>
configuration>
plugin>
plugins>
build>
project>
pox.xml主要分两大部分,上面的10行-111行主要是为了添加项目jar包依赖,下面的114行-124行主要是为了集成generator插件(可以通过映射数据库表字段生成实体类);
添加pox.xml文件只有,在IDEA的右侧打开Maven Projects模块,点击左上方的刷新控件,刷新整个项目。
1.2、右键项目,选择open module setting,点击左上角的+符号,选择maven,添加generator插件
2.1 在MySQL数据库中执行如下SQL语句:
Create DATABASE spring4_mybatis3;
USE spring4_mybatis3;
DROP TABLE IF EXISTS user;
CREATE TABLE user (
user_id char(32) NOT NULL,
user_name varchar(30) DEFAULT NULL,
user_birthday date DEFAULT NULL,
user_salary double DEFAULT NULL,
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.2 手动创建【src/main/resources】、【src/main/java】、【src/test/resources】、【src/test/java】这几个source folder,如下图所示:
2.3 在main/resources中添加generatorConfig.xml文件
<generatorConfiguration>
<classPathEntry location="D:\Java\IdeaProjects\MyBatis\lib\mysql-connector-java-5.1.7-bin.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/spring4_mybatis3" userId="root" password="123456">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator targetPackage="com.shi.domain" targetProject="D:\Java\IdeaProjects\MyBatis\MyBatis_08\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="com.shi.mapping" targetProject="D:\Java\IdeaProjects\MyBatis\MyBatis_08\src\main\java">
<property name="enableSubPackages" value="true" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.shi.dao" targetProject="D:\Java\IdeaProjects\MyBatis\MyBatis_08\src\main\java">
<property name="enableSubPackages" value="true" />
javaClientGenerator>
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
context>
generatorConfiguration>
运行之前配置好的generator_08插件,会在项目的java目录中根据创建好的数据库表生成MyBatis的表对应的实体类:
生成的代码和映射文件一般都不用改,可以直接应用到项目当中。下面我们看一眼由generator插件生成的代码和映射文件:
生成的UserMapper是一个接口,里面定义了一些操作user表的增删改查方法。
package com.shi.dao;
import com.shi.domain.User;
public interface UserMapper {
int deleteByPrimaryKey(String userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
User类是user表的对应的实体类,User类中定义的属性和user表中的字段一一对应。
package com.shi.domain;
import java.util.Date;
public class User {
private String userId;
private String userName;
private Date userBirthday;
private Double userSalary;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public Date getUserBirthday() {
return userBirthday;
}
public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}
public Double getUserSalary() {
return userSalary;
}
public void setUserSalary(Double userSalary) {
this.userSalary = userSalary;
}
}
<mapper namespace="com.shi.dao.UserMapper" >
<resultMap id="BaseResultMap" type="com.shi.domain.User" >
<id column="user_id" property="userId" jdbcType="CHAR" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="user_birthday" property="userBirthday" jdbcType="DATE" />
<result column="user_salary" property="userSalary" jdbcType="DOUBLE" />
resultMap>
<sql id="Base_Column_List" >
user_id, user_name, user_birthday, user_salary
sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from user
where user_id = #{userId,jdbcType=CHAR}
select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from user
where user_id = #{userId,jdbcType=CHAR}
delete>
<insert id="insert" parameterType="com.shi.domain.User" >
insert into user (user_id, user_name, user_birthday,
user_salary)
values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE},
#{userSalary,jdbcType=DOUBLE})
insert>
<insert id="insertSelective" parameterType="com.shi.domain.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userId != null" >
user_id,
if>
<if test="userName != null" >
user_name,
if>
<if test="userBirthday != null" >
user_birthday,
if>
<if test="userSalary != null" >
user_salary,
if>
trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userId != null" >
#{userId,jdbcType=CHAR},
if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
if>
<if test="userBirthday != null" >
#{userBirthday,jdbcType=DATE},
if>
<if test="userSalary != null" >
#{userSalary,jdbcType=DOUBLE},
if>
trim>
insert>
<update id="updateByPrimaryKeySelective" parameterType="com.shi.domain.User" >
update user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
if>
<if test="userBirthday != null" >
user_birthday = #{userBirthday,jdbcType=DATE},
if>
<if test="userSalary != null" >
user_salary = #{userSalary,jdbcType=DOUBLE},
if>
set>
where user_id = #{userId,jdbcType=CHAR}
update>
<update id="updateByPrimaryKey" parameterType="com.shi.domain.User" >
update user
set user_name = #{userName,jdbcType=VARCHAR},
user_birthday = #{userBirthday,jdbcType=DATE},
user_salary = #{userSalary,jdbcType=DOUBLE}
where user_id = #{userId,jdbcType=CHAR}
update>
mapper>
UserMapper.xml这个文件的内容是编写操作user表的SQL语句,重点说一下UserMapper.xml配置中需要注意的几个小细节问题:
1、UserMapper.xml的标签的namespace必须是UserMapper接口的全类名,
2、UserMapper.xml的定义操作数据库的这些标签的id属性的值必须和UserMapper接口定义的方法名一致,如下图所示:
#### 四、Spring与MyBatis整合
4.1、添加Service对象
1、在src/main/java目录下创建一个com.shi.service包,然后在com.shi.service包创建一个UserServiceI接口,如下所示:
package com.shi.service;
import com.shi.domain.User;
public interface UserServiceI {
/**
* 添加用户
* @param user
*/
void addUser(User user);
/**
* 根据用户id获取用户
* @param userId
* @return
*/
User getUserById(String userId);
}
2、在src/main/java目录下创建一个com.shi.service.impl包,然后在com.shi.service.impl包创建一个针对UserServiceI接口的实现类:UserServiceImpl,如下所示:
package com.shi.service.impl;
import com.shi.dao.UserMapper;
import com.shi.domain.User;
import com.shi.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author AFinalStone
* 使用@Service注解将UserServiceImpl类标注为一个service
* service的id是userService
*/
@Service("userService")
public class UserServiceImpl implements UserServiceI {
/**
* 使用@Autowired注解标注userMapper变量,
* 当需要使用UserMapper时,Spring就会自动注入UserMapper
*/
@Autowired
private UserMapper userMapper;//注入dao
public void addUser(User user) {
userMapper.insert(user);
}
public User getUserById(String userId) {
return userMapper.selectByPrimaryKey(userId);
}
}
4.2、编写相关配置文件
1、dbconfig.properties
在src/main/resources目录下创建一个dbconfig.properties文件,用于编写连接MySQL数据库的相关信息,dbconfig.properties的内容如下:
“`properties
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=123456
2、spring.xml(spring框架的配置文件)
在src/main/resources目录下创建一个spring.xml文件,spring.xml文件就是针对Spring框架编写的核心配置文件,我们的spring.xml文件的配置非常简单,就两个配置。
spring.xml的内容如下:
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:property-placeholder location="classpath:dbconfig.properties" />
<context:component-scan base-package="com.shi.service" />
beans>
<div class="se-preview-section-delimiter">div>
3、spring-mybatis.xml(spring与mybatis整合的配置文件)
在src/main/resources目录下创建一个spring-mybatis.xml文件,spring-mybatis.xml文件就是针对Spring框架与Mybatis框架整合编写的配置文件,spring-mybatis.xml的内容如下:
<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="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="initialSize" value="0" />
<property name="maxActive" value="20" />
<property name="maxIdle" value="20" />
<property name="minIdle" value="0" />
<property name="maxWait" value="60000" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="25200000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1800" />
<property name="logAbandoned" value="true" />
<property name="filters" value="mergeStat" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/shi/mapping/UserMapper.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shi.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.shi.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
aop:config>
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>com.shi.service.*value>
list>
property>
bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
aop:config>
beans>
注意:需要我们把pom.xml依赖添加到项目当中
4.3 进行单元测试
经过以上两个步骤,spring4与mybatis3的整合算是全部完成了。接下来我们要做的工作就算进行单元测试,测试一下spring4与mybatis3的整合是否成功。
1、在src/main/java目录下创建一个com.shi.service包,然后在com.shi.service包创建一个UserServiceI接口,如下所示: