SpringBoot整合Mybatis的簡單例子(註解版)
阿新 • • 發佈:2019-01-31
1. 資料庫準備
a.建立資料庫
CREATE DATABASE test_logistics;
b.建立表
create table wh_user (
userId int auto_increment primary key comment '使用者Id',
userCode varchar(20) unique key comment '使用者編碼',
userName varchar(20) comment '使用者名稱稱'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 comment '使用者表' ;
c.錄入資料
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'張三') ;
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'李四') ;
INSERT INTO `wh_user` (`userCode`, `userName`) VALUES(uuid(),'王五') ;
2.專案程式碼
a. 專案目錄
b.配置pom.xml
引入mybatis依賴
<!-- mybatis -->
<dependency >
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId >
</dependency>
c.配置application.properties
#資料庫配置
spring.datasource.url=jdbc:mysql://192.168.0.95:3306/test_logistics? useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=bjbshwlff
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis配置
mybatis.typeAliasesPackage=test.entity
#埠配置
server.port=8085
d.建立WhUser實體物件
package test.entity;
public class WhUser {
private Integer userId;
private String userCode;
private String userName;
public Integer getUserId() {
return userId;
}
public WhUser() {
super();
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
e.建立WhUserDao介面
package test.dao;
import org.apache.ibatis.annotations.Select;
import test.entity.WhUser;
public interface WhUserDao {
@Select("SELECT * FROM wh_user WHERE userId = #{userId}")
WhUser getUserInfo(WhUser user);
}
f.控制層和service層程式碼
testController.java程式碼
@RequestMapping("/testUserInfo.show")
public String testUserInfo(){
WhUser user = new WhUser();
user.setUserId(1);
user = testService.getUserInfo(user);
return user.getUserName();
}
testService.java程式碼
package test.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.dao.WhUserDao;
import test.entity.WhUser;
@Service
@Transactional(rollbackFor = Exception.class)
public class testService {
@Resource
private WhUserDao whUserDao;
public WhUser getUserInfo(WhUser user){
return whUserDao.getUserInfo(user);
}
}
g.配置Application.java
通過@MapperScan註解進行dao檔案的掃描
@SpringBootApplication //工程啟動自動掃描的基礎註解
@MapperScan("test.dao")//掃描dao層程式碼
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 執行專案
a.在啟動檔案Application.java中,右擊–> Run As –> java Application,啟動專案
b.開啟瀏覽器,輸入地址,檢視返回資料,如下圖