简体   繁体   中英

How to create and add data to Table 3 without adding data to Table 1 and Table 2 in hibernate

I am new to Hibernate and not able to find out a way of the situation that I have. It is kind of Many to Many relationship but the only difference is that I want the data to be only inserted in table 3 and not in table 1 & table 2.

Table 1 and Table 2 already has all the data present.

Current Requirement:

Table 1 has user id, first name, last name (Already Exists) Table 2 has document id, document name, document content (Already Exists) Table 3 should have user id and document id Both Table 1 & Table 2 already has all the data prepopulated. Now if a user views a document, I want to make an entry in the third table without persisting or updating in Table 1 & Table 2. We want to maintain data on the documents which are viewed by a user so that even when the user logged off and login back we can show him only the docs which are unread. What is the best use of Hibernate in this situation?

You don't need to update the people nor the document table. Hibernate is able to add entries to your third table (the join table) if you configure everything right. You just annotate a collection with @ManyToMany and make sure you are working with entities from the DB instead of creating new ones:

  • load person from DB
  • load document from DB
  • put document into the list of the person
  • save person entity

See here: http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/ for a good walkthrough

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