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

最近兩天在幫同窗搭建SpringBoot框架,我以往使用的是xml映射文件的方式,此次個人同窗要我使用@Select註解的方式搭建的一次。感受挺有意思的,分享給你們。javascript

  一、建立SpringBoot項目前端

    兩種方式:一、經過idea來New一個project項目。java

        二、登錄 https://start.spring.io/ 上面選擇相應的配置,點擊「Generate Project」按鈕下載項目,完成項目初始化。mysql

          pom.xml文件的配置(其中mysql的maven配置可能會和你本地的不服,會報數據庫鏈接的錯誤,若是出現這種問題,改一下數據庫版本就能夠):web

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

#項目的啓動端口
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、項目內部結構sql

    

  三、項目的最小功能代碼數據庫

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

      Controller層:json

 

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的方式寫得太死了,不夠靈活。更多的仍是使用另外兩種方式。這兩天我會再介紹另外兩種方式。

相關文章
相關標籤/搜索