Spring-boot配置Mybatis
這一章僅僅是為了接入Mybatis匕荸,無需深究代碼是否能跑起來车摄,跑不起來的原因有很多,可能是版本問題奏寨,依賴包直接的版本差異性蚤告,此外這里僅僅作為演示,在常規(guī)的開發(fā)中一般寫在XML文件中服爷,而不用注解的方式杜恰,這里僅需理解。
1.新建一個(gè)數(shù)據(jù)庫仍源,創(chuàng)建一張數(shù)據(jù)表
2.新建一個(gè)項(xiàng)目
3.添加依賴包到工程里面
4.添加application.properties
5.編寫實(shí)體類
6.編寫Mapper接口
7.編寫service層
8.配置PageHelper
9.編寫返回?cái)?shù)據(jù)格式
10.編寫Controller層
11.運(yùn)行代碼
1.新建一個(gè)數(shù)據(jù)庫心褐,創(chuàng)建一張數(shù)據(jù)表
1.Mac平臺下直接下載MySQL,直接安裝即可笼踩;
2.安裝Navicat for MySQL逗爹,連接數(shù)據(jù)庫,然后創(chuàng)建表格,可視化界面
注意:自己做測試可以只創(chuàng)建兩個(gè)字段掘而,id和name挟冠,一切從簡到繁
2.新建一個(gè)項(xiàng)目
1.新建一個(gè)Maven Project,與之前的項(xiàng)目無異
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 自動(dòng)選擇最合適的版本 -->
<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 ,默認(rèn)是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>
<!-- 數(shù)據(jù)庫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
創(chuàng)建src/main/resource文件
創(chuàng)建File,并命名為application.properties斑胜,文件內(nèi)如下
########################################################
###datasource - mySql配置數(shù)據(jù)庫連接
########################################################
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.編寫實(shí)體類
創(chuàng)建一個(gè)User實(shí)體類控淡,這里依照創(chuàng)建的表的名稱命名,為了避免太多因?yàn)槊麊栴}出現(xiàn)的問題止潘,請用小寫掺炭,或者駝峰的方式去創(chuàng)建,切勿含有下劃線等字符凭戴。
// 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這是一個(gè)接口涧狮,應(yīng)該創(chuàng)建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標(biāo)識為一個(gè)查詢方法,后面寫入sql語句
* #{username}是一個(gè)占位符號
**/
@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標(biāo)識為一個(gè)插入方法么夫,后面寫入sql語句
* @Options是選項(xiàng)配置者冤,這里配置主鍵,并規(guī)定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.編寫返回?cái)?shù)據(jù)格式
// 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) {
// 設(shè)置分頁
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;
}
}