由于項(xiàng)目中使用mybatis比較多,并且mybatis這種半orm形式的持久層框簡(jiǎn)單又不失可控性,所以這一章簡(jiǎn)單講一下springboot與mybatis的集成。
mybatis-spring-boot-starter
官方說(shuō)明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
Springboot整合mybatis主要有兩種方案,一種是使用注解解決,另一種是簡(jiǎn)化后的傳統(tǒng)方式。
當(dāng)然兩種方式首先都得添加pom依賴(lài),這是必不可少的
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
無(wú)配置文件注解
即所有問(wèn)題都通過(guò)注解解決,這也是我喜歡的方式
1、添加pom文件
<!-- mybatis相關(guān)-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2、application.properties 添加相關(guān)配置
mybatis.mapperLocations=classpath*:/mapper/*.xml
在啟動(dòng)類(lèi)中添加對(duì)mapper包掃描@MapperScan。
@MapperScan(basePackages = {"com.liangliang.lessons.mapper"})
@SpringBootApplication
public class LessonsApplication {
public static void main(String[] args) {
SpringApplication.run(LessonsApplication.class, args);
}
}
3、開(kāi)發(fā)mapper
@Mapper
public interface UserMapper {
List<UserEntity> getAll();
UserEntity getOne(Long id);
void insert(UserEntity user);
void update(UserEntity user);
void delete(Long id);
}
為了更接近生產(chǎn)我特地將user_sex、nick_name兩個(gè)屬性在數(shù)據(jù)庫(kù)加了下劃線(xiàn)和實(shí)體類(lèi)屬性名不一致,另外user_sex使用了枚舉。
4、使用
上面三步就基本完成了相關(guān)dao層開(kāi)發(fā),使用的時(shí)候當(dāng)作普通的類(lèi)注入進(jìn)入就可以了。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
UserMapper userMapper;
@Test
public void getAll() throws Exception {
System.out.println("----------userMapper:"+userMapper);
userMapper.getOne(1l);
}
@Test
public void getOne() throws Exception {
}
@Test
public void insert() throws Exception {
}
@Test
public void update() throws Exception {
}
@Test
public void delete() throws Exception {
}
}
到此,單元測(cè)試完成,controller中寫(xiě)法在代碼中有詳細(xì)的注解,直接使用即可,對(duì)于另一種在mapper中寫(xiě)sql注解的方式,這里不做說(shuō)明,這種做法對(duì)代碼侵入性太高,不建議使用,網(wǎng)上也有相應(yīng)教程,感興趣的小伙伴可以自行寫(xiě)。
同樣代碼地址在
https://github.com/liangliang1259/daily-lessons.git 中的項(xiàng)目lessons-4