具有约束的SecondaryTable

时间:2018-08-02 14:38:44

标签: java sql-server hibernate jpa

在我的情况下最好的解决方案是什么?

我有一个滞后数据库,想使用一个休眠实体访问数据。我想让Java部分尽可能简单。

我的数据库由三个表组成:

  1. Table1(id,Att1,Att2)
  2. Table2(id,Att3)
  3. Table3(id,current,Att4)

我这样使用@SecondaryTable注释:

@Entity
@Table(name = "Table1")
@SecondaryTables({
  @SecondaryTable(name = "Table2", pkJoinColumns = @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")),
  @SecondaryTable(name = "Table3", pkJoinColumns = @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")) 
})
public class Entity implements Serializable {
  int id;
  int Att1;
  int Att2;
  int Att3;
  int Att4;
}

这对于Table2Att3来说完全正常。但是,在表3中,我只希望Att4current = true。假设Att4的旧版本保存在Table3中。可以通过@SecondaryTable完成此操作,还是需要其他方法?我宁愿保留一个实体,也不要通过创建不必要的Table3实体来使用@OneToMany。

1 个答案:

答案 0 :(得分:4)

如何将current添加到您的实体中?

public class Entity implements Serializable {
  int  id;
  int  Att1;
  int  Att2;
  int  Att3;
  int  Att4;
  byte current;
}

从另一面看,如果您追求的是最佳解决方案,我将对SQL Server进行更改。因此,您将获得最大的性能优势,因为SQL Server基数估计器将能够创建最佳的执行计划。这将限制在转换上浪费的不必要的SQL Server事务的数量,以及在应用程序和数据库之间传输的数据量。您需要做的只是在SQL Server方面:

CREATE VIEW [YourEntityOnDB]
AS
SELECT t1.[id], t1.[Att1], t1.[Att2], t2.[Att3], t3.[Att4]
FROM [Table1] t1
JOIN [Table2] t2 ON t1.[id] = t2.[id]
JOIN [Table3] t3 ON t1.[id] = t3.[id]
WHERE t3.[current] = 1;

您的JAVA部分将尽可能地容易,因为[YourEntityOnDB]是您将要调用的唯一对象,并且其中将包含所有id,Att1,Att2,Att3,Att4和current = 1。 在此基础上,根据数据的唯一性和您的需求,您可以应用一些索引(甚至为新视图编制索引)以使其运行更快。在最新版本(SQL Server 2014+)中,甚至有内存中的选项可以根据需要使它快速点亮。应用程序和数据库上都有许多选项可以达到相同的目的,但这主要取决于您的需求和公司标准。我见过一些公司,其中有关数据关系的所有内容都是由应用程序驱动的,而所有这些都与性能有关。

相关问题