0.项目环境:
使用maven导入工程所需jar包
Spring 4.3.21.RELEASE
Mybatis 3.4.6
MySQL 8.0.13
druid 1.1.12
项目的整体结构如下
1.创建一个maven java项目,根据需求填写pom.xml配置文件,以及jdbc.properties和log4j.properties
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.spring</groupId>
<artifactId>spring_mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<junit.version>4.12</junit.version>
<spring.version>4.3.21.RELEASE</spring.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>1.3.1</mybatis.spring.version>
<mysql.version>8.0.13</mysql.version>
<commons.logging.version>1.1.3</commons.logging.version>
<druid.version>1.1.12</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons.logging.version}</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<type>bundle</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--因为idea不会编译src目录下面的xml文件,所以要在pom文件内添加-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai
log4j.properties
### set log levels ###
#trace debug info warn error fetal
log4j.rootLogger = debug,stdout,log
#, log, index, D, I, W, E
### print log to console ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d %p [%c] - <%m>%n
### create log to file ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = /logs/log.log
log4j.appender.log.Append = true
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern= %d %p [%c] - <%m>%n
# Control logging for other open source packages
log4j.logger.net.sf.navigator=ERROR
log4j.logger.net.sf.acegisecurity=WARN
log4j.logger.net.sf.acegisecurity.intercept.event.LoggerListener=WARN
log4j.logger.org.apache.commons=ERROR
log4j.logger.org.apache.struts=WARN
log4j.logger.org.displaytag=ERROR
log4j.logger.org.springframework=WARN
log4j.logger.org.apache.velocity=WARN
# SqlMap logging configuration...
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.db=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.sqlmap.engine.cache.CacheModel=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientImpl=debug
log4j.logger.com.ibatis.sqlmap.engine.builder.xml.SqlMapParser=debug
log4j.logger.com.ibatis.common.util.StopWatch=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=error
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=error
2.数据库内表student 创建实体类
数据库内sql语句
CREATE TABLE student (
id int(11) PRIMARY KEY AUTO_INCREMENT,
name varchar(10),
sex varchar(2),
addr varchar(10),
) ;
INSERT INTO `student` VALUES (1, '老王', '女', '北京');
INSERT INTO `student` VALUES (2, '小李', '男', '上海');
INSERT INTO `student` VALUES (3, '小刘', '女', '深圳');
INSERT INTO `student` VALUES (4, '小张', '男', '南京');
INSERT INTO `student` VALUES (5, '老王', '女', '哈尔滨');
INSERT INTO `student` VALUES (6, '老赵', '男', '沈阳');
INSERT INTO `student` VALUES (7, '老李', '女', '大连');
实体类Student
package cn.spring.bean;
import org.springframework.stereotype.Component;
@Component
public class Student {
private Integer id;
private String name;
private String sex;
private String addr;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr == null ? null : addr.trim();
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
3.分层设计controller以及service、dao内接口
StudentSeverlet.java
package cn.spring.controller;
import cn.spring.bean.Student;
import cn.spring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class StudentSeverlet {
@Autowired
private StudentService studentService;
public int deleteByPrimaryKey(Integer id) {
return studentService.deleteByPrimaryKey(id);
}
public int insert(Student record) {
return studentService.insert(record);
}
public int insertSelective(Student record) {
return studentService.insertSelective(record);
}
public Student selectByPrimaryKey(Integer id) {
return studentService.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(Student record) {
return studentService.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Student record) {
return studentService.updateByPrimaryKey(record);
}
}
StudentService .java
package cn.spring.service;
import cn.spring.bean.Student;
public interface StudentService {
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
StudentDao .java
package cn.spring.dao;
import cn.spring.bean.Student;
public interface StudentDao {
int deleteByPrimaryKey(Integer id);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
4.根据需求创建StudentDao.xml
也可以利用mybatis反向工程创建
StudentDao.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.spring.dao.StudentDao" >
<resultMap id="BaseResultMap" type="student" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="addr" property="addr" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, name, sex, addr
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from student
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="student" >
insert into student (id, name, sex,
addr)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR},
#{addr,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="student" >
insert into student
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="sex != null" >
sex,
</if>
<if test="addr != null" >
addr,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
#{sex,jdbcType=VARCHAR},
</if>
<if test="addr != null" >
#{addr,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="student" >
update student
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="addr != null" >
addr = #{addr,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="student" >
update student
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
addr = #{addr,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
5.创建service层实现类
StudentServiceImpl
package cn.spring.service.impl;
import cn.spring.bean.Student;
import cn.spring.dao.StudentDao;
import cn.spring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
public int deleteByPrimaryKey(Integer id) {
return studentDao.deleteByPrimaryKey(id);
}
public int insert(Student record) {
return studentDao.insert(record);
}
public int insertSelective(Student record) {
return studentDao.insertSelective(record);
}
public Student selectByPrimaryKey(Integer id) {
return studentDao.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(Student record) {
return studentDao.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(Student record) {
return studentDao.updateByPrimaryKey(record);
}
}
6.填写spring和mybatis的配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据库信息-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="maxActive" value="20"/>
<property name="initialSize" value="1"/>
<property name="minIdle" value="1"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxOpenPreparedStatements" value="20"/>
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="validationQuery" value="select 1"/>
</bean>
<!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatisConfig.xml"/>
</bean>
<!-- 配置mapper代理对象 -->
<bean id="studentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.spring.dao.StudentDao"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!-- 使用扫描包的形式来创建mapper代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.spring.dao"></property>
</bean>
<!--基于classpath扫描方式-->
<context:component-scan base-package="cn.spring"/>
</beans>
mybatisConfig.xml
<?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.spring.bean"/>
</typeAliases>
<!--加载映射文件-->
<!--在applicationContext.xml中使用的是扫描包的形式来创建mapper代理对象,这里不用再次指定-->
<!--<mappers>
<package name="cn.spring.dao"/>
</mappers>-->
</configuration>
7.写一个测试程序测试,以查询方法为例
TestSpring_Mybatis.java
import cn.spring.bean.Student;
import cn.spring.controller.StudentSeverlet;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring_Mybatis {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentSeverlet studentSeverlet = context.getBean(StudentSeverlet.class);
int id = 1;
// 测试查询方法
Student student = studentSeverlet.selectByPrimaryKey(id);
System.out.println(student);
}
}