說明
使用 mybatis 作為持久層框架,sql 語句暴露在外部,適合做大數(shù)據(jù)量的優(yōu)化
實(shí)現(xiàn)
1、引入 jar 包
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、在 application.yml 中添加配置
spring:
# 數(shù)據(jù)庫連接配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/build
username: root
password: root
#配置mybatis
mybatis:
mapper-locations: classpath:mapper/*.xml
3、創(chuàng)建文件夾,結(jié)構(gòu)如下

image.png
4、添加實(shí)體類和配置文件
添加model類、mapper類、mapper配置文件:使用mybatis-generator插件自動生成
5、在啟動類添加注解
@SpringBootApplication
@MapperScan(basePackages = "com.liucz.message.mapper")
public class MessageApplication {
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
}
6、添加service
import com.liucz.message.mapper.MessageBodyMapper;
import com.liucz.message.model.message.MessageBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageService {
@Autowired
MessageBodyMapper messageBodyMapper;
/**
* 插入一條消息體
* @param messageBody
*/
public void insert(MessageBody messageBody) throws Exception {
//標(biāo)題驗(yàn)證
if(messageBody.getTitle()==null || messageBody.getTitle().isEmpty()){
throw new Exception("標(biāo)題不能為空");
}
//內(nèi)容驗(yàn)證
if(messageBody.getContent()==null || messageBody.getContent().isEmpty()){
throw new Exception("內(nèi)容不能為空");
}
messageBodyMapper.insertSelective(messageBody);
}
}
7、添加測試類
import com.liucz.message.model.message.MessageBody;
import com.liucz.message.servicce.MessageService;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MessageServiceTest {
@Autowired
MessageService messageService;
/**
* 插入一條消息體
* @param
*/
@Test
public void insert() throws Exception {
MessageBody messageBody = new MessageBody();
messageBody.setTitle("消息標(biāo)題");
messageBody.setContent("消息內(nèi)容");
messageService.insert(messageBody);
}
}