SpringBoot2集成JPA和MyBatis

JPA和MyBatis各有各的好处,混合食用效果更佳。
根据前面的博文《Spring Boot2集成JPA》《SpringBoot2集成MyBatis》,我们已经知道怎么分别集成JPA和MyBatis,两者一起集成也简单。

合并配置文件application.yml

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/test
    username: postgres
    password: postgres
  jpa:
    properties:
      hibernate:
        hbm2ddl:
          auto: update
        dialect: org.hibernate.dialect.PostgreSQLDialect
        temp:
          use_jdbc_metadata_defaults: false
    show-sql: true
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.wu.parker.jpamybatis

在Service里注入JPA和MyBatis接口

package com.wu.parker.jpamybatis.service.impl;

import com.wu.parker.jpamybatis.dao.UserMapper;
import com.wu.parker.jpamybatis.dao.UserRepository;
import com.wu.parker.jpamybatis.po.User;
import com.wu.parker.jpamybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: wusq
 * @date: 2018/11/28
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void testTransaction() {
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword("admin");
        userRepository.save(user1);

        User user2 = new User();
        user2.setId("2");
        user2.setUsername("test");
        user2.setPassword("test");
        userMapper.save(user2);

        // 抛出异常则全部回滚,不会保存到数据库
        // throw new RuntimeException();
    }

}

测试类

package com.wu.parker.jpamybatis.test;

import com.wu.parker.jpamybatis.service.UserService;
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;

/**
 * @author: wusq
 * @date: 2018/11/28
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testTransaction() throws Exception {
        userService.testTransaction();
    }

}

Spring自动处理事务问题,一般情况下这样同时用是没问题的,但是如果JPA的接口和MyBatis的接口方法存在依赖,并且数据库表存在外键的情况下,可能会出问题,遇到的时候自然就知道了,这时候可以统一用JPA或MyBatis。

项目源代码:https://github.com/wu-boy/parker.git

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值