Spring Boot并没有提供mybaits的集成,但是mybatis实现了,详细信息参看:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
mybatis.mapper-locations=classpath:com/luyou/mybatis/*.xml
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.luyou.domain.User;
// 注意这个@Mapper注解必须要
@Mapper
public interface UserXMLMapper {
List<User> findAll();
long save(User user);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.luyou.dao.UserXMLMapper">
<insert id="save" parameterType="com.luyou.domain.User" useGeneratedKeys="true" keyProperty="id">
insert into user (name,birthday,createtime) values (#{name},#{birthDay},#{registerDate})
</insert>
<select id="findAll" resultType="com.luyou.domain.User">
select id,name,birthday birthDay,createtime registerDay from user
</select>
</mapper>
@Autowired
private UserXMLMapper userXMLMapper;
@Override
public List<User> queryAll() {
//List<User> list = userDao.queryAll();
//List<User> list = userRepository.findAll();
List<User> list = userXMLMapper.findAll();
return list;
}
@Override
@Transactional
public long save(User user) {
// 参数校验
Assert.notNull(user,"用户不能为空");
Assert.isTrue(user.getId() == 0, "用户id非法,必须为0");
Assert.hasLength(user.getName(), "用户名称不能为空");
Assert.notNull(user.getBirthDay(),"用户生日不能为空");
Assert.notNull(user.getRegisterDate(),"用户注册时间不能为空");
// 新增
//long pk = userDao.save(user);
// 打印主键
// 造成异常
//double result = 1 / 0;
//User afterUser = userRepository.save(user);
userXMLMapper.save(user);
long pk = user.getId();
return pk;
}
package com.luyou.dao;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import com.luyou.domain.User;
@Mapper
public interface UserAnnotationMapper {
@Insert("insert into user (name,birthday,createtime) values (#{name},#{birthDay},#{registerDate})")
@Options(useGeneratedKeys=true,keyProperty="id")
long save(User user);
@Select("select id,name,birthday birthDay, createtime registerDate from user")
List<User> findAll();
}
@Autowired
private UserAnnotationMapper userAnnotationMapper;
内容来源于网络,如有侵权,请联系作者删除!