简体   繁体   English

在单个模型Hibernate Spring中将第三个表连接起来

[英]Joining two tables on a third in a single model Hibernate Spring

I have two tables that I would like to treat as a single model class in Hibernate/Spring, however their only relationship can be established through a third table. 我有两个表希望在Hibernate / Spring中作为单个模型类处理,但是它们的唯一关系可以通过第三个表建立。 For example... 例如...

tableA {  
   id integer <PK>
   username varchar2(25 byte)
}
tableB {
   personID varchar2(15 byte) <PK>
   divisionID integer
   positionID integer
}
tableC {
   personID varchar2(10) <FK>
   username varchar2(25 byte)
}

While it would be very nice to simply add the personID as a column in tableA, circumstances do not permit. 仅将personID添加为tableA中的一列会非常好,但是情况不允许。 I would, however, like to interact with these tables using one model in hibernate, such as the one below... 但是,我想使用休眠中的一种模型与这些表进行交互,例如下面的一种...

@Entity
@Table(name="tableA")
public class myTable {
   @Id
   @GeneratedValue
   private int id;
   private String username;
   @Formula("(select distinct tableC.personID from tableC where upper(tableC.username) = upper(THIS_.username) and tableC.personID is not null)")
   String personID;
   @Formula("(select distinct tableB.divisionID from tableB where tableB.personID = THIS_.personID)")
   int divisionID;
   @Formula("(select distinct tableB.oositionID from tableB where tableB.personID = THIS_.personID)")
   int positionID;

   //getters, setters, etc...
}

I know that the way I have it written here is impossible, I'm just trying to convey the idea. 我知道我在这里写的方式是不可能的,我只是想传达这个想法。 When I go to save or update the database later on, I would like for Hibernate to be able to update the appropriate tables from which each attribute came. 当我稍后保存或更新数据库时,我希望Hibernate能够更新每个属性来自的适当表。

I have explored using @Transient, @SecondaryTables, and a few others but I haven't found a good way to make this work. 我已经探索过使用@ Transient,@ SecondaryTables和其他一些方法,但是我还没有找到一种好的方法来完成这项工作。 Is it possible to do this the way that I want to? 是否可以按照我想要的方式进行? If so, what approach/annotations should I use? 如果是这样,我应该使用哪种方法/注释? If not, what alternative approach should I take? 如果没有,我应该采取什么替代方法? I am relatively new to Hibernate and Spring, so please bear with me. 我对Hibernate和Spring比较陌生,所以请多多包涵。

I'm sure there's a way to do this; 我敢肯定有办法做到这一点; I don't have an answer for you. 我没有你的答案。

But your question suggests to me that you're not thinking properly about Hibernate. 但是您的问题向我暗示您没有正确考虑Hibernate。 It's an ORM tool - Object -Relational Mapping. 这是一个ORM工具- 对象 -关系映射。 If you're still thinking just in terms of tables and SQL, loading values into primitives, then Hibernate isn't the right tool. 如果您仍然只考虑表和SQL,将值加载到基元中,那么Hibernate不是正确的工具。

I'd suggest just using Spring SimpleJdbcTemplate rather than Hibernate if you don't have objects to map your data into. 如果您没有将数据映射到的对象,我建议仅使用Spring SimpleJdbcTemplate而不是Hibernate。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM