Spring-boot配置Mybatis
这一章仅仅是为了接入Mybatis,无需深究代码是否能跑起来,跑不起来的原因有很多,可能是版本问题,依赖包直接的版本差异性,此外这里仅仅作为演示,在常规的开发中一般写在XML文件中,而不用注解的方式,这里仅需理解。
1.新建一个数据库,创建一张数据表
2.新建一个项目
3.添加依赖包到工程里面
4.添加application.properties
5.编写实体类
6.编写Mapper接口
7.编写service层
8.配置PageHelper
9.编写返回数据格式
10.编写Controller层
11.运行代码
1.新建一个数据库,创建一张数据表
1.Mac平台下直接下载MySQL,直接安装即可;
2.安装Navicat for MySQL,连接数据库,然后创建表格,可视化界面
注意:自己做测试可以只创建两个字段,id和name,一切从简到繁
2.新建一个项目
1.新建一个Maven Project,与之前的项目无异
3.添加依赖包到工程里面
打开pom.xml文件,配置如下
<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>com.avalanching</groupId>
<artifactId>com.avalanching.spring.Mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>com.avalanching.spring.Mybatis</name>
<url>http://maven.apache.org</url>
<!-- 配置parent maven 自动选择最合适的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 指定一下jdk的版本 ,这里我们使用jdk 1.8 ,默认是1.6 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- spring-boot-starter-web: MVC,AOP的依赖包.... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- <version></version> 由于我们在上面指定了 parent(spring boot) -->
</dependency>
<!-- 数据库mysql依赖包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- mybatis分页拦截 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
4.添加application.properties
创建src/main/resource文件
创建File,并命名为application.properties,文件内如下
########################################################
###datasource - mySql配置数据库连接
########################################################
spring.datasource.url=jdbc:mysql://localhost:3306/avalanching_crm?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
5.编写实体类
创建一个User实体类,这里依照创建的表的名称命名,为了避免太多因为命名问题出现的问题,请用小写,或者驼峰的方式去创建,切勿含有下划线等字符。
// User.java:
package com.avalanching.com.avalanching.spring.Mybatis.bean;
public class User {
private Integer id;
private String username;
private String password;
private String moblie;
private String nickname;
private String address;
private String avatar;
private double assets;
private int contactsid;
private String car;
private String wechat;
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;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMoblie() {
return moblie;
}
public void setMoblie(String moblie) {
this.moblie = moblie;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public double getAssets() {
return assets;
}
public void setAssets(double assets) {
this.assets = assets;
}
public int getContactsid() {
return contactsid;
}
public void setContactsid(int contactsid) {
this.contactsid = contactsid;
}
public String getCar() {
return car;
}
public void setCar(String car) {
this.car = car;
}
public String getWechat() {
return wechat;
}
public void setWechat(String wechat) {
this.wechat = wechat;
}
}
6.编写Mapper接口
// Mapper.java这是一个接口,应该创建Interface
package com.avalanching.com.avalanching.spring.Mybatis.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import com.avalanching.com.avalanching.spring.Mybatis.bean.User;
public interface UserMapper {
/**
* @Select标识为一个查询方法,后面写入sql语句
* #{username}是一个占位符号
**/
@Select("select * from user where username = #{username}")
public User queryByUsername(String username);
@Select("select * from user")
public List<User> queryAllUser();
@Select("select * from User where id = #{id}")
public User queryUserById(Integer id);
@Select("select username from User where id = #{id}")
public String queryUsernameById(Integer id);
@Select("select * from User where username = #{username} AND password = #{password}")
public User queryUserByNamePassword(String name, String password);
/**
* @Insert标识为一个插入方法,后面写入sql语句
* @Options是选项配置,这里配置主键,并规定id的是否自增
**/
@Insert("Insert into User(username) values(#{username})")
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
public void save(User user);
}
7.编写service层
// UserService.java
package com.avalanching.com.avalanching.spring.Mybatis.sevice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.avalanching.com.avalanching.spring.Mybatis.bean.User;
import com.avalanching.com.avalanching.spring.Mybatis.mapper.UserMapper;
@Service
public class UserService {
@Autowired
private UserMapper mapper;
public List<User> queryAllUsers() {
return mapper.queryAllUser();
}
public User queryUserByName(String username) {
return mapper.queryByUsername(username);
}
public User queryUserById(Integer id) {
return mapper.queryUserById(id);
}
@Transactional
public void insertUser(User user) {
mapper.save(user);
}
}
8.配置PageHelper
// MybatisPageHelperConfig.java
package com.avalanching.com.avalanching.spring.Mybatis.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import com.github.pagehelper.PageHelper;
public class MybatisPageHelperConfig {
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "turn");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
9.编写返回数据格式
// BasicsModel.java
package com.avalanching.com.avalanching.spring.Mybatis.json;
/**
* 这里<T>是范型定义,如果不想定义T,可以使用Object类型
*/
public class BasicsModel<T> {
private Integer ret;
private T data;
private String message;
public Integer getRet() {
return ret;
}
public void setRet(Integer ret) {
this.ret = ret;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
10.编写Controller层
// UserController.java
package com.avalanching.com.avalanching.spring.Mybatis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.avalanching.com.avalanching.spring.Mybatis.bean.User;
import com.avalanching.com.avalanching.spring.Mybatis.json.BasicsModel;
import com.avalanching.com.avalanching.spring.Mybatis.sevice.UserService;
import com.github.pagehelper.PageHelper;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryUserByName")
public BasicsModel<User> getUserByUsername(String name) {
User user = userService.queryUserByName(name);
BasicsModel<User> model = new BasicsModel<User>();
model.setData(user);
model.setRet(0);
model.setMessage("success");
return model;
}
@RequestMapping("/queryUserById")
public BasicsModel<User> queryUserById(Integer id) {
User user = userService.queryUserById(id);
BasicsModel<User> model = new BasicsModel<User>();
model.setData(user);
if (user == null) {
model.setRet(101);
model.setMessage("not found object");
} else {
model.setRet(0);
model.setMessage("success");
}
return model;
}
@RequestMapping("/allUsers")
public BasicsModel<List<User>> getUserList(Integer pagenum, Integer pagesize) {
// 设置分页
System.out.println("pagenum: " + pagenum + "pagesize: " + pagesize);
PageHelper.startPage(pagenum, pagesize);
List<User> list = userService.queryAllUsers();
BasicsModel<List<User>> model = new BasicsModel<List<User>>();
model.setData(list);
model.setRet(0);
model.setMessage("success");
return model;
}
@RequestMapping("/save")
public BasicsModel<User> save(String username, String password, String moblie) {
User user = new User();
user.setPassword(password);
user.setUsername(username);
user.setMoblie(moblie);
userService.insertUser(user);
BasicsModel<User> model = new BasicsModel<User>();
model.setData(user);
model.setRet(0);
model.setMessage("success");
return model;
}
}