1. 程式人生 > >Spring Boot註解方式集成Mybatis

Spring Boot註解方式集成Mybatis

face batis update pac conn src jar包 local code

一、無配置文件註解版 1.pom文件必要jar包的引入
1 <dependency>
2 <groupId>mysql</groupId>
3 <artifactId>mysql-connector-java</artifactId>
4 </dependency>
5 <dependency>
6 <groupId>org.mybatis.spring.boot</groupId>
7 <artifactId>mybatis-spring-boot-starter</artifactId>
8
<version>1.1.1</version> 9 </dependency>

2.application.properties添加相關配置   SpringBoot會自動加載application.properties配置文件,會讀取spring.datasource.*相關的配置,數據源會自動註入到sqlSessionFactory中,sqlSessionFactory會自動註入到Mapper中   會掃描的model實體類路徑
1 mybatis.type-aliases-package=com.neo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://
localhost:3306/test1? 2 useUnicode=true&characterEncoding=utf-8 3 spring.datasource.username = root 4 spring.datasource.password = root

3.建立啟動類
@SpringBootApplication @MapperScan("com.neo.mapper") 
public class Application { 
    public static void main(String[] args) {         
        SpringApplication.run(Application.
class, args); } }

[email protected]

4.mapper文件配置
 1 public interface UserMapper { 
 2 @Select("SELECT * FROM users") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) List<UserEntity> getAll();
 3 @Select("SELECT * FROM users WHERE id = #{id}") 
 4 @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), 
 5 @Result(property = "nickName", column = "nick_name") }) 
 6 UserEntity getOne(Long id); @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})") void insert(UserEntity user); 
 7 @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}") 
 8 void update(UserEntity user); 
 9 @Delete("DELETE FROM users WHERE id =#{id}") 
10 void delete(Long id); }

5測試類 技術分享

Spring Boot註解方式集成Mybatis