新入職的猿,師傅給了一個小任務,用STS寫一個springboot整合mybatis的小demo。由於之前沒用過STS和eclipse,所以聽到這個任務還是比較懵逼的,經過一天的摸索,慢慢的摸出了門道,寫一篇小博客和大家分享一下,希望能幫助到和我一樣剛上手的小白,同時也希望大佬能給點建議!
首先從STS配置開始
什麼是STS?
STS就是spring tool suite的縮寫,是基於eclipse的、開發spring應用的定製的開發環境。
下載STS,直接到spring官網上下載即可,我下載的是當前的最新版。
下載之後直接解壓,得到如下目錄:
解壓後直接打開SpringToolSuite4.exe程序,彈出如下窗口:
需要配置workspace,就是存放項目的地方。
配置好後點擊launch。
啓動之後,會發現界面和eclipse如出一轍。
下面對STS進行配置。
外觀配置:
單擊windows->preference->general->appearance,可以更換主題,我個人比較喜歡黑色,比較護眼。
配置JDK
單擊windows->preference->java->installed JREs
會發現自帶的有一個jre1.8.0_201。
單擊add
選擇standard VM,點擊next
點擊directory,選擇JDK安裝的路徑
我的已經配置好了,所以會出現the jre name is already in use.
點擊finish。
選擇JDK,單擊apply。
compiler->compiler compliance settings
選擇編譯項目的JDK版本,我選擇的1.8,和我的JDK版本保持一致。
配置maven
windows->preference->maven->installations->add
添加之前下載好的maven
導入全局setting.xml文件並自動配置maven倉庫.
下面就可以寫springboot集成mybatis的小demo了
新建項目的目錄結構,其實和idea建的spring項目差不多。
開始寫代碼
目錄結構如下:
User.java
package com.firsttask.model;
public class User {
private Integer id;
private String account;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", account='" + account + '\'' +
", password='" + password + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserMapper.java
package com.firsttask.mapper;
import com.firsttask.model.*;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
List<User> findAll();
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "../config/mybatis-3-mapper.dtd">
<mapper namespace="com.firsttask.mapper.UserMapper">
<select id="findAll" resultType="Map">
select account,password from user
</select>
</mapper>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#Mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
Demo5ApplicationTests.java
package com.firsttask;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.firsttask.mapper.UserMapper;
import com.firsttask.model.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo5ApplicationTests {
@Autowired
UserMapper userMapper;
@Test
public void selectAll() {
List<User> userList=userMapper.findAll();
for (int i=0;i<userList.size();i++){
System.out.println(userList.get(i));
}
}
}
運行結果: