SecondaryTable with Where Constraint

Thanthla :

What is the best solution in my scenario?

I have a lagacy database and want to access the data by using a single hibernate entity. I want to keep the java part as simple as possible.

My database consists of three tables:

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

I used the @SecondaryTable anonntaion like this:

@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;
}

This works totally fine for Table2 and Att3. However, in Table3 I only want Att4 if current = true. Assuming old versions of Att4 are kept in Table3. Can this be done by @SecondaryTable or do I need another approach? I would prefer to keep a single entity and not use @OneToMany by creating a unneccesary Table3 entity.

Bartosz X :

What about adding the current to your entity?

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

From the other side if you are after the best solution here I would go for making a change down in the SQL Server. Thanks to that you would get the biggest performance advantage you can have, as SQL Server cardinality estimator will be able to create the most optimal execution plan. This will limit the number of unnecessary SQL Server transactions wasted on transformation as well as amount of data transferred between the app and the database. All you need to do will be on the SQL Server side:

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;

And the your JAVA part will be really as easy as possible as [YourEntityOnDB] will be the only object you would call and it will contain all id, Att1, Att2, Att3, Att4 and current = 1 in it. On top of that based on the data uniqueness and your needs you can apply some indexes (even index your new view) to make it run even faster. In recent versions (SQL Server 2014+) there are even in-memory options to make it lighting fast if needed. There is a number of options available both on app and DB to get to the same point, but this mostly depends on your needs and company standards. I have seen companies where everything regarding data relations were app driven as well as these where it was all about the performance.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93309&siteId=1