我有2个数据库是mysql,另一个是postgree。我试图从MySQL交易方法中获取后数据。
@Transactional(value = "pg")
public List<String> getSubordinate(){
Query q1 = JPA.em().createNativeQuery("select vrs.subordinate_number, vrs.superior_numbern" +
"from view_reporting_structure vrsn" +
"where vrs.superior_number = :personel_number");
q1.setParameter("personel_number","524261");
List<String> me = q1.getResultList();
return me;
}
}
来自另一种方法
@Transactional
public Result getOpenRequestList(){
Subordinate subordinate = new Subordinate();
List<String> subordinateData = subordinate.getSubordinate();
....
}
我有错误
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'db_hcm.view_reporting_structure' doesn't exist
因此,我的后gre方法被识别为MySQL事务,这是MySQL数据库中不存在的视图。如何使用1方法从不同的天赋单元中获取数据?
我从来没有做过(不同的数据库),但我想以下可能会起作用。
例如,您在application.conf中具有以下数据源定义:
# MySql
db.mysql.driver=com.mysql.jdbc.Driver
... the rest of setting for db.mysql
# H2
db.postgre.driver=org.postgresql.Driver
... the rest of setting for db.postgre
而不是使用@transactional注释,而是明确管理交易并使用JPA使用Transaction API:
private static final String MYSQL_DB = "mysql";
private static final String POSTGRE_DB = "postgre";
public List<String> getSubordinate() {
JPA.withTransaction(MYSQL_DB, true/* this is read-only flag*/,
() -> {
Query q1 = JPA.em().createNativeQuery("select vrs.subordinate_number, vrs.superior_numbern" +
"from view_reporting_structure vrsn" +
"where vrs.superior_number = :personel_number");
q1.setParameter("personel_number","524261");
List<String> me = q1.getResultList();
return me;
}
}
public Result getOpenRequestList(){
JPA.withTransaction(POSTGRE_DB, true/* this is read-only flag*/,
() -> {
Subordinate subordinate = new Subordinate();
List<String> subordinateData = subordinate.getSubordinate();
....
}
}
注意:我更喜欢始终使用处理,因为它可以更好地控制不愉快的流动。您应该用try-catch包装呼叫。如果JPA在Commit上抛出运行时例外,则可以进行适当的错误处理。如果使用@transactional注释,则提交发生在控制器完成后,您无法处理错误。