【发布时间】:2017-12-12 19:01:22
【问题描述】:
我遇到一个项目,有两个数据库,但这些数据库中的数据结构不同,涉及多数据源中的事务管理。
另外,我想使用JpaRepository,它只是在一些扩展JpaRepository的接口上添加@Repository注解,重点关注sql语句。例如:
@Scope(value="prototype")
@Repository
public interface UserRepository extends JpaRepository<User, Integer>,
JpaSpecificationExecutor<User> {
@Query(value="select * from users",nativeQuery=true)
public List<User> getAll();
@Query(value="select * from users where email=binary ?1 or phone_number=?1",nativeQuery=true)
public User findUserByEmailOrPhone(String name);
public User save(User user);
@Modifying
@Query("Update User u set u.lastLoginTime=?2,u.mac=?3,u.lastIp=?4 where u.id=?1")
public int updateLast_login(Integer id,Date last_loginTime,String mac,
String last_ip);
}
关于事务管理,我想继续使用@Transctional注解,但这涉及到两个mysql数据库中sql语句的执行。
根据我对一个数据源的经验,我想只有一个entityManagerFactory来管理两个数据源中的不同实体类。
但是如何配置JpaRepository接口和数据源的映射,告诉entityManagerFactory数据源和实体类的映射呢?
这是我想要完成上述功能的示例。
// this entity data is restored in A databse's Atab table
@Table
@Entity
public class A{
private String A_item1;
private Integer A_item2;
private Long A_item3;
public A(){
super();
}
}
// this entity data is restored in B databse's Btab table
@Table
@Entity
public class B{
private String B_item1;
private Integer B_item2;
private Long B_item3;
public B(){
super();
}
}
@Repository
public interface A_Repository extends JpaRepository<A, Integer>,
JpaSpecificationExecutor<A>{
public A save(A a);
@Modifying
@Query(value="update Atab set a_item1=?1 where a_item2=?2",nativeQuery=true)
public A update(String a_item1,int a_item2 );
public A update(A a);
}
@Repository
public interface B_Repository extends JpaRepository<B, Integer>,
JpaSpecificationExecutor<B>{
public B save(B a);
@Modifying
@Query(value="update Btab set b_item1=?1 where b_item2=?2",nativeQuery=true)
public B update(String b_item1,int b_item2 );
public B update(B b);
}
@service
public class A_B_Service{
@Autowired
A_Repository a_Repos;
@Autowired
B_Repository b_Repos;
@Transactional(rollbackFor=Exception.class)
public void synchronous_save_AandB(A a,B b){
a_Repos.save(a);
b_Repos.save(b);
}
@Transactional(rollbackFor=Exception.class)
public void synchronous_update_AandB(A a,B b){
a_Repos.update(a);
b_Repos.update(b);
}
@Transactional(rollbackFor=Exception.class)
public void synchronous_update_AandB(String a_item1,int a_item2,String b_item1,int b_item2){
a_Repos.update( a_item1,a_item2);
b_Repos.update(b_item1,b_item2);
}
}
【问题讨论】:
标签: spring hibernate jpa spring-data