spring boot2 整合(一)Mybatis (特别完整!)
大概介绍下流程:
- 借助idea实现mybatis逆向工程
- 用xml配置实现整合
- 用cmd命令行实现mybatis逆向工程
- 用mapping.xml配置实现数据交互
- 用注解的方式实现数据交互
首先我的开发环境:
jdk1.8+maven3+IDEA
1. mybatis逆向攻城
逆向工程方式很多,我目前接触到的就两种,一种是借助于ide开发工具,一种是在cmd中执行命令。(其实二者原理都一样,都是执行maven的generator命令,具体请看下文)。
1. 完善pom文件
<?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>springboot-mybatis</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>springboot-integration</groupId>
<artifactId>springboot-integration</artifactId>
<version>1.0-SNAPSHOT</version>
</parent> <!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency> <!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency> <!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency> <!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.4</version>
</dependency>
</dependencies> <!-- Package as an executable jar -->
<build>
<finalName>springboot-mybatis</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
pom.xml
2. 逆向所需配置文件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> <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="E:\lib\mysql_driver\mysql-connector-java-5.1.26-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator> <!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/user" userId="root"
password="root"></jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.fantj.sbmybatis.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator> <!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator> <!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.fantj.sbmybatis.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
generatorConfig.xml
3. 利用IDE创建逆向工程启动类
4. add一个Maven configuration
5. 我的数据库和表结构
6. application配置文件
server:port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/user
username: root
password: root
# druid 连接池
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.fant.model
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
application.yml
运行generator工程 自动生成代码
生成的文件
User.java
package com.fantj.model; import java.util.Date; public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username == null ? null : username.trim();
} public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
}
User.java
UserMapper .java
package com.fantj.mapper; import com.fantj.model.User; import java.util.List; public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> selectAll();
}
userMapper.java
UserMapper.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.fantj.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.fantj.model.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="birthday" property="birthday" jdbcType="DATE"/>
<result column="sex" property="sex" jdbcType="CHAR"/>
<result column="address" property="address" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List"> id, username, birthday, sex, address </sql>
<select id="selectAll" resultMap="BaseResultMap">select
<include refid="Base_Column_List"/>
from user
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">select
<include refid="Base_Column_List"/>
from user where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey"
parameterType="java.lang.Integer"> delete from user where id = #{id,jdbcType=INTEGER} </delete>
<insert id="insert"
parameterType="com.fantj.model.User"> insert into user (id, username, birthday, sex, address) values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR}) </insert>
<insert id="insertSelective" parameterType="com.fantj.model.User">insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="username != null">username,</if>
<if test="birthday != null">birthday,</if>
<if test="sex != null">sex,</if>
<if test="address != null">address,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id,jdbcType=INTEGER},</if>
<if test="username != null">#{username,jdbcType=VARCHAR},</if>
<if test="birthday != null">#{birthday,jdbcType=DATE},</if>
<if test="sex != null">#{sex,jdbcType=CHAR},</if>
<if test="address != null">#{address,jdbcType=VARCHAR},</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.fantj.model.User">update user
<set>
<if test="username != null">username = #{username,jdbcType=VARCHAR},</if>
<if test="birthday != null">birthday = #{birthday,jdbcType=DATE},</if>
<if test="sex != null">sex = #{sex,jdbcType=CHAR},</if>
<if test="address != null">address = #{address,jdbcType=VARCHAR},</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey"
parameterType="com.fantj.model.User"> update user set username = #{username,jdbcType=VARCHAR}, birthday = #{birthday,jdbcType=DATE}, sex = #{sex,jdbcType=CHAR}, address = #{address,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>
userMapper.xml
修改启动类
逆向生成代码后,我们还需要在启动类上添加一个@MapperScan("com.fantj.mapper")
注解,告诉我们的Mapper需要扫描的包,这样就不用每个Mapper上都添加@Mapper注解了
package com.fantj; import com.fantj.util.Params;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @SpringBootApplication
@MapperScan("com.fantj.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
App.java
完善controller和service
UserController.java
package com.fantj.controller; import com.fantj.model.User;
import com.fantj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import javax.jws.soap.SOAPBinding;
import java.util.Date;
import java.util.List; @RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService; @RequestMapping(method = RequestMethod.GET, value = "/delete/{id}")
public void delete(@PathVariable("id") int id) {
userService.delete(id);
} @RequestMapping(method = RequestMethod.POST, value = "/insert")
public void insert(User user) {
userService.insert(user);
} @RequestMapping(method = RequestMethod.POST, value = "/update/{id}")
public void update(@RequestParam User user) {
userService.update(user);
} @RequestMapping(method = RequestMethod.GET, value = "/{id}/select")
public User select(@PathVariable("id") int id) {
return userService.selectById(id);
} @RequestMapping(method = RequestMethod.GET, value = "/selectAll/{pageNum}/{pageSize}")
public List<User> selectAll(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
return userService.selectAll(pageNum, pageSize);
}
}
UserController.java
UserService.java
package com.fantj.service; import com.fantj.model.User; import java.util.List; public interface UserService {
/**
* 删除
*/
public void delete(int id); /**
* 增加
*/
public void insert(User user); /**
* 更新
*/
public int update(User user); /**
* 查询单个
*/
public User selectById(int id); /**
* 查询全部列表
*/
public List<User> selectAll(int pageNum, int pageSize);
}
UserService.java
UserServiceImpl .java
package com.fantj.service.impl; import com.fantj.mapper.UserMapper;
import com.fantj.model.User;
import com.fantj.service.UserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; /**
* 删除 * * @param id
*/
@Override
public void delete(int id) {
userMapper.deleteByPrimaryKey(id);
} /**
* 增加 * * @param user
*/
@Override
public void insert(User user) {
userMapper.insert(user);
} /**
* 更新 * * @param user
*/
@Override
public int update(User user) {
return userMapper.updateByPrimaryKey(user);
} /**
* 查询单个 * * @param id
*/
@Override
public User selectById(int id) {
return userMapper.selectByPrimaryKey(id);
} /**
* 查询全部列表,并做分页 * * @param pageNum 开始页数 * @param pageSize 每页显示的数据条数
*/
@Override
public List<User> selectAll(int pageNum, int pageSize) { //将参数传给这个方法就可以实现物理分页了,非常简单。 PageHelper.startPage(pageNum,pageSize); return userMapper.selectAll(); } }
UserServiceImpl.java
spring boot2 整合(一)Mybatis (特别完整!)的更多相关文章
- [Java] Spring boot2 整合 Thymeleaf 后 去除模板缓存
Spring boot2 整合 Thymeleaf 后 去除模板缓存 网上好多文章只是简单粗暴的说,在 application.properties 做如下配置即可: #Thymeleaf cach ...
- Spring Boot整合tk.mybatis及pageHelper分页插件及mybatis逆向工程
Spring Boot整合druid数据源 1)引入依赖 <dependency> <groupId>com.alibaba</groupId> <artif ...
- spring boot 2.x 系列 —— spring boot 整合 druid+mybatis
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.说明 1.1 项目结构 项目查询用的表对应的建表语句放置在resour ...
- spring boot2整合dubbox全注解
前题 dubbox是dubbo的一个升级版,简单说就是本来dubbo是阿里开发的,现在阿里不维护了,当当网拿过去继续开发.本来阿里的dubbo维护到2.6版本,而再高版本的都是当当网维护的就叫成dub ...
- spring boot2 整合(二)JPA(特别完整!)
JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. JPA 的目标之一是制定一个可以由很多供应商 ...
- Spring Boot2(十一):Mybatis使用总结(自增长、多条件、批量操作、多表查询等等)
一.前言 上次用Mybatis还是2017年做项目的时候,已经很久过去了.中途再没有用过Mybatis.导致现在学习SpringBoot过程中遇到一些Mybatis的问题,以此做出总结(XML极简模式 ...
- spring boot整合 springmvc+mybatis
需要以下依赖 <dependencies> <dependency> <groupId>org.springframework.boot</groupId&g ...
- MyBatis 3 与 Spring 4 整合关键
MyBatis 3 与 Spring 4 整合关键 MyBatis与Spring整合,首先需要一个Spring数据源.其次有两个关键,配置sqlSessionFactory时需要配置扫描sql映射xm ...
- MyBatis与Spring的整合实例详解
从之前的代码中可以看出直接使用 MyBatis 框架的 SqlSession 访问数据库并不简便.MyBatis 框架的重点是 SQL 映射文件,为方便后续学习,本节讲解 MyBatis 与 Spri ...
随机推荐
- 【CF600E】Lomsat gelral
题目大意:给定一棵 N 个节点的有根树,1 号节点是树的根节点,每个节点有一个颜色.求对于每个节点来说,能够支配整棵子树的颜色之和是多少.支配的定义为对于以 i 为根的子树,该颜色出现的次数不小于任何 ...
- 【POJ2230】Watchcow
题目大意:给定一个 N 个点,M 条边的无向图,要求不重复地经过每条边两次,并且从 1 号节点出发最后回到 1 号节点,求一条路径. 题解:不重复地经过两次这个操作很容易地通过无向图的建边方式来实现, ...
- 利用captcha库绘制验证码
#导包 from captcha.image import ImageCaptcha from PIL import Image import random import time import os ...
- Linux批量修改(删除)文件名某些字符(rename命令)
假设在路径C:/下存在多个类似以下的文件名 file_nall_abc1.txt file_nall_abc2.txt file_nall_abc3.txt file_nall_abc4.txt fi ...
- 斯坦福大学公开课机器学习: machine learning system design | prioritizing what to work on : spam classification example(设计复杂机器学习系统的主要问题及构建复杂的机器学习系统的建议)
当我们在进行机器学习时着重要考虑什么问题.以垃圾邮件分类为例子.假如你想建立一个垃圾邮件分类器,看这些垃圾邮件与非垃圾邮件的例子.左边这封邮件想向你推销东西.注意这封垃圾邮件有意的拼错一些单词,就像M ...
- Tennis Game CodeForces - 496D(唯一分解定理,费马大定理)
Tennis Game CodeForces - 496D 通过排列组合解决问题. 首先两组不同素数的乘积,是互不相同的.这应该算是唯一分解定理的逆运用了. 然后是,输入中的素数,任意组合,就是n的因 ...
- Linux中sed的用法实践
Linux中sed的用法实践 参考资料:https://www.cnblogs.com/emanlee/archive/2013/09/07/3307642.html http://www.fn139 ...
- mysql删除大表更快的drop table办法
mysql删除大表更快的drop table办法 参考资料:https://blog.csdn.net/anzhen0429/article/details/76284320 利用硬链接和trunca ...
- Java概念、语法和变量基础整理
Java概述 J2SE: Java 2 Platform Standard Edition( 2005年之后更名为Java SE ).包含构成Java语言核心的类 J2EE: Java 2 Plat ...
- spring 整合 redis,以及spring的RedisTemplate如何使用
需要的jar包 spring-data-redis-1.6.2.RELEASE.jar jedis-2.7.2.jar(依赖 commons-pool2-2.3.jar) commons-pool2- ...