1. 程式人生 > >SpringBoot+Mybatis 框架之 @Select註解方式搭建

SpringBoot+Mybatis 框架之 @Select註解方式搭建

最近兩天在幫同學搭建SpringBoot框架,我以往使用的是xml對映檔案的方式,這次我的同學要我使用@Select註解的方式搭建的一次。感覺挺有意思的,分享給大家。

  1、建立SpringBoot專案

    兩種方式:1、通過idea來New一個project專案。

        2、登陸 https://start.spring.io/ 上面選擇相應的配置,點選“Generate Project”按鈕下載專案,完成專案初始化。

          pom.xml檔案的配置(其中mysql的maven配置可能會和你本地的不服,會報資料庫連線的錯誤,如果出現這種問題,改一下資料庫版本就可以

):

<?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>

   <groupId>com.example</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.1</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web-services</artifactId>
      </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>

      <!--整合日誌logback+slf4j -->
      <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>1.7.2</version>
      </dependency>
   </dependencies>

   <!--<packaging>jar</packaging>-->

   <build>
      <finalName>demo</finalName>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

  application.properties檔案中的配置項(埠、資料庫配置、debug、mybatis)

#專案的啟動埠
server.port=9090
#資料庫的配置
spring.datasource.url=jdbc:mysql://localhost:3306/DBName?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username= USERNAME
spring.datasource.password= PASSWORD
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#顯示標準輸出
logging.level.com.shyroke.mapper=debug
#路徑是是實體類的路徑,和寫在所有Mapper檔案中用來掃描Mapper檔案的@Mapper註解聯用
mybatis.type-aliases-package=com.web.test.test.domain

 

  2、專案內部結構

    

  3、專案的最小功能程式碼

    這個例子是實現一個簡單的查詢功能:    

      Controller層:

 

package com.web.test.test.controller;

import com.web.test.test.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
  
  //Select By Id
    @RequestMapping("/showTeacher/{id}")
    public String selectTeacher(@PathVariable int id){
        return teacherService.selectTeacher(id).toString();
    }
    
    //Select All
    @RequestMapping("/selectAll")
    public String selectAll(){
        return teacherService.selectAll().toString();
    }

 

  

      * 有的小朋友想在return的時候直接跳轉介面去,看到@RestController了嗎,這個是ResponseBody和Controller的集合,意思是return的資料都變成json的格式,返回到前端,不會跳轉介面。

    如果想跳轉頁面的話,就需要把RestController改成Controller,就會跳轉頁面了。

      * 還有些朋友想帶著資料返回到重新定義的頁面去,對於這種需求,我建議使用“檢視直譯器解析”——ModelAndVIew。ModelAndView的用法類似於這樣:  

@RequestMapping
public ModelAndView list(Model model) {
	model.addAttribute("userList", userRepository.listUsers());
	model.addAttribute("title", "使用者管理");
        // new ModelAndView(目標頁面的路徑, 目標頁面接到的返回值名稱, api封裝好返回的資料)
	return new ModelAndView("users/list","userModel",model);
}

 

  Service層:

package com.we b.test.test.service;

import com.web.test.test.domain.Teacher;
import java.util.List;

public interface TeacherService {
    Teacher selectTeacher(int id);
    List<Teacher> selectAll();
}

  Mapper 相當於DAO層:

package com.we b.test.test.mapper;

import com.web.test.test.domain.Teacher;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface TeacherMapper {
    @Select ("SELECT * FROM Teacher WHERE id = #{id}")
    Teacher selectTeacher(int id);

    @Select("SELECT * FROM TEACHER WHERE 1=1")
    List<Teacher> selectAll();
}

  Domain 實體類:

package com.web.test.test.domain;

public class Teacher {
    private int id;
    private String name;

    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Teacher{" +"id=" + id +", name='" + name + '\'' +'}';
    }
}

  這樣就能實現@Select標籤的方式搭建SpringBoot的Mybatis框架了。挺簡單的,但是我不太喜歡用這種當時,Mybatis的繼承方式三種:@Select、@Provider、還有xml對映檔案的方式。

@Select的方式寫得太死了,不夠靈活。更多的還是使用另外兩種方式。這兩天我會再介紹另外兩種方式。