springboot-mybatis-mysql
阿新 • • 發佈:2019-07-15
-
整體結構
-
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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>top.heliming.mybatis</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> <mybatis.version>1.3.2</mybatis.version> <commons-lang3.version>3.4</commons-lang3.version> <pagehelper.version>1.2.5</pagehelper.version> <druid.version>1.1.9</druid.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>${mybatis.version}</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> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <!-- 分頁外掛 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>${pagehelper.version}</version> </dependency> <!-- alibaba的druid資料庫連線池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
-
application.yml
server: port: 8080 spring: datasource: name: mysql_test type: com.alibaba.druid.pool.DruidDataSource #druid相關配置 druid: #監控統計攔截的filters filters: stat driver-class-name: com.mysql.jdbc.Driver #基本屬性 url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true username: manager password: 123 #配置初始化大小/最小/最大 initial-size: 5 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 #開啟PSCache,並指定每個連線上PSCache的大小。oracle設為true,mysql設為false。分庫分表較多推薦設定為false pool-prepared-statements: false max-pool-prepared-statement-per-connection-size: 20 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: top.heliming.mybatis.springbootmybatis.pojo #pagehelper #如此配置就可使用分頁功能,分頁注意事項: # #在pageHelper.startpage方法後的第一條查詢方法才會被分頁 # #帶有for update 行鎖的語句,不要使用分頁外掛,會拋異常 pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql returnPageInfo: check
-
pojo
package top.heliming.mybatis.springbootmybatis.pojo; /** * 測試實體類 */ public class User { private Integer userId; private String userName; private String password; private Long phone; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Long getPhone() { return phone; } public void setPhone(Long phone) { this.phone = phone; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", phone=" + phone + '}'; } }
-
dao
package top.heliming.mybatis.springbootmybatis.dao; import org.springframework.stereotype.Repository; import top.heliming.mybatis.springbootmybatis.pojo.User; import java.util.List; @Repository public interface UserDao { int insert(User user); List<User> selectUsers(); }
-
service
package top.heliming.mybatis.springbootmybatis.service; import com.github.pagehelper.PageInfo; import top.heliming.mybatis.springbootmybatis.pojo.User; public interface UserService { int addUser(User user); PageInfo<User> findAllUser(int pageNum, int pageSize); }
-
Impl
package top.heliming.mybatis.springbootmybatis.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.heliming.mybatis.springbootmybatis.dao.UserDao; import top.heliming.mybatis.springbootmybatis.pojo.User; import top.heliming.mybatis.springbootmybatis.service.UserService; import java.util.List; @Service(value = "userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public int addUser(User user) { return userDao.insert(user); } /* * 這個方法中用到了我們開頭配置依賴的分頁外掛pagehelper * 很簡單,只需要在service層傳入引數,然後將引數傳遞給一個外掛的一個靜態方法即可; * pageNum 開始頁數 * pageSize 每頁顯示的資料條數 * */ @Override public PageInfo<User> findAllUser(int pageNum, int pageSize) { //將引數傳給這個方法就可以實現物理分頁了,非常簡單。 PageHelper.startPage(pageNum, pageSize); List<User> users = userDao.selectUsers(); PageInfo result = new PageInfo(users); return result; } }
-
controller
package top.heliming.mybatis.springbootmybatis.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import top.heliming.mybatis.springbootmybatis.pojo.User; import top.heliming.mybatis.springbootmybatis.service.UserService; @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @PostMapping("/add") public int addUser(User user) { return userService.addUser(user); } @GetMapping("/all") public Object findAllUser( @RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum, @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) { return userService.findAllUser(pageNum, pageSize); } }
-
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="top.heliming.mybatis.springbootmybatis.dao.UserDao" > <sql id="BASE_TABLE"> t_user </sql> <sql id="BASE_COLUMN"> userId,userName,password,phone </sql> <insert id="insert" parameterType="top.heliming.mybatis.springbootmybatis.pojo.User"> INSERT INTO <include refid="BASE_TABLE"/> <trim prefix="(" suffix=")" suffixOverrides=","> userName,password, <if test="phone != null"> phone, </if> </trim> <trim prefix="VALUES(" suffix=")" suffixOverrides=","> #{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR}, <if test="phone != null"> #{phone, jdbcType=VARCHAR}, </if> </trim> </insert> <select id="selectUsers" resultType="top.heliming.mybatis.springbootmybatis.pojo.User"> SELECT <include refid="BASE_COLUMN"/> FROM <include refid="BASE_TABLE"/> </select> </mapper>
-
SpringbootMybatisApplicationTests
package top.heliming.mybatis.springbootmybatis; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootMybatisApplicationTests { @Test public void contextLoads() { } }
-
UserControllerTest
package top.heliming.mybatis.springbootmybatis.controller; import com.github.pagehelper.PageInfo; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import top.heliming.mybatis.springbootmybatis.SpringbootMybatisApplicationTests; import top.heliming.mybatis.springbootmybatis.dao.UserDao; import top.heliming.mybatis.springbootmybatis.pojo.User; import top.heliming.mybatis.springbootmybatis.service.UserService; import static org.junit.Assert.*; public class UserControllerTest extends SpringbootMybatisApplicationTests { @Autowired private UserService userService; @Autowired private UserDao userDao; @Test public void addUser() { User user = new User(); user.setUserName("小紅"); user.setPassword("000000"); user.setPhone(13490234321L); int insert = userDao.insert(user); assertEquals(insert,1); user.setUserName("小明"); user.setPassword("000000"); user.setPhone(13490234320L); insert = userDao.insert(user); assertEquals(insert,1); } @Test public void findAllUser(){ PageInfo<User> pageInfo = userService.findAllUser(0, 5); System.out.println(pageInfo); assertNotNull(pageInfo); } }
-
test.sql
/* Navicat Premium Data Transfer Source Server : manager Source Server Type : MySQL Source Server Version : 50726 Source Host : localhost:3306 Source Schema : test Target Server Type : MySQL Target Server Version : 50726 File Encoding : 65001 Date: 15/07/2019 00:44:56 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `userId` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(255) DEFAULT '', `password` varchar(255) DEFAULT '', `phone` bigint(11) DEFAULT '0', PRIMARY KEY (`userId`) ) ENGINE=InnoDB AUTO_INCREMENT=1007 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_user -- ---------------------------- BEGIN; INSERT INTO `t_user` VALUES (1005, '小紅', '000000', 13490234321); INSERT INTO `t_user` VALUES (1006, '小明', '000000', 13490234320); COMMIT; SET FOREIGN_KEY_CHECKS = 1;