spring boot集成mybatis
1.pom.xml中添加jar包依赖
添加集成mybatis所需要的依赖包
<!-- mybatis集成springboot启动包 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql的jdbc依赖包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
2.配置文件中配置mapper.xml文件配置
在application.properties文件中添加mybatis文件中xml的位置所在的配置。
#mybats配置
mybatis.mapper-locations=classpath:com/example/demo/mapping/*.xml
3.配置文件中配置数据源信息
在application.properties文件中添加mybatis加载数据源的信息
spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test_client?useUnicode=true&characterEncoding=UTF-8&noAccessToProcedureBodies=true&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
4.添加mybatis注解
我们可以在mybatis的Mapper接口中添加@Mapper注解,或者在运行的主类上添加@MapperScan(basePackages = ("com.example.demo.mapper"))注解包扫描。
以上步骤完成后,就可以操作数据库了。下面上代码。
首先根据数据库自动生成mybatis的代码,我这是一个简单的学生表,表结构如下:
CREATE TABLE `student` ( `id` varchar(10) NOT NULL COMMENT '学号', `name` varchar(20) NOT NULL COMMENT '姓名', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
根据上面的表生成文件如下,model类:里面就是数据库的实体类
package com.example.demo.model; public class Student { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } }
package com.example.demo.model; import java.util.ArrayList; import java.util.List; public class StudentExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public StudentExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<String> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<String> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
mapper的java文件
package com.example.demo.mapper; import com.example.demo.model.Student; import com.example.demo.model.StudentExample; import org.apache.ibatis.annotations.Param; import java.util.List; public interface StudentMapper { int countByExample(StudentExample example); int deleteByExample(StudentExample example); int deleteByPrimaryKey(String id); int insert(Student record); int insertSelective(Student record); List<Student> selectByExample(StudentExample example); Student selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example); int updateByExample(@Param("record") Student record, @Param("example") StudentExample example); int updateByPrimaryKeySelective(Student record); int updateByPrimaryKey(Student record); }
mapper的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="com.example.demo.mapper.StudentMapper" > <resultMap id="BaseResultMap" type="com.example.demo.model.Student" > <id column="id" property="id" jdbcType="VARCHAR" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <sql id="Example_Where_Clause" > <where > <foreach collection="oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixOverrides="and" > <foreach collection="criteria.criteria" item="criterion" > <choose > <when test="criterion.noValue" > and ${criterion.condition} </when> <when test="criterion.singleValue" > and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue" > and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue" > and ${criterion.condition} <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," > #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause" > <where > <foreach collection="example.oredCriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixOverrides="and" > <foreach collection="criteria.criteria" item="criterion" > <choose > <when test="criterion.noValue" > and ${criterion.condition} </when> <when test="criterion.singleValue" > and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue" > and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue" > and ${criterion.condition} <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," > #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List" > id, name </sql> <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.example.demo.model.StudentExample" > select <if test="distinct" > distinct </if> 'true' as QUERYID, <include refid="Base_Column_List" /> from student <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null" > order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from student where id = #{id,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String" > delete from student where id = #{id,jdbcType=VARCHAR} </delete> <delete id="deleteByExample" parameterType="com.example.demo.model.StudentExample" > delete from student <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.example.demo.model.Student" > insert into student (id, name) values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.example.demo.model.Student" > insert into student <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=VARCHAR}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="com.example.demo.model.StudentExample" resultType="java.lang.Integer" > select count(*) from student <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map" > update student <set > <if test="record.id != null" > id = #{record.id,jdbcType=VARCHAR}, </if> <if test="record.name != null" > name = #{record.name,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map" > update student set id = #{record.id,jdbcType=VARCHAR}, name = #{record.name,jdbcType=VARCHAR} <if test="_parameter != null" > <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.Student" > update student <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=VARCHAR} </update> <update id="updateByPrimaryKey" parameterType="com.example.demo.model.Student" > update student set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=VARCHAR} </update> </mapper>
然后编写一个访问数据的controller和响应的service处理类
package com.example.demo.service; import com.example.demo.model.Student; public interface GetStudentService { public Student getStudentInfo(); }
package com.example.demo.service.impl; import com.example.demo.mapper.StudentMapper; import com.example.demo.model.Student; import com.example.demo.service.GetStudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class GetStudentServiceImpl implements GetStudentService { @Autowired private StudentMapper studentMapper; @Override public Student getStudentInfo() { Student student = studentMapper.selectByPrimaryKey("122528"); return student; } }
package com.example.demo.controller; import com.example.demo.model.Student; import com.example.demo.service.impl.GetStudentServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GetStudentController { @Autowired private GetStudentServiceImpl getStudentServiceImpl; @RequestMapping("/getStudent") public String getStudent(){ Student student = getStudentServiceImpl.getStudentInfo(); return "学号=" + student.getId() + ";姓名=" + student.getName(); } }
最后修改一下启动类,用于扫描所有的mapper文件。
package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication @MapperScan(basePackages = ("com.example.demo.mapper")) public class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
运行效果如下: