配置部分
在pom.xml
中加入如下部分,并使用maven
进行安装 (maven install
)
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
在resources/application.properties
中,设置spring.datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/db_name
spring.datasource.username=
spring.datasource.password=
在Java文件中构建SQL语句
在XXXApplication.java文件中,与@SpringBootApplication
在一起的地方加入@MapperScan(xxx.xxx.xxx.mapper)
,使Spring Boot能够从这个package中找到mappers并构建成JavaBeans
在上述的package中,加入一些mapper (interface),这样就可以在其他地方使用@Autowired
取得Spring Boot注入的mapper
批处理
批处理是指讲多个insert、update、delete语句放在一个SQL session里执行,提高通信效率,减少通信时间。常用的方法就是在service中实现,例如:
public class ExpenseService {
@Autowired
SqlSessionFactory sqlSessionFactory;
public void batchInsert(List<Expense> expenseList) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, true);
for (Expense expense : expenseList) {
sqlSession.insert("xxx.xxx.xxx.mapper.ExpenseMapper.addExpense", expense);
}
sqlSession.close();
}
}
常用的注解
@Insert
、@Update
、@Delete
、@Select
是四个基本的CURD语句,SQL语句中可以用#{variable}
来获得其中variable的值并进行字符串escape
@Options
可以设置访问数据的一些选项,例如:
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "sid")
可以将insert或者update语句中id这个column存放到传入实例的sid
这个field里面
@Results
可用于将结果的columns存入到返回实例的fields里,每个column都可以使用@Result
进行描述如何映射,下面这个例子分别将数据库中is_domestic, department_id映射到instance的isDomestic, departmentId中这两个fields里面
@Results(value = {
@Result(column = "is_domestic", property = "isDomestic"),
@Result(column = "department_id", property = "departmentId")
})
@Param
在函数有多个变量时,可以将函数变量转换为SQL语句中的#{}
这些变量里面
在XML文件中构建SQL语句
若使用xml构建MyBatis语句的调用,建议在resources/application.properties
加入如下设置
mybatis.config-location=classpath:mybatis-config.xml
To be continued