集成mybatis
2018-05-01 本文已影响0人
刘二先生说
说明
使用 mybatis 作为持久层框架,sql 语句暴露在外部,适合做大数据量的优化
实现
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:
# 数据库连接配置
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、创建文件夹,结构如下
image.png4、添加实体类和配置文件
添加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 {
//标题验证
if(messageBody.getTitle()==null || messageBody.getTitle().isEmpty()){
throw new Exception("标题不能为空");
}
//内容验证
if(messageBody.getContent()==null || messageBody.getContent().isEmpty()){
throw new Exception("内容不能为空");
}
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("消息标题");
messageBody.setContent("消息内容");
messageService.insert(messageBody);
}
}