SpringBoot整合Mybatis注解和xml配置形式分别使用(增、删、改、查)
不介绍理论之类的了。直接上代码演示
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>
<name>07-spring-boot-mybatis</name>
<description>Demo project for Spring Boot</description>
<groupId>com.kevin</groupId>
<artifactId>07-spring-boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- springboot版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springboot启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- web启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mybatis启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!-- mybatis逆向生成工程-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<!-- json解析器 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
</project>
application.yml
spring:
#数据源配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_crud?characterEncoding=utf-8
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
#springboot的静态资源调用
thymeleaf:
prefix: classpath:/templates/
cache: false
mybatis:
#定义别名
type-aliases-package: com.kevin.entity
#指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
#打印执行的sql语句
logging:
level:
com:
kevin:
mapper: debug
mbg.xml,用不用无所谓,看个人喜欢,我现在并没用上,mybatis的逆向生成
<?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="D:\generator\mysql-connector-java-5.0.7-bin.jar" />-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<!-- connectionURL="jdbc:sqlserver://localhost:1433;databasename=xxx" -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和NUMERIC 类型解析为Integer,为true时把JDBC DECIMAL和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<!-- targetPackage="com.atmb.cloud.entity" -->
<javaModelGenerator
targetPackage="entity"
targetProject="src/main/java">
<!-- 是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="true" />
<!-- 从数据库返回值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mybatis.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator
type="XMLMAPPER"
targetPackage="com.kevin.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="GeneralAviation" domainObjectName="GeneralAviation"
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false" />
<!--<table tableName="Airway" domainObjectName="Airway"></table>-->
</context>
</generatorConfiguration>
UsersMapper.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.kevin.mapper.UsersMapper">
<!-- 添加用户 -->
<insert id="insertUser" parameterType="users">
insert into users(name,age) values(#{name},#{age})
</insert>
<!-- 查询全部用户 -->
<select id="selectUsersAll" resultType="users">
select id,name,age from users
</select>
<!-- 根据ID查询用户 -->
<select id="selectUsersById" resultType="users">
select id,name,age from users where id = #{value}
</select>
<!-- 更新用户 -->
<update id="updateUser" parameterType="users">
update users set name=#{name} ,age=#{age} where id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUserById">
delete from users where id = #{value}
</delete>
</mapper>
MBGTest,逆向生成类
package com.kevin.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
/**
* 执行逆向工程,生成javabean,mapper
* @author caonanqing
*
*/
public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
String file = "mybatis/mbg.xml";
File configFile = new File(file);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback, warnings);
myBatisGenerator.generate(null);
}
}
控制层
EmpsController
package com.kevin.controller;
import com.google.gson.Gson;
import com.kevin.entity.Emps;
import com.kevin.service.EmpsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 用注解方式获取数据
* @createDate 2019/3/20
*/
@RestController
@RequestMapping("/emps")
public class EmpsController {
@Autowired
private EmpsService empsService;
@RequestMapping("/select")
public String selectEmps(){
List<Emps> emps = empsService.selectEmps();
// 将list的对象解析成json展示到页面
Gson gson = new Gson();
String json = gson.toJson(emps);
return json;
}
}
UsersController
package com.kevin.controller;
import com.kevin.entity.Users;
import com.kevin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 用xml配置文件获取数据,视图控制层
* @createDate 2019/3/13
*/
@Controller
@RequestMapping("/users")
public class UsersController {
@Autowired
private UsersService usersService;
/**
* 页面跳转 访问地址:http://localhost:8080/users/input
* @param page
* @return
*/
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
/**
* 用户添加 访问地址:http://localhost:8080/users/input,添加name,age提交到该方法
* @param users
*/
@RequestMapping("/addUser")
public String addUser(Users users) {
this.usersService.addUser(users);
return "ok";
}
/**
* 查询全部用户 访问地址: http://localhost:8080/users/findUserAll
*/
@RequestMapping("/findUserAll")
public String findUserAll(Model model){
List<Users> list = this.usersService.findUserAll();
model.addAttribute("list", list);
return "showUsers";
}
/**
* 根据用户id查询用户 访问地址: http://localhost:8080/users/findUserAll ,点更新用户会来到该方法根据id查询出来
*/
@RequestMapping("/findUserById")
public String findUserById(Integer id,Model model){
Users user = this.usersService.findUserById(id);
model.addAttribute("user", user);
return "updateUser";
}
/**
* 更新用户 访问地址: http://localhost:8080/users/findUserAll ,点更新用户后修改点确定就会来到该方法修改
*/
@RequestMapping("/editUser")
public String editUser(Users users){
this.usersService.updateUser(users);
return "ok";
}
/**
* 删除用户 访问地址: http://localhost:8080/users/findUserAll ,点删除用户会来到该方法进行删除
*/
@RequestMapping("/delUser")
public String delUser(Integer id){
this.usersService.deleteUserById(id);
return "redirect:/users/findUserAll";
}
}
实体类层
Emps
package com.kevin.entity;
/**
* @author kevin
* @version 1.0
* @description 邮箱实体类
* @createDate 2019/3/20
*/
public class Emps {
private Integer id;
private String name;
private String email;
public Emps() {
}
public Emps(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Users
package com.kevin.entity;
/**
* @author kevin
* @version 1.0
* @description 用户实体类
* @createDate 2019/3/13
*/
public class Users {
private Integer id;
private String name;
private Integer age;
public Users() {
}
public Users(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Mapper层
EmpsMapper
package com.kevin.mapper;
import com.kevin.entity.Emps;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 使用注解形式获取数据的数据
* @createDate 2019/3/20
*/
public interface EmpsMapper {
@Select("select * from emps")
List<Emps> selectEmps();
}
UsersMapper
package com.kevin.mapper;
import com.kevin.entity.Users;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 使用xml形式获取数据,数据持久层
* @createDate 2019/3/13
*/
public interface UsersMapper {
void insertUser(Users users);
List<Users> selectUsersAll();
Users selectUsersById(Integer id);
void updateUser(Users users);
void deleteUserById(Integer id);
}
Service接口层
EmpsService
package com.kevin.service;
import com.kevin.entity.Emps;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description
* @createDate 2019/3/20
*/
public interface EmpsService {
List<Emps> selectEmps();
}
UsersService
package com.kevin.service;
import com.kevin.entity.Users;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 业务层
* @createDate 2019/3/13
*/
public interface UsersService {
void addUser(Users users);
List<Users> findUserAll();
Users findUserById(Integer id);
void updateUser(Users users);
void deleteUserById(Integer id);
}
Service实现层
EmpsServiceImpl
package com.kevin.service.impl;
import com.kevin.entity.Emps;
import com.kevin.mapper.EmpsMapper;
import com.kevin.service.EmpsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description
* @createDate 2019/3/20
*/
@Service
public class EmpsServiceImpl implements EmpsService {
@Autowired
private EmpsMapper empsMapper;
@Override
public List<Emps> selectEmps() {
return empsMapper.selectEmps();
}
}
UsersServiceImpl
package com.kevin.service.impl;
import com.kevin.entity.Users;
import com.kevin.mapper.UsersMapper;
import com.kevin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author kevin
* @version 1.0
* @description 实现业务层
* @createDate 2019/3/13
*/
@Service // 表示为业务实现层
@Transactional // 该注解表示该类下所有的方法都受控制
public class UsersServiceImpl implements UsersService {
@Autowired
UsersMapper usersMapper;
@Override
public void addUser(Users users) {
this.usersMapper.insertUser(users);
}
@Override
public List<Users> findUserAll() {
return this.usersMapper.selectUsersAll();
}
@Override
public Users findUserById(Integer id) {
return this.usersMapper.selectUsersById(id);
}
@Override
public void updateUser(Users users) {
this.usersMapper.updateUser(users);
}
@Override
public void deleteUserById(Integer id) {
this.usersMapper.deleteUserById(id);
}
}
启动类
package com.kevin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author kevin
* @version 1.0
* @description springboot整合mybatis(注解和xml配置形式分别使用)
* @createDate 2019/3/13
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.kevin.mapper"}) // 扫描Mybatis的mapper的接口
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
页面
input.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<form th:action="@{/users/addUser}" method="post">
用户姓名:<input type="text" name="name"/><br/>
用户年龄:<input type="text" name="age"/><br/>
<input type="submit" value="确定"/><br/>
</form>
</body>
</html>
ok.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>操作提示页面</title>
</head>
<body>
操作成功!!!
</body>
</html>
showUsers.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>展示用户数据</title>
</head>
<body>
<table border="1" style="width:300px;">
<tr>
<th>用户ID</th>
<th>用户姓名</th>
<th>用户年龄</th>
<th>操作</th>
</tr>
<tr th:each="user : ${list}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
<td>
<a th:href="@{/users/findUserById(id=${user.id})}">更新用户</a>
<a th:href="@{/users/delUser(id=${user.id})}">删除用户</a>
</td>
</tr>
</table>
</body>
</html>
updateUser.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form th:action="@{/users/editUser}" method="post">
<input type="hidden" name="id" th:field="${user.id}"/>
用户姓名:<input type="text" name="name" th:field="${user.name}"/><br/>
用户年龄:<input type="text" name="age" th:field="${user.age}"/><br/>
<input type="submit" value="确定"/><br/>
</form>
</body>
</html>
整体目录
用注解形式的访问地址:http://localhost:8080/emps/select
用户添加访问地址:http://localhost:8080/users/input
随便新增数据,测试成功
查询全部用户访问地址: http://localhost:8080/users/findUserAll
点击删除zhangjie
点击更新用户kevin,改为程序员
再查询全部,全部测试成功