简体   繁体   中英

How to create intermediate table between two tables in Hibernate/JPA?

Table 1:Computer table

 @Entity
 @Table ("computer")
 public class Computer{
   private int id;
   .
 }

Table 2: License table:

 @Entity
 @Table ("licenses")
 public class Licnese{
   private int id;
   .
 }

Table 3: To be created. This is Intermediate, which should have two fields only

Computer ID | License ID

License ID can be link to multiple computer ID and multiple computer ID can have multiple licenses.

CompID | LicneseID  
      1|2
      1|2
      2|2

In our case, Computer and Licnese data already exists. We run a job to populate intermediate table ie pick computer id, download lincense id from rest service, find license in existing database and create record in intermediate table.

How should it be done?

  1. Insert independently or

    class intermediate{ private int compid private int liceid }

but in this primary key is required which customer do not want.

  1. update using Computer or License entity if yes then how?

I understand we need to use ElementCollection in Computer entity but how to refer license ID?

@ElementCollection(targetClass = Intermediate.class)
    @CollectionTable(name = "Intermediate", joinColumns = @JoinColumn(name = "ID"))
    @AttributeOverrides({
        @AttributeOverride(name = "license ID",column = @Column(name = "License ID")),
    private List<Intermediate> intermediate;

also do we need to merge Computer entity in this case?

As per the description you want to use Hibernate join table approach. How to implement join table approach you can refer link mentioned below: http://fruzenshtein.com/hibernate-join-table-intermediary/

You can simply define a @ManyToMany relationship and the joininig table would be created automaticaly.

@ManyToMany
@JoinTable(
  name = "licence_computer", 
  joinColumns = @JoinColumn(name = "computer_id"), 
  inverseJoinColumns = @JoinColumn(name = "licence_id"))
private Set<Licnese> licences;

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