简体   繁体   中英

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. 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. 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.

I have explored using @Transient, @SecondaryTables, and a few others but I haven't found a good way to make this work. 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.

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. It's an ORM tool - Object -Relational Mapping. If you're still thinking just in terms of tables and SQL, loading values into primitives, then Hibernate isn't the right tool.

I'd suggest just using Spring SimpleJdbcTemplate rather than Hibernate if you don't have objects to map your data into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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