数据库准备
配置数据库的链接:
# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = adminter
spring.datasource.driverClassName = com.mysql.jdbc.Driver
#mybatis
mybatis.type-aliases-package=com.lf.entity
mybatis.mapper-locations=classpath:mapper/*.xml
版本依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
创建实体类
package com.lf.entity;
/**
* Created by LF on 2017/4/18.
*/
public class City {
private String id;
private String name;
private String stats;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStats() {
return stats;
}
public void setStats(String stats) {
this.stats = stats;
}
}
mapper接口
package com.lf.dao;
import com.lf.entity.City;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* Created by LF on 2017/4/18.
*/
@Mapper
public interface CityDao {
@Select("select * from city")
List<City> getAll();
}
此处使用的注解的方式
如果使用xml配置的话,则mapper文件放的位置由mybatis.mapper-locations
指定
测试
package com.lf;
import com.lf.dao.CityDao;
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 MybatisApplicationTests {
@Autowired
private CityDao cityDao;
@Test
public void contextLoads() {
cityDao.getAll();
}
}
事物的使用
spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement
开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional
便可。
@EnableTransactionManagement
放在启动类上