spring-boot2-整合(一)Mybatis-(特別完整!)
整合Mybatis分為兩種模式,一種是xml配置,一種是註解。(類似JPA)
我在這裡重點放在xml配置上,因為如果想用註解的話,建議直接用jpa代替,因為Jpa有更成熟的CRUD介面更方便開發。我在後文中也會把註解方式說清楚。
大概介紹下流程:
1. 藉助idea實現mybatis逆向工程
2. 用xml配置實現整合
3. 用cmd命令列實現mybatis逆向工程
4. 用mapping.xml配置實現資料互動
5. 用註解的方式實現資料互動
首先我的開發環境:
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>
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>
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
執行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();
}
}
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.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>
修改啟動類
逆向生成程式碼後,我們還需要在啟動類上新增一個@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);
}
}
完善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);
}
}
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);
}
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();
}
}
瀏覽器訪問127.0.0.1/user/selectAll/0/1
說明我們成功了。
一個小甜點
有人問,get方法可以直接從瀏覽器地址中的url來測試,那post請求怎麼測試呢?
個人建議用postman工具,也可以寫測試類用程式碼來完成測試。也可以使用idea的一個測試工具Test RESTful Web Service
註解方式
好了,配置方式我們介紹完了,我在這裡稍微聊一聊註解開發方式,個人建議如果想用註解開發,直接用jpa,可以更方便自己的開發。
UserMapper.java
package com.fantj.mapper;
import com.fantj.model.User;
import org.apache.ibatis.annotations.*;
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();*/
//如果例項物件中的屬性名和資料表中欄位名不一致,用@Result註解進行說明對映關係,我在這裡只是告訴你怎麼寫
@Select("SELECT * FROM user")
@Results({
@Result(property = "username", column = "username"),
@Result(property = "sex", column = "sex"),
@Result(property = "address",column = "address")
})
List<User> selectAll();
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "sex", column = "sex"),
@Result(property = "username", column = "username")
})
User selectByPrimaryKey(int id);
@Insert({"INSERT INTO user(username,birthday,sex,address}) VALUES(#{userName}, #{birthday}, #{sex},#{address})"})
void insert(User user);
@Update("UPDATE user SET userName=#{userName} WHERE id =#{id}")
int updateByPrimaryKey(User user);
@Delete("DELETE FROM user WHERE id =#{id}")
int deleteByPrimaryKey(int id);
}
註解的一些解釋
- @Select 是查詢類的註解,所有的查詢均使用這個
- @Result 修飾返回的結果集,關聯實體類屬性和資料庫欄位一一對應,如果實體類* 屬性和資料庫屬性名保持一致,就不需要這個屬性來修飾。
- @Insert 插入資料庫使用,直接傳入實體類會自動解析屬性到對應的值
- @Update 負責修改,也可以直接傳入物件
- @delete 負責刪除
注意將application配置檔案中的mybatis.mapper-locations:屬性注視掉再啟動專案。否則它會報錯:Mapped Statements collection already contains value for com.fantj.mapper.UserMapper.insert 。意思是mapper中方法重複。
最後一個甜點
還有一個東西忘說了 -.-,就是用cmd來逆向生成程式碼。
聲稱語句
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
src目錄請忽略,這是生成的目錄。
好了 乾貨都分享了,謝謝大家。0.0