【发布时间】:2015-01-09 10:04:02
【问题描述】:
我有 2 个表 TABLE1 和 TABLE2。Table1 有名称,Table2 有电子邮件和电话。
要获取姓名、邮箱和电话,我查询如下
query = entityManagerUtil.createNativeQuery("select s.Name,c.Phone1,c.Email1 from Table1 s,Table2 c where c.id= s.NodeID and s.NodeID =21")
现在我的下一个要求是更新姓名、电子邮件和电话。由于这些参数存在于不同的表中,所以我正在搜索将更新 2 个表的单个查询。不幸的是,我正在使用 sql server 并且有 no way to update 2 tables using single query
所以我正在考虑使用@Transactional 和 2 个查询来更新 2 个表,如下所示
@Transactional
public void updateDetails()
{
Query query1= entityManagerUtil.entityManager.createNativeQuery("update Table1 set Name='' where id in (select NodeID from Table 2) and NodeID=21");
Query query2= entityManagerUtil.entityManager.createNativeQuery("update Table2 set Email='' and phone1='' where NodeID in (select id from Table 2) and NodeID=21");
query1.executeUpdate();
query2.executeUpdate();
}
还有其他更好的方法来更新 2 个表吗?
【问题讨论】:
-
你不能用一条 SQL 语句在一个查询中更新 2 个表,所以你不能在 Hibernate 中这样做。要么改变你的架构,要么你的事务方法是要走的路。
-
@mavroprovato 您指的是什么架构更改?我使用的方式(@Transactional)是否有效?
-
我的意思是将两列放在同一个表中。至于 Transactional 注释,它看起来不错,但如果没有看到更多代码,我不能肯定地告诉你:它只能在 spring bean 中工作,你必须进行一些配置等。你必须阅读并明白这一点:docs.spring.io/spring/docs/current/spring-framework-reference/…