一、创建一个springboot项目
(1)创建项目
(2)设置项目信息
- 这里使用springboot内嵌tomcat;
- 选择jar包即可,jdk版本选择8;
- 其余选项可根据自己情况适当调整
(3)选择依赖模块
-
这里为了通过浏览器访问查看最终效果,所以选择依赖web模块
-
为了演示整个整合myBatis过程,暂时不引入SQL相关依赖,实际应用中可以选择对应模块则更加方便会自动导入相关依赖,其他模块类似
(4)然后下一页点击finish,工程创建成功
直接完成即可
二、整合mybatis(方式一)
先纯手动的导入相关依赖,并创建相应文件,下面会介绍利用generator自动生成mybatis相关代码
(1)导入相关依赖
导入mybatis起步依赖和mysql相关依赖
pom.xml如下:
<?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.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zrk</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis</name>
<description>demo</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis起步依赖-->
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(2)配置数据库连接跟驱动
报红可能是因为没有找到驱动,更新新maven即可
其他的数据源可配置的参数,如果了解springboot原理可以参考DataSourceProperties文件中的属性
(3)配置mybatis相关路径参数
application.properties如下:
#datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/zrk?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# mybatis
##对应实体类路径
mybatis.type-aliases-package=com.zrk.springbootmybatis.pojo
##mapper映射xml所在路径
mybatis.mapper-locations=classpath:mapper/*.xml
(4)创建用户表
CREATE TABLE user (
id int(4) NOT NULL AUTO_INCREMENT,
name char(20) NOT NULL,
password char(20) NOT NULL DEFAULT '123456',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
(5)创建User实体
User.java如下:
package com.zrk.sprintboot.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable{
private static final long serialVersionUID = 1123359545311049357L;
private Integer id;
private String name;
private String password;
}
-
关于生成***可参考
https://jingyan.baidu.com/article/656db918c36534e381249c83.html
-
为了简化代码使用@Data注解,这是lombok的注解,使用的话需要在pom文件中导入lombok依赖,
-
当然也可以使用@Getter和@Setter两个lombok注解效果一样
-
当然不使用lombok使用原始get、set方法也可以
<!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
(6)创建UserDao接口
UserDao.java如下:
package com.zrk.springbootmybatis.dao;
import com.zrk.springbootmybatis.pojo.User;
import java.util.List;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
public interface UserDao {
List<User> getAllUser();
User getUserById(Integer id);
}
(7)创建UserMapper.xml
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.zrk.springbootmybatis.dao.UserDao">
<select id="getAllUser" resultType="com.zrk.springbootmybatis.pojo.User">
select * from user
</select>
<select id="getUserById" resultType="com.zrk.springbootmybatis.pojo.User">
select * from user where id = #{id,jdbcType=INTEGER}
</select>
</mapper>
(8)在启动类配置mapper扫描路径
(9)最后创建对应controller、service调用测试即可
UserController.java
package com.zrk.springbootmybatis.controller;
import com.zrk.springbootmybatis.pojo.User;
import com.zrk.springbootmybatis.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
@RequestMapping(value = "user")
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("getAllUser")
public List<User> getAllUser(){
return userService.getAllUser();
}
@GetMapping("getUserById")
public User getUserById(
@RequestParam(value = "id") Integer id
){
return userService.getUserById(id);
}
}
UserService.java
package com.zrk.springbootmybatis.service;
import com.zrk.springbootmybatis.pojo.User;
import java.util.List;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
public interface UserService {
List<User> getAllUser();
User getUserById(Integer id);
}
UserServiceImpl.java
package com.zrk.springbootmybatis.service.impl;
import com.zrk.springbootmybatis.dao.UserDao;
import com.zrk.springbootmybatis.pojo.User;
import com.zrk.springbootmybatis.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> getAllUser() {
return userDao.getAllUser();
}
@Override
public User getUserById(Integer id) {
return userDao.getUserById(id);
}
}
三、测试
(1)启动项目
(2)浏览器访问测试
(3)工程结构
四、通过mybatis generator 自动生成代码
(1)pom文件中引入插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<!--版本根据实际情况调整-->
<version>1.3.5</version>
<configuration>
<!--设置为配置文件路径-->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
(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="C:\Users\srt\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.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/zrk" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.zrk.springbootmybatis.pojo" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zrk.springbootmybatis.dao" 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)运行
先更新manen,然后双击插件图标即可
(4)生成的文件
UserMapper.java
package com.zrk.springbootmybatis.dao;
import com.zrk.springbootmybatis.pojo.User;
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);
}
User.java
package com.zrk.springbootmybatis.pojo;
public class User {
private Integer id;
private String name;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
}
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.zrk.springbootmybatis.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.zrk.springbootmybatis.pojo.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="CHAR" property="name" />
<result column="password" jdbcType="CHAR" property="password" />
</resultMap>
<sql id="Base_Column_List">
id, name, password
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
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.zrk.springbootmybatis.pojo.User">
insert into user (id, name, password)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=CHAR}, #{password,jdbcType=CHAR})
</insert>
<insert id="insertSelective" parameterType="com.zrk.springbootmybatis.pojo.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="password != null">
password,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=CHAR},
</if>
<if test="password != null">
#{password,jdbcType=CHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.zrk.springbootmybatis.pojo.User">
update user
<set>
<if test="name != null">
name = #{name,jdbcType=CHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=CHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.zrk.springbootmybatis.pojo.User">
update user
set name = #{name,jdbcType=CHAR},
password = #{password,jdbcType=CHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
(5)修改Controller、Service、ServiceImpl
UserController.java
package com.zrk.springbootmybatis.controller;
import com.zrk.springbootmybatis.pojo.User;
import com.zrk.springbootmybatis.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
@RequestMapping(value = "user")
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("getUserById")
public User getUserById(
@RequestParam(value = "id") Integer id
){
return userService.selectByPrimaryKey(id);
}
}
UserService.java
package com.zrk.springbootmybatis.service;
import com.zrk.springbootmybatis.pojo.User;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
public interface UserService {
User selectByPrimaryKey(Integer id);
}
UserServiceImpl.java
package com.zrk.springbootmybatis.service.impl;
import com.zrk.springbootmybatis.dao.UserMapper;
import com.zrk.springbootmybatis.pojo.User;
import com.zrk.springbootmybatis.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @description:
* @author: zrk
* @create: 2019/1/10
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userDao;
@Override
public User selectByPrimaryKey(Integer id) {
return userDao.selectByPrimaryKey(id);
}
}