##概述
众所周知,目前的java项目几乎离不开Spring框架,而MyBatis又是操作dao层的优秀框架,所以非常有必要有必要学习在Spring框架中集成MyBatis。
下面以一个web项目为例说明在Spring框架中集成MyBatis具体使用。
##准备工作
在使用JDBC连接数据库之前,首先要有数据库,数据库要创建表。我的数据库信息如下:
- 数据库类型:MySql。
- 数据库名字:xia。
- 用户名:root。
- 密码:root.
- 创建数据库表student。
create table student(
id int primary key auto_increment,
name varchar(20),
age int
);
##开发环境
- 操作系统:MACOS。
- 开发工具:IntelliJ IDEA。
- Java版本:jdk1.8。
- 使用maven管理jar包。
##正式开发
开发完成后的项目目录结构如下:
一,在pom.xml文件中引入需要jar的依赖
<!--springmvc依赖,里面包含spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- 指定jackson依赖的版本 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<!-- 添加spring-jdbc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis与spring的整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
二,创建model类
在com.honor.springmybatis.model包中创建StudentModel类,字段与student表对应。代码如下:
public class StudentModel {
private int id;
private String name;
private int age;
//get和set方法略
}
三,创建Mapper文件
在resources/mapper目录下创建student表对应的mapper文件,起名为studentMapper.xml。在该文件中写sql语句,内容如下:
<?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文件的唯一标识,在同一个项目中不能重复-->
<mapper namespace="student">
<!--定义resultMap-->
<resultMap id="BaseResultMap" type="studentModel">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="age" jdbcType="VARCHAR" property="age"/>
</resultMap>
<!--将所有字段定义为一个sql片段-->
<sql id="Base_Column_List">
id, name, age
</sql>
<!--所有字段的动态where,供查询list和查询数量使用。-->
<sql id="Base_Where">
<where>
<if test="name!=null and name.length()>0">
AND name=#{name}
</if>
<if test="age > 0">
AND age=#{age}
</if>
</where>
</sql>
<!--插入数据,并返回id-->
<insert id="insert" parameterType="studentModel" useGeneratedKeys="true" keyProperty="id">
insert into student (name,age)
values(#{name,jdbcType=VARCHAR},#{age,jdbcType=INTEGER})
</insert>
<!--根据id查找一条数据-->
<select id="queryOne" parameterType="int" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from student WHERE id=#{id}
</select>
<!--根据name和age查找数据集合-->
<select id="queryList" parameterType="studentModel" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from student
<include refid="Base_Where"/>
</select>
<!--查询梳理-->
<select id="queryCount" parameterType="studentModel" resultType="int">
SELECT COUNT(*) FROM student
<include refid="Base_Where"/>
</select>
<!--根据id更新-->
<update id="update" parameterType="studentModel">
UPDATE student
<set>
<if test="name!=null and name.length()>0">
name= #{name},
</if>
<if test="age>0">
age = #{age},
</if>
</set>
WHERE id = #{id}
</update>
<!--根据id删除-->
<delete id="delete" parameterType="studentModel">
DELETE from student WHERE id = #{id}
</delete>
</mapper>
四,创建MyBatis的配置文件sqlMapConfig.xml
在resources/mapper目录下创建MyBatis框架的配置文件,起名为sqlMapConfig.xml。在该文件中配置mapper文件,声明Model类对应的别名。内容如下:
<?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>
<typeAlias type="com.honor.springmybatis.model.StudentModel" alias="studentModel"/>
</typeAliases>
<!--配置mapper文件-->
<mappers>
<mapper resource="mapper/studentMapper.xml"/>
</mappers>
</configuration>
五,创建数据库参数配置文件config.properties
config.properties文件目录是:/resource/conf。文件内容是:
#数据库参数配置
mysql.driverClassName=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/xia
mysql.username=root
mysql.password=root
六,创建Spring配置文件applicationContext.xml
applicationContext.xml文件目录是:/resource/conf。文件内容是:
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 配置包扫描器 -->
<context:component-scan base-package="com.honor.springmybatis.dao"/>
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:conf/config.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource"
destroy-method="forceCloseAll">
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
<property name="driver" value="${mysql.driverClassName}" />
</bean>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:conf/sqlMapConfig.xml" />
</bean>
<!--得到sqlSessionTemplate对象-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="SIMPLE" />
</bean>
</beans>
七,创建springmvc配置文件springmvc.xml
springmvc.xml文件目录是:/resource/conf。文件内容是:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.honor.springmybatis.controller" />
<!--适配器注解驱动-->
<mvc:annotation-driven />
</beans>
八,配置web.xml文件
web.xml文件是javaweb项目的配置文件,文件中的内容是:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
九,创建dao类
在dao类分别实现了增删改查操作,具体参见代码:
package com.honor.springmybatis.dao;
import com.honor.springmybatis.model.StudentModel;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by xiagz
* Date:2018/9/8
*/
@Repository
public class StudentDao {
@Autowired
SqlSessionTemplate sqlSessionTemplate;
//插入
public int insert(StudentModel student) {
sqlSessionTemplate.insert("student.insert",student);
return student.getId();
}
//更新
public int update(StudentModel student) {
sqlSessionTemplate.update("student.update",student);
return 0;
}
//删除
public int delete(int id) {
sqlSessionTemplate.delete("student.delete",id);
return 0;
}
//根据id查找一个对象
public StudentModel queryOne(int id) {
StudentModel studentModel = sqlSessionTemplate.selectOne("student.queryOne",id);
return studentModel;
}
//查找集合
public List<StudentModel> queryList(StudentModel student) {
List<StudentModel> studentModelList = sqlSessionTemplate.selectList("student.queryList",student);
return studentModelList;
}
//查找数量
public int queryCount(StudentModel student) {
int count = sqlSessionTemplate.selectOne("student.queryCount",student);
return count;
}
}
十,测试
此时使用controller提供接口测试,代码如下:
@Controller
public class StudentController {
@Autowired
StudentDao studentDao;
@RequestMapping("/get.do")
public @ResponseBody
StudentModel get(){
return studentDao.queryOne(5);
}
}
然后启动项目,访问该接口,返回值如下:
大功告成。
##总结
以上以一个JavaWeb项目的示例说明Spring与MyBatis框架的结合使用。以上代码较多,解释较少,下面总体解释如下:
- sqlMapConfig.xml是MyBatis框架的配置文件,用法与单独使用MyBatis框架类似。
- applicationContext.xml是Spring框架的配置文件,这个文件中加载数据库参数配置DataSource对象,然后又加载sqlMapConfig.xml文件配置sqlSessionFactory对象,根据sqlSessionFactory对象配置sqlSessionTemplate对象,在dao中使用sqlSessionTemplate操作mapper文件中的sql语句。
- springmvc.xml文件是springmvc的配置文件,它与mybatis框架的使用没有多大关系。
- web.xml文件是JavaWeb项目的核心文件,里面加载applicationContext.xml和springmvc.xml,这些都是Spring框架的用法,与MyBatis框架关系不大。