SpringBoot整合MyBatis完成資料獲取
SpringBoot我就不詳細介紹了,約定大於配置,上手十分簡單,開發快速簡潔且功能強大。
MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和對映原生資訊,將介面和 Java 的 POJOs(Plain Old Java Objects,普通的 Java物件)對映成資料庫中的記錄。
用xml配置的方法我就不講了,xml的對映配置總覺得有點麻煩。使用mybatis generator 自動生成程式碼的方式,介面定義和對映離散在不同的檔案中,閱讀起來不是很方便。於是,準備使用mybatis的註解方式實現對映。
首先快速構建springboot專案這裡就不說了
專案架構:
1.pom.xml檔案加上mybatis的依賴
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version >
</dependency>
2.application.properties配置檔案中加入如下配置資訊:
spring.datasource.url=jdbc:mysql://localhost/questionbank?useSSL=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
3.實體層entity(和資料庫表相對應):
package olcp.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* 題目
*/
@Entity
@Table(name="question")
public class question implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 題目Id
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Integer id;
/**
* 題目內容
*/
@Column
private String content;
/**
* 題目選項
*/
@Column
private String option;
/**
* 題目圖片地址
*/
@Column
private String imgurl;
/**
* 題目型別
*/
@Column
private Integer type;
/**
* 難度
*/
@Column
private Integer difficulty;
/**
* 題目建立時間
*/
@Column
private Date creation_time;
/**
* 題目方向
*/
@Column
private String direction;
/**
* 題目熱度
*/
@Column
private Integer hot;
@Column
@Transient
private question question;
public question getQuestion() {
return question;
}
public void setQuestion(question question) {
this.question = question;
}
public question(){
}
public question(String content, String option, String imgurl, Integer type, Integer difficulty, Date
creation_time, String direction, Integer hot) {
this.content = content;
this.option = option;
this.imgurl = imgurl;
this.type = type;
this.difficulty = difficulty;
this.creation_time = creation_time;
this.direction = direction;
this.hot = hot;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Date getCreation_time() {
return creation_time;
}
public void setCreation_time(Date creation_time) {
this.creation_time = creation_time;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public Integer getHot() {
return hot;
}
public void setHot(Integer hot) {
this.hot = hot;
}
}
4.mapper層(介面)
package olcp.mapper;
import olcp.entity.question;;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface QuestionMapper {
@Select("SELECT * FROM question WHERE DIRECTION = #{direction}")
List<question> findByDirection(@Param("direction") String direction);
@Insert("INSERT INTO question(DIRECTION) VALUES(#{direction})")
int insert(@Param("direction") String direction);
}
多種註解配置如下:
傳參方式:
1.使用@Param,上面的程式碼已經展示了這種用法
2.使用Map
@Insert("INSERT INTO question(DIRECTION) VALUES(" + "#{direction, jdbcType=VARCHAR})")
int insertByMap(Map<String, Object> map);
對於Insert語句中需要的引數,我們只需要在map中填入同名的內容即可
Map<String, Object> map = new HashMap<>();
map.put("direction","c++");
QuestionMapper.insertByMap(map);
3.使用物件
使用普通的java物件作為查詢條件的引數:
@Insert("INSERT INTO question(DIRECTION) VALUES(#{direction})")
int insertByQuestion(question question1);
只需要語句中的#{direction}對應question物件中的direction屬性即可。
question q = new question();
q.setDirection("c++");
QuestionMapper.insertByQuestion(q);
增刪改查(CRUD):
@Select("SELECT * FROM question WHERE DIRECTION = #{direction}")
question findByDirection(@Param("direction") String direction);
@Insert("INSERT INTO question(DIRECTION) VALUES(#{direction})")
int insertByDirection(question question1);
@Update("UPDATE question SET CONTENT = #{content} WHERE DIRECTION = #{direction}")
void update(question question1);
@Delete("DELETE FROM question WHERE ID = #{id}")
void delete(Integer id);
返回結果繫結
通過@Results和@Result註解來進行繫結
@Results({
@Result(property = "direction", column = "DIRECTION"),
@Result(property = "content", column = "CONTENT")
})
@Select("SELECT DIRECTION, CONTENT FROM question")
List<question> findAll();
5.控制層(實現邏輯)
package olcp.web.admin;
import olcp.entity.question;
import olcp.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/admin/question")
public class adminQuestionController {
@Autowired
private QuestionMapper QuestionMapper;
/**
* 檢視對應方向的題目
*/
@RequestMapping("/all")
public List<question> getall(String direction) {
List<question> questions = QuestionMapper.findByDirection(direction);
return questions;
}
}
資料庫表設計:
下面執行springboot專案,在瀏覽器上輸入對應的訪問路徑,可以看到對應的json資料
我這裡配的是http://localhost:8081/tc/admin/question/all?direction=java
當然我這裡只是舉的一個簡單的例子,直接把資料介面中的json資料顯示到前臺了,並沒有用h5+css+js或者前端框架那些去渲染資料了,有興趣的同學可以用到自己的前後端分離的專案中去。
MyBatis的內容還遠不止我講的這些,還有很多內層的以及一些註解什麼的我就沒講了,這些到後面有機會再補充,這裡先介紹SpringBoot整合MyBatis完成資料介面獲取的操作(後端部分)。