mybatis参考文档: https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
<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> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.5</version> </dependency>
# mybatis mybatis.type-aliases-package=com.luckey.flashsale.domain mybatis.configuration.map-underscore-to-camel-case=true mybatis.configuration.default-fetch-size=100 mybatis.configuration.default-statement-timeout=3000 mybatis.mapperLocations = classpath:com/luckey/flashsale/dao/*.xml # druid spring.datasource.url=jdbc:mysql://127.0.0.1:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false spring.datasource.username=root spring.datasource.password=1234 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.filters=stat spring.datasource.maxActive=2 spring.datasource.initialSize=1 spring.datasource.maxWait=60000 spring.datasource.minIdle=1 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=select 'x' spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxOpenPreparedStatements=20
控制器里新增一个查询db方法
@RequestMapping("/db/get") @ResponseBody public Result<User> dbGet() { User user = userService.getById(1); return Result.success(user); }
依次新建User,UserDao,UserService对象
@Mapper public interface UserDao { @Select("select * from user where id = #{id}") public User getById(@Param("id") int id); } @Service public class UserService { @Resource private UserDao userDao; public User getById(int id){ return userDao.getById(id); } }
重启服务查看页面:
验证一下mybatis的事务,简单思路:db中已有id为1的数据,先插入一条id为3的记录,然后再插入一条id为1的会报错(主键冲突),验证一下id为3的记录是否会回滚.
cotroller
@RequestMapping("/db/tx") @ResponseBody public Result<Boolean> dbTx() { Boolean result = userService.tx(); return Result.success(result); }
dao
@Insert("insert into user(id,name) values (#{id}, #{name})") public int insert(User user);
service
@Transactional public Boolean tx() { User u1 = new User(); u1.setId(2); u1.setName("2222"); userDao.insert(u1); User u2 = new User(); u2.setId(1); u2.setName("11111"); userDao.insert(u2); return true; }
重启服务访问 /db/tx 报错,发现数据库中没有新增记录
备注:如果去掉@Transactional 注解或者捕捉异常,则会新增一条id为2的记录