特意完整

2019-10-07 01:18 来源:未知

用完spring-data-jpa之后并不是很想用mybatis,可是不可能啊,大遇到照旧mybatis,并且今后mybatis也出了多数插件,大家依旧一道探问怎样结合mybatis吧关于整合mybatis有三种办法,一种是声明情势,另一种是古板的xml情势

整合Mybatis分为二种情势,一种是xml配置,一种是注明。作者在此间关键放在xml配置上,因为只要想用注脚的话,建议间接用jpa替代,因为Jpa有更成熟的CRUD接口更利于开荒。小编在后文中也会把表明方式说知道。

先看看引进的依赖

大约介绍下流程:

 <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>1.3.2</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>
  1. 借助idea完毕mybatis逆向工程
  2. 用xml配置达成整合
  3. 用cmd命令行完结mybatis逆向工程
  4. 用mapping.xml配置完成多少交互
  5. 用注明的措施完成数量交互

sql文件

首先自身的开垦条件:jdk1.8+maven3+IDEA

CREATE TABLE `test`.`Untitled` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `passwd` varchar CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY  USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

1. mybatis逆向攻城

逆向工程措施非常多,笔者当下触及到的就两种,一种是依赖ide开辟工具,一种是在cmd中施行命令。(其实互相原理都无差别,都以举行maven的generator命令,具体请看下文)。

application.properties

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>
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql:///test?useSSL=truespring.datasource.username=rootspring.datasource.password=root#打印sql语句到控制台logging.level.com.priv.gabriel.demoformybatis.mapper=debug
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:libmysql_drivermysql-connector-java-5.1.26-bin.jar"/> <context 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>

User.java

3. 使用IDE创造逆向工程运维类

图片 1

package com.priv.gabriel.demoformybatis.entity;/** * Created with Intellij IDEA. * * @Author: Gabriel * @Date: 2018-10-14 * @Description: */public class User { private long id; private String username; private String passwd; public long getId() { return id; } public void setId { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; }}
4. add一个Maven configuration

图片 2图片 3

UserMapper.java

5. 自身的数据库和表结构

图片 4

package com.priv.gabriel.demoformybatis.mapper;import com.priv.gabriel.demoformybatis.entity.User;import org.apache.ibatis.annotations.*;/** * Created with Intellij IDEA. * * @Author: Gabriel * @Date: 2018-10-14 * @Description: */@Mapperpublic interface UserMapper { /*注解方式的话直接在方法上写上对应的sql语句就可以了*/ @Select("select * from user where id = #{id}") /*如果需要重复使用该Result,给该Results加一个 id 属性,下面即可使用@ResultMap重复调用*/ @Results(id = "user",value = { @Result(property = "username",column = "name") }) User findById; /*获取回传自增id*/ /*id会自动存入user中*/ @Insert("insert into user(name,passwd) values (#{username},#{passwd})") @Options(useGeneratedKeys = true,keyProperty = "id") int inertUser(User user);}
6. application配置文件
server: port: 8080spring: 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: 20mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: com.fant.model#pagehelper分页插件pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql

运营generator工程 自动生成代码

UserController.java

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(); }}
package com.priv.gabriel.demoformybatis.controller;import com.priv.gabriel.demoformybatis.entity.User;import com.priv.gabriel.demoformybatis.mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * Created with Intellij IDEA. * * @Author: Gabriel * @Date: 2018-10-14 * @Description: */@RestController@RequestMappingpublic class UserController { @Autowired private UserMapper userMapper; @RequestMapping(value = "/{id}",method = RequestMethod.GET) public User selectById(@PathVariable long id){ return userMapper.findById; } @RequestMapping(value = {""},method = RequestMethod.POST) public String addUser(User user){ userMapper.inertUser; return "现在自增id为"+user.getId(); }}
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();}

在SpringBoot1.x中还要求在开发银行类中步入@MapperScan("mapper所在目录"),而在2.x本子中无需进入就可以自行扫描到mapper了

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 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, username, birthday, sex, address </sql> <select resultMap="BaseResultMap" > select <include ref /> from user </select> <select resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include ref /> from user where id = #{id,jdbcType=INTEGER} </select> <delete parameterType="java.lang.Integer" > delete from user where id = #{id,jdbcType=INTEGER} </delete> <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 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 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 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>

亟待引进pageHelper依赖

修改运行类

逆向生成代码后,我们还索要在起步类上增多贰个@MapperScan("com.fantj.mapper")表明,告诉大家的Mapper供给扫描的包,那样就毫无各类Mapper上都加上@Mapper注脚了。

@SpringBootApplication@MapperScan("com.fantj.mapper")public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); }}
 <!-- 引入分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>

完善controller和service

在UserMapper中新扩充三个查询全体音讯的法子

UserController.java
@RestController@RequestMappingpublic class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET,value = "/delete/{id}") public void delete(@PathVariableint id){ userService.delete; } @RequestMapping(method = RequestMethod.POST,value = "/insert") public void insert(User user){ userService.insert; } @RequestMapping(method = RequestMethod.POST,value = "/update/{id}") public void update(@RequestParam User user){ userService.update; } @RequestMapping(method = RequestMethod.GET,value = "/{id}/select") public User select(@PathVariableint id){ return userService.selectById; } @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); }}
 @Select("select * from user") /*调用之前的Results*/ @ResultMap List<User> listUser();
UserService.java
package com.fantj.service;import com.fantj.model.User;import java.util.List;public interface UserService { /** 删除 */ public void delete; /** 增加*/ public void insert(User user); /** 更新*/ public int update(User user); /** 查询单个*/ public User selectById; /** 查询全部列表*/ public List<User> selectAll(int pageNum, int pageSize);}

在Controller中调用

UserServiceImpl .java
@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; /** * 删除 * * @param id */ @Override public void delete { userMapper.deleteByPrimaryKey; } /** * 增加 * * @param user */ @Override public void insert(User user) { userMapper.insert; } /** * 更新 * * @param user */ @Override public int update(User user) { return userMapper.updateByPrimaryKey; } /** * 查询单个 * * @param id */ @Override public User selectById { return userMapper.selectByPrimaryKey; } /** * 查询全部列表,并做分页 * * @param pageNum 开始页数 * @param pageSize 每页显示的数据条数 */ @Override public List<User> selectAll(int pageNum, int pageSize) { //将参数传给这个方法就可以实现物理分页了,非常简单。 PageHelper.startPage(pageNum,pageSize); return userMapper.selectAll(); }}
 /*获取分页数据 包含分页详细信息*/ @RequestMapping(value = "/",method = RequestMethod.GET) public PageInfo getAll(@RequestParam Integer page, @RequestParam Integer size){ PageHelper.startPage(page,size); List<User> users = userMapper.listUser(); PageInfo<User> pageInfo = new PageInfo; return pageInfo; } /*仅获取分页数据 @RequestMapping(value = "/",method = RequestMethod.GET) public List<User> getAll(@RequestParam Integer page, @RequestParam Integer size){ PageHelper.startPage(page,size); List<User> users = userMapper.listUser(); return users; }*/
浏览器访谈127.0.0.1/user/selectAll/0/1

图片 5

表明大家中标了。

xml格局的话和原先Spring整合mybatis未有太大的界别,在那边能够运用Mybatis-Generator自动生成代码一丢丢一点代码,其他的话就相当少介绍了

三个小甜品

有人问,get方法能够直接从浏览器地址中的url来测验,那post伏乞怎么测验呢?个人提议用postman工具,也足以写测量试验类用代码来造成测量试验。也能够选取idea的三个测验工具Test RESTful Web Service

图片 6图片 7

好了,配置情势我们介绍完了,作者在此间稍微聊一聊表明开垦方式,个人提议一旦想用注明开采,直接用jpa,能够更实惠温馨的花费。

不论是选拔注脚方式照旧XML格局都依然会存在一个哪些都得投机动手的景况,接下去的话,我们结合七个通用的Mapper,在mybatis中体会jpa的痛感援引注重

mybatis java api :
<!-- 引入通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.4</version> </dependency>
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; @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;}

继承BaseMapper

讲明的有的演说
  • @Select 是查询类的注释,全数的询问均选用这么些
  • @Result 修饰重返的结果集,关联实体类属性和数据库字段一一对应,要是实体类* 属性和数据库属性名保持一致,就没有须求这么些性格来修饰。
  • @Insert 插入数据库使用,直接传入实体类会自动剖析属性到相应的值
  • @Update 担负修改,也能够直接传入对象
  • @delete 负担删除
package com.priv.gabriel.demoformybatis.mapper;import com.priv.gabriel.demoformybatis.entity.User;import org.apache.ibatis.annotations.Mapper;import tk.mybatis.mapper.common.BaseMapper;/** * Created with Intellij IDEA. * * @Author: Gabriel * @Date: 2018-10-14 * @Description: */@Mapperpublic interface UserCommonMapper extends BaseMapper<User> {}
注意将application配置文件中的mybatis.mapper-locations:属性注视掉再开行项目。否则它会报错:Mapped Statements collection already contains value for com.fantj.mapper.UserMapper.insert 。意思是mapper中艺术重复。

接着在Controller中调用

最后三个甜品

还应该有三个东西忘说了 -.-,便是用cmd来逆向生成代码。

图片 8

 @Autowired private UserCommonMapper mapper; @RequestMapping("/testCommonMapperForSelectAll") public List<User> testCommonMapper(){ return mapper.selectAll(); }
申明语句

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwritesrc目录请忽略,那是浮动的目录。好了 干货都享受了,多谢大家。0.0

至于mybatis的庞大比非常多,还大概有像mybatis-plus,关于那个话一时光再说吧,ε=ε=ε=┏┛

TAG标签:
版权声明:本文由金沙澳门唯一官网发布于编程教学,转载请注明出处:特意完整