springboot mybatis 整合

  1. pom.xml 添加mysql,mybatis等依赖。

    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.3.2


    mysql
    mysql-connector-java
    runtime

  1. application.yml:添加数据库连接信息和mybatis配置信息(默认使用hikari高性能连接池)
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false
mybatis:
  type-aliases-package: cn.example.mybatistest.model
  # mapper-locations: mapper/*Mapper.xml # 暂时不需要 xml 方式
  1. 入口类添加注解@EnableTransactionManagement,激活事务管理
@SpringBootApplication
@EnableTransactionManagement
public class MybatistestApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatistestApplication.class, args);
    }
}
  1. 创建实体类(数据库创建对应表)
public class User {
    private Long id;
    private String name;
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
}
  1. 添加 dao 层,使用注解方式
@Mapper
@Repository
public interface UserDao {
    @Select("select * from user where id=#{id}")
    public User getNameById(@Param("id") long id);

    @Options(useGeneratedKeys = true, keyProperty = "iid")
    @Insert("insert into user(name) values(#{name})")
    public int insert(User user);
}
  1. 添加 service 层,并在该层进行事务管理
@Service
public class UserService {
    @Autowired UserDao userDao;

    // 只读取数据,不修改数据,提高效率
    @Transactional(propagation= Propagation.SUPPORTS,readOnly=true)
    public User getImageById(long id) {
        return userDao.getNameById(id);
    }
    
    // 需要开启事务,修改数据
    @Transactional(propagation = Propagation.REQUIRED)
    public int insert() {
        User user = new User();
        user.setName("insert");
        return userDao.insert(user);
    }

    // 测试异常回滚,一有异常,所有操作都回滚
    @Transactional(propagation = Propagation.REQUIRED)
    public int rollback3() {
        User user = new User();
        user.setName("rollback3");
        userDao.insert(user);

        int i = 1 / 0; // 异常,回滚修改

        user.setName("rollback33");
        return userDao.insert(user);
    }
}

参考:http://www.fengyunxiao.cn

你可能感兴趣的:(springboot,mybatis,springboot2)