前言
這是我學習 Spring Boot 的第三篇文章,終於可以見到效果了。錯過的同學可以看看之前的文章
我們為什么要學習 Spring Boot
Spring Boot 入門詳細分析
在入門的基礎上,我們現在已經能運行起來項目了,至少保證 Hello World 是正常的,下面直接進入正題。
准備數據庫環境
創建表
CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `name` varchar(50) DEFAULT NULL COMMENT '姓名', `age` int(2) DEFAULT NULL COMMENT '年齡', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
工程相關
項目目錄結構
編輯配置文件 application.properties 、pom.xml
編輯 application.properties 文件
## 數據源配置 spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_test?useUnicode=true&characterEncoding=utf8 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=root ## Mybatis 配置 # 配置為 com.kris.entry 指向實體類包路徑。 mybatis.typeAliasesPackage=com.kris.entry
編輯 pom.xml 文件
<?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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.kris</groupId> <artifactId>demo2</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo2</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <!-- 這個 mybatis 的版本不能太低,否則有問題,無法導入相關注解 --> <mybatis-spring-boot>1.3.2</mybatis-spring-boot> <mysql-connector>5.1.39</mysql-connector> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <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>${mybatis-spring-boot}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
編寫實體類
package com.kris.entry; /** * Created by Kris on 2019/3/20. */ public class User { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
編寫 DAO 接口
package com.kris.dao; import com.kris.entry.User; import org.apache.ibatis.annotations.*; /** * Created by Kris on 2019/3/20. */ @Mapper public interface UserDao { /** * 新增用戶 * @param user */ @Insert("insert into t_user(id,name,age) values (#{id},#{name},#{age})") boolean add(User user); /** * 刪除用戶 * @param id */ @Delete("delete from t_user where id = #{id} ") boolean delete(Integer id); /** * 根據用戶 ID 修改用戶 * @param user */ @Update("update t_user set name = #{name},age = #{age} where id = #{id} ") boolean update(User user); /** * 根據 ID 查找用戶 * @param id * @return */ @Select("select * from t_user where id = #{id}") User select(Integer id); }
@Mapper 的作用:實話說,都說有作用,但是我測試了一波,去掉這個也沒有問題。誰知道 @Mapper 的作用,麻煩告訴我一聲!
@Insert @Delete @Update @Select 對應數據庫的增刪改查操作。
另外,在綁定參數的過程中,因為只有一個參數,所以可以自動綁定,若是有多個參數,那就需要@Param("XXX") 與 SQL 語句中的參數綁定了。例如:
@Update("update t_user set name = #{name},age = #{age} where id = #{id} ") boolean update(@Param("name")String name,@Param("age")Integer age,@Param("id")Integer id);
編寫 Service 接口以及 Service 實現
這個模塊和之前的 SSM 項目沒有區別,當前就這個 Demo 來說,也可以不寫這個層。
package com.kris.service; import com.kris.entry.User; /** * Created by Kris on 2019/3/20. */ public interface UserService { boolean add(User user); boolean delete(Integer id); boolean update(User user); User select(Integer id); }
package com.kris.service.impl; import com.kris.dao.UserDao; import com.kris.entry.User; import com.kris.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by Kris on 2019/3/20. */ @Service public class UserServiceImpl implements UserService{ @Autowired UserDao userDao; @Override public boolean add(User user) { return userDao.add(user); } @Override public boolean delete(Integer id) { return userDao.delete(id); } @Override public boolean update(User user) { return userDao.update(user); } @Override public User select(Integer id) { return userDao.select(id); } }
編寫 Controller 層
package com.kris.controller; import com.kris.entry.User; import com.kris.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by Kris on 2019/3/20. */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/add",method = RequestMethod.POST) public boolean addUser(User user){ return userService.add(user); } @RequestMapping(value = "/delete",method = RequestMethod.DELETE) public boolean deleteUser(Integer id){ return userService.delete(id); } @RequestMapping(value = "/update",method = RequestMethod.PUT) public boolean updateUser(User user){ return userService.update(user); } @RequestMapping(value = "/select",method = RequestMethod.GET) public User selectUser(Integer id){ return userService.select(id); } }
@RestController 這個注解等於 @Controller + @ResponseBody 訪問結果以 JSON 格式返回,其它的都是以前的知識。
運行項目
package com.kris; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.kris.dao") public class Demo2Application { public static void main(String[] args) { SpringApplication.run(Demo2Application.class, args); } }
SpringBootApplication:開啟組件掃描和自動配置。
到這里知道了為什么會有 @Mapper 這個注解了,在之前我們想要實現 Dao 層的實現,我們使用 Mapper 動態代理開發機制,但是外在表現就是在 DAO 接口上添加 @Mapper 即可。但是這樣我們需要為每一個 Dao 文件添加注解,太麻煩,現在為了方便,簡化操作我們可以直接使用 @MapperScan 進行掃描即可。另外,@MapperScan 這個注解還可以同時掃描多個文件,中間用逗號隔開。我們可以這樣寫
@MapperScan("com.kris.dao","com.yu.mapper")
測試
測試這里我使用的 Postman ,當然你也可以使用 Restlet 。呃呃,測試就自己來吧,我就不截圖了。實在不行,你就用瀏覽器直接訪問啊,但是注意設置請求的形式呦。