配置
POM文件
<parent>
<groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>1.5.6.RELEASEversion> <relativePath /> parent> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>tk.mybatisgroupId> <artifactId>mapper-spring-boot-starterartifactId> <version>RELEASEversion> dependency> <dependency> <groupId>com.github.pagehelpergroupId> <artifactId>pagehelper-spring-boot-starterartifactId> <version>RELEASEversion> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> dependency> <dependency> <groupId>org.mybatis.spring.bootgroupId> <artifactId>mybatis-spring-boot-starterartifactId> <version>1.3.1version> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-jdbcartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> dependencies>
同一环境1.5.7.RELEASE版本的Spring-boot会抛Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver异常,1.5.6.RELEASE以及1.5.5.RELEASE版本亲测没问题
application.properties配置文件
#数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=741852
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis&&通用Mapper
mybatis.type-aliases-package=com.karle.bean
mybatis.mapper-locations=classpath:mapper/*.xml
mapper.mappers=com.karle.tk.TkMapper
mapper.identity=MYSQL
#分页插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#log
logging.file=logger.log
logging.level.*=debug
映射实体(省略字段get、set)
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Table; @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 名称 */ @Column(name = "name") private String name; /** * 年龄 */ @Column(name = "age") private Integer age; /** * 身份编号 */ @Column(name = "card_no") private Integer cardNo; /** * 生日 */ @Column(name = "birthday") private Date birthday; }
本地通用Mapper接口(继承通用Mapper接口)
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface TkMapper<T> extends Mapper<T>, MySqlMapper<T> { }
Mapper接口:基本的增、删、改、查方法
MySqlMapper:针对MySQL的额外补充接口,支持批量插入
业务接口(继承“本地通用Mapper接口”)
import org.apache.ibatis.annotations.Param;
import com.karle.bean.User;
import com.karle.tk.TkMapper;
public interface UserMapper extends TkMapper<User> { public User selectByCardNo(@Param("cardNo") int cardNo); }
Spring-boot启动类,@MapperScan仅扫描业务接口包,不能扫描本地通用Mapper接口包,否则报java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class异常
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = { "com.karle.mapper" }) public class SpringBootMyBatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMyBatisApplication.class, args); } }
通过使用@MapperScan可以指定要扫描的Mapper类的包的路径,比如:
- @SpringBootApplication
- @MapperScan("com.kfit.*.mapper")
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
或者:
- @SpringBootApplication
- @MapperScan("com.kfit.mapper")
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
可以根据包的结构指定不同的表达式。
使用@MapperScan注解多个包
可以使用如下的方式指定多个包:
- @SpringBootApplication
- @MapperScan({"com.kfit.demo","com.kfit.user"})
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
如果mapper类没有在Spring Boot主程序可以扫描的包或者子包下面,可以使用如下方式进行配置:
- @SpringBootApplication
- @MapperScan({"com.kfit.*.mapper","org.kfit.*.mapper"})
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
单元测试
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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; import com.github.pagehelper.PageHelper; import com.karle.bean.User; import com.karle.mapper.UserMapper; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootMyBatisApplicationTests { @Autowired private UserMapper mapper; // 插入一条新记录 @Test public void insertOne() { User newUser = new User(); int cardNo = (int) (Math.random() * 10000000); newUser.setAge(24); newUser.setBirthday(new Date()); newUser.setName(cardNo + "用户"); newUser.setCardNo(cardNo); mapper.insertSelective(newUser); System.out.println("插入成功"); } // 批量插入记录 @Test public void insertMore() { List recordList = new ArrayList(); for (int i = 0; i < 2; i++) { User newUser = new User(); int cardNo = (int) (Math.random() * 10000000); newUser.setAge(26); newUser.setBirthday(new Date()); newUser.setName(cardNo + "批量插入用户"); newUser.setCardNo(cardNo); recordList.add(newUser); } mapper.insertList(recordList); System.out.println("批量插入成功"); } // 根据唯一编号查询用户(通用Mapper查询) @Test public void selectByCardNo() { User paramBean = new User(); paramBean.setCardNo(6647403); User dbUser = mapper.selectOne(paramBean); if (dbUser != null) { System.out.println("数据库用户(通用Mapper查询):" + dbUser.getName()); return; } System.out.println("查无此用户"); } // 根据唯一编号查询用户(XML查询) @Test public void selectByCardNoByXml() { User dbUser = mapper.selectByCardNo(6105967); if (dbUser != null) { System.out.println("数据库用户(XML查询):" + dbUser.getName()); return; } System.out.println("查无此用户"); } // 根据年龄查询一组用户 @Test public void selectByAge() { User paramBean = new User(); paramBean.setAge(24); List dbUserList = mapper.select(paramBean); System.out.println("总共查询数:" + dbUserList.size()); } // 分页查询用户 @Test public void selectByPage() { PageHelper.offsetPage(1, 5); List dbUserList = mapper.select(null); for (User item : dbUserList) { System.out.println("分页用户:" + item.getName()); } } // 更新用户信息 @Test public void updateOneInfo() { User paramBean = new User(); paramBean.setId(1); paramBean.setAge(26); mapper.updateByPrimaryKeySelective(paramBean); System.out.println("更新成功"); } }
事物的使用
spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement
开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional
便可。
@EnableTransactionManagement
放在启动类上