<?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.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lonelycountry</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</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.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- alibaba的druid數據庫鏈接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--這個自動生成工具我以爲很差用啊-->
<!--<plugin>-->
<!--<groupId>org.mybatis.generator</groupId>-->
<!--<artifactId>mybatis-generator-maven-plugin</artifactId>-->
<!--<version>1.3.2</version>-->
<!--<configuration>-->
<!--<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>-->
<!--<overwrite>true</overwrite>-->
<!--<verbose>true</verbose>-->
<!--</configuration>-->
<!--</plugin>-->
</plugins>
</build>
</project>
複製代碼
application.yml
php
spring:
datasource:
name: springboot-demo
type: com.alibaba.druid.pool.DruidDataSource
druid:
filters: stat
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: ******
url: jdbc:mysql://localhost:3306/springboot-mybatis
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20
http:
encoding:
charset: UTF-8
server:
port: 80
tomcat:
uri-encoding: utf-8
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.lonelycountry.springbootmybatis.po
configuration:
map-underscore-to-camel-case: true
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
複製代碼
package com.lonelycountry.springbootmybatis.po;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.apache.ibatis.type.Alias;
import java.sql.Timestamp;
@Alias("User")//設置別名,在mapper.xml裏面就不須要每次都填完整路徑了
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String username;
private String password;
private Integer age;
private Timestamp createDate;
}
複製代碼
package com.lonelycountry.springbootmybatis.dao;
import com.lonelycountry.springbootmybatis.po.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
List<User> listUsers();
List<User> listUsers(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize);
User getUser(@Param("id") Long id);
void insertUser(User user);
void updateUser(User user);
void batchInsertUser(@Param("users") List<User> users);
void deleteUser(@Param("id") Long id);
void batchDeleteUser(@Param("ids") List<Long> ids);
}
複製代碼
<?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.lonelycountry.springbootmybatis.dao.UserMapper">
<select id="listUsers" resultType="User">
select * from user
</select>
<select id="getUser" resultType="User">
select * from user
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</select>
<insert id="insertUser">
insert into user (id,username,password,age,create_date)
values (#{id},#{username},#{password},#{age},#{createDate})
</insert>
<insert id="batchInsertUser">
insert into user (id,username,password,age,create_date)
values
<foreach collection="users" item="user" index="index" separator=",">
(#{user.id},#{user.username},#{user.password},#{user.age},#{user.createDate})
</foreach>
</insert>
<update id="updateUser">
update user
<set>
username = #{username},
password = #{password},
age = #{age},
create_date = #{createDate}
</set>
<where>
id = #{id}
</where>
</update>
<delete id="deleteUser">
delete from user
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</delete>
<delete id="batchDeleteUser">
delete from user
<where>
id in
<foreach collection="ids" item="id" index="index" separator="," open="(" close=")">
<if test="id != null">
#{id}
</if>
</foreach>
</where>
</delete>
</mapper>
複製代碼
說明:
寫了通用的增刪改查以及部分批量操做。具體請看mybatis官方文檔。html
UserController
java
package com.lonelycountry.springbootmybatis.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lonelycountry.springbootmybatis.dao.UserMapper;
import com.lonelycountry.springbootmybatis.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
/** * @author zhuqiwei * 2019-02-19. */
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@Autowired
private HttpServletRequest request;
@GetMapping("/user/all")
public List<User> getUser() {
List<User> users = userMapper.listUsers();
return users;
}
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
User user = userMapper.getUser(id);
return user;
}
@PostMapping("/user/create")
public User insertUser(@RequestBody User user) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
user.setCreateDate(timestamp);
userMapper.insertUser(user);
return user;
}
@PostMapping("/user/update")
public User updateUser(@RequestBody User user) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
user.setCreateDate(timestamp);
userMapper.updateUser(user);
return user;
}
@PostMapping("/user/create/batch")
public List<User> insertUser(@RequestBody List<User> users) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
users.forEach(user -> {
user.setCreateDate(timestamp);
});
userMapper.batchInsertUser(users);
return users;
}
@PostMapping("/user/delete/{id}")
public List<User> deleteUser(@PathVariable("id") Long id) {
userMapper.deleteUser(id);
return getUser();
}
@PostMapping("/user/delete/batch")
public List<User> updateUser(@RequestBody List<Long> ids) {
userMapper.batchDeleteUser(ids);
return getUser();
}
@GetMapping("/user/all/{page}/{size}")
public PageInfo<User> getUser(@PathVariable("page") int page, @PathVariable("size") int size) {
//方法1
//List<User> users = PageHelper.startPage(page, size).doSelectPage(() -> userMapper.listUsers());
//return users;
//方法2
//PageHelper.startPage(page, size);
//List<User> users = userMapper.listUsers();
//Page<User> userPage = (Page<User>) users;
//return userPage;
//方法4
PageHelper.startPage(page, size);
List<User> users = userMapper.listUsers();
PageInfo<User> pageInfo = new PageInfo<>(users);
return pageInfo;
//return null;
}
@GetMapping("/user/all/flip")
public List<User> getUser2() {
//方法3
PageHelper.startPage(request);
List<User> users = userMapper.listUsers();
Page<User> userPage = (Page<User>) users;
return userPage;
}
}
複製代碼
說明:
在獲取所有user數據的時候使用了分頁插件並實現了四種方法,具體相關文檔能夠參照mybatis分頁插件官方文檔。mysql
本文爲原創,轉載請註明原處。git