倉庫地址:spring-boot-learning
歡迎star、fork,給作者一些鼓勵
前言
Mybatis 初期使用比較麻煩,需要各種配置文件、實體類、Dao 層映射關聯、還有一大推其它配置。mybatis-spring-boot-starter
就是 Spring Boot+ Mybatis 可以完全註解不用配置文件,也可以簡單配置輕鬆上手。
mybatis-spring-boot-starter
官方說明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
其實就是 Mybatis 看 Spring Boot 這麼火熱也開發出一套解決方案來湊湊熱鬧,但這一湊確實解決了很多問題,使用起來確實順暢了許多。mybatis-spring-boot-starter
主要有兩種解決方案,一種是使用註解解決一切問題,一種是簡化後的老傳統。
當然任何模式都需要首先引入mybatis-spring-boot-starter
的 Pom 文件,現在最新版本是 2.0.1
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
我一般使用的是XML極簡模式,可能是由於之前用的hibernate用習慣了
極簡 xml 版本
極簡 xml 版本保持映射文件的老傳統,接口層只需要定義空方法,系統會自動根據方法名在映射文件中找對應的 Sql .
1 添加相關 Maven 文件
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
完整的 Pom 包這裏就不貼了,大家直接看源碼
2、application.yml
相關配置
推薦使用application.yml
進行配置,其實使用application.yml
或者application.properties
都是一樣的效果,application.yml
最終是轉換爲application.properties
進行生效的,只不過application.yml
視覺效果看起來更加明瞭。新建項目默認爲application.properties
,直接改爲application.yml
,另外新增一個application-test.yml
用戶不同環境使用不同的配置文件用。
application.yml
配置:
#指定配置文件爲test
spring:
profiles:
active: test
#配置Mybatis
mybatis:
type-aliases-package: com.niaobulashi.entity
mapper-locations: classpath:mapper/*.xml
configuration:
# 開啓駝峯命名轉換,如:Table(create_time) -> Entity(createTime)。不需要我們關心怎麼進行字段匹配,mybatis會自動識別`大寫字母與下劃線`
map-underscore-to-camel-case: true
#打印SQL日誌
logging:
level:
com.niaobulashi.dao: DEBUG
application-test.yml
配置:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
Spring Boot 會自動加載 spring.datasource.*
相關配置,數據源就會自動注入到 sqlSessionFactory 中,sqlSessionFactory 會自動注入到 Mapper 中,對了,你一切都不用管了,直接拿起來使用就行了。
在啓動類中添加對 mapper 包掃描@MapperScan
@SpringBootApplication
@MapperScan("com.niaobulashi.dao")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
或者直接在 Mapper 類上面添加註解@Mapper
,建議使用上面那種,不然每個 mapper 加個註解也挺麻煩的
3、添加 User 的實例
@Data
public class SysUserEntity implements Serializable {
private static final long serialVersionUID = 1L;
//用戶ID
private Long userId;
//用戶名
private String username;
//密碼
private String password;
//鹽
private String salt;
//郵箱
private String email;
//手機號
private String mobile;
//狀態 0:禁用 1:正常
private Integer status;
//創建時間
private Date createTime;
}
4、添加 User 的映射文件
<mapper namespace="com.niaobulashi.dao.SysUserDao">
<!--查詢用戶的所有菜單ID-->
<select id="queryUserInfo" resultType="com.niaobulashi.entity.SysUserEntity">
SELECT
ur.*
FROM
sys_user ur
WHERE
1 = 1
AND ur.user_id = #{userId}
</select>
</mapper>
其實就是把上個版本中 Mapper 的 Sql 搬到了這裏的 xml 中了
5、編寫 Mapper 層的代碼
public interface SysUserDao {
/**
* 根據userId查詢用戶信息
* @param userId 用戶ID
*/
List<SysUserEntity> queryUserInfo(Long userId);
}
6、編寫Service層的代碼
SysUserService
接口類:
public interface SysUserService {
/**
* 查詢用戶的所有菜單ID
*/
List<SysUserEntity> queryUserInfo(Long userId);
}
SysUserServiceImpl
實現類:
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
@Resource
private SysUserDao sysUserDao;
/**
* 查詢用戶的所有菜單ID
* @param userId
* @return
*/
@Override
public List<SysUserEntity> queryUserInfo(Long userId) {
return sysUserDao.queryUserInfo(userId);
}
}
7、測試
經過上面5個步驟就可以完成基本的接口開發,省去了Controller層的開發
@RunWith(SpringRunner.class)
@SpringBootTest
public class MabatisTest {
private final static Logger logger = LoggerFactory.getLogger(MabatisTest.class);
@Autowired
private SysUserService sysUserService;
@Test
public void queryUserInfo() throws Exception {
SysUserEntity userEntity = new SysUserEntity();
userEntity.setUserId(1L);
List<SysUserEntity> list = sysUserService.queryUserInfo(userEntity.getUserId());
logger.info("list:" + list);
}
}
最後項目目錄結構
總結
SpringBoot和Mybatis這對CP,完美