从零到一 Springboot+Mybatis_XML示例
1、建表
新建一张测试表,演示使用。
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`summary` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`create_time` datetime(0) NOT NULL,
`modify_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
2、创建工程
工程结构如下:
3、引入依赖相关依赖
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qqxhb</groupId>
<artifactId>springboot-mybatis-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis-demo</name>
<description>Demo project for Spring Boot and Mybatis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4、配置数据源等
server.port=8080
spring.datasource.url=jdbc:mysql://127.0.0.1/demo?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis 配置
mybatis.check-config-location=true
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapperLocations=classpath:mapper/*.xml
5、创建实体及映射(可使用mybatis的插件)
实体
package com.qqxhb.demo.entity;
import java.util.Date;
public class News {
private Long id;
private String title;
private String summary;
private Date createTime;
private Date modifyTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
}
映射接口
package com.qqxhb.demo.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.qqxhb.demo.entity.News;
import com.qqxhb.demo.entity.NewsExample;
public interface NewsMapper {
long countByExample(NewsExample example);
int deleteByExample(NewsExample example);
int insert(News record);
int insertSelective(News record);
List<News> selectByExample(NewsExample example);
int updateByExampleSelective(@Param("record") News record, @Param("example") NewsExample example);
int updateByExample(@Param("record") News record, @Param("example") NewsExample example);
}
映射文件
<?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.qqxhb.demo.dao.NewsMapper">
<resultMap id="BaseResultMap" type="com.qqxhb.demo.entity.News">
<result column="id" jdbcType="BIGINT" property="id" />
<result column="title" jdbcType="VARCHAR" property="title" />
<result column="summary" jdbcType="VARCHAR" property="summary" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="modify_time" jdbcType="TIMESTAMP" property="modifyTime" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")">
<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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, title, summary, create_time, modify_time
</sql>
<select id="selectByExample" parameterType="com.qqxhb.demo.entity.NewsExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from news
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<delete id="deleteByExample" parameterType="com.qqxhb.demo.entity.NewsExample">
delete from news
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.qqxhb.demo.entity.News">
insert into news (id, title, summary,
create_time, modify_time)
values (#{id,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{summary,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP}, #{modifyTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.qqxhb.demo.entity.News">
insert into news
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="title != null">
title,
</if>
<if test="summary != null">
summary,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="modifyTime != null">
modify_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="title != null">
#{title,jdbcType=VARCHAR},
</if>
<if test="summary != null">
#{summary,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="modifyTime != null">
#{modifyTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.qqxhb.demo.entity.NewsExample" resultType="java.lang.Long">
select count(*) from news
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update news
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=BIGINT},
</if>
<if test="record.title != null">
title = #{record.title,jdbcType=VARCHAR},
</if>
<if test="record.summary != null">
summary = #{record.summary,jdbcType=VARCHAR},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=TIMESTAMP},
</if>
<if test="record.modifyTime != null">
modify_time = #{record.modifyTime,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update news
set id = #{record.id,jdbcType=BIGINT},
title = #{record.title,jdbcType=VARCHAR},
summary = #{record.summary,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=TIMESTAMP},
modify_time = #{record.modifyTime,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
</mapper>
6、编码Service和Controller
Service
package com.qqxhb.demo.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qqxhb.demo.dao.NewsMapper;
import com.qqxhb.demo.entity.News;
import com.qqxhb.demo.entity.NewsExample;
@Service
public class NewsService {
@Autowired
NewsMapper newsMapper;
/**添加新闻
* @param title
* @param summary
* @return
*/
public int insertNews(String title, String summary) {
if (title == null || title.length() < 1) {
return 0;
}
News record = new News();
record.setTitle(title);
record.setSummary(summary);
record.setCreateTime(new Date());
return newsMapper.insertSelective(record);
}
/**查询新闻
* @param title
* @return
*/
public List<News> selectNews(String title) {
NewsExample example = new NewsExample();
if (title != null && title.length() > 0) {
example.createCriteria().andTitleLike(title);
}
return newsMapper.selectByExample(example);
}
}
Controller
package com.qqxhb.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.qqxhb.demo.entity.News;
import com.qqxhb.demo.service.NewsService;
@RestController
@RequestMapping("news")
public class NewsController {
@Autowired
NewsService newsService;
/**添加新闻
* @param title
* @param summary
* @return
*/
@PostMapping
public String addNews(@RequestParam(value = "title",required = true)String title, String summary) {
int news = newsService.insertNews(title, summary);
return news>0?"添加成功!":"添加失败!";
}
/**查询新闻
* @param title
* @return
*/
@GetMapping
public List<News> getNews(String title) {
return newsService.selectNews(title);
}
}
7、启动并测试接口
启动类
package com.qqxhb.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.qqxhb.demo.dao")
public class SpringbootMybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}
新建接口测试
查询接口测试
总结
本文简单介绍了Springboot 整合Mybatis (XML),编写了简单的测试接口并测试通过。实际项目开发 还有很多需要配置的,比如引入alibaba的druid连接池并配置、事务声明配置、使用PageHelper实现分页等。欢迎大家留言指正!
附
源码地址:https://github.com/qqxhb/springboot-mybatis-demo
generatorConfig.xml 的精简配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="mysqlgenerator" targetRuntime="MyBatis3">
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection connectionURL="jdbc:mysql://127.0.0.1/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"
driverClass="com.mysql.jdbc.Driver"
userId="root"
password="root"/>
<javaModelGenerator targetPackage="com.qqxhb.demo.entity"
targetProject="springboot-mybatis-demo"/>
<sqlMapGenerator targetPackage="mapper"
targetProject="springboot-mybatis-demo"/>
<javaClientGenerator targetPackage="com.qqxhb.demo.dao"
targetProject="springboot-mybatis-demo"
type="XMLMAPPER"/>
<table tableName="news"/>
</context>
</generatorConfiguration>