简体   繁体   中英

Join 2 entities with a column other than PK and FK

I am currently working on entities mapping and wondering if there are any ways of mapping a @OneToMany without the primary key usage. All mappings require primary key on at least one of the entity getting mapped.

Eg: I have 2 tables

Table 1
ID(PK),
Name,
Xid

Table 2
ID(PK),
UserName,
userType,
Xid

I don't want to perform say for example:

@OnetoMany(mapped by="")
public Table2 t2

@ManyToOne()
public Table1 id;

Is there any way to map/associate Xid of Table1 to Xid of Table2 using @JoinTable ?

Yes you can map Relation on other than primary key and Foreign keys.

Table1 :

@Entity
@Table(name = "Table1")
public class Table1 implements Serializable,Cloneable {

  @Id
  @Column(name = "id")
  private BigInteger id;     

  @Column(name = "Name")
  private String name; 

  @Column(name = "Xid")
  private BigInteger xid;

  @OneToOne
  @JoinColumn(name = "Xid", nullable = false, insertable = false, updatable = false, referencedColumnName = "Xid")
  private Table2 table2;

// Getter and Setters
}

Table2 :

@Entity
@Table(name = "Table2")
public class Table2 implements Serializable , Cloneable {

  public Table2() {
  }

  @Column(name = "id")
  private BigInteger id;

  @Column(name = "Xid")
  private BigInteger xid;

  @Column(name = "UserName")
  private String userName;

  @Column(name = "userType")
  private String userType;
// Getter and Setters    

}

And in Query you will specify Join like

    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<Table1> cq = cb.createQuery(Table1.class);
    Root<Table1> root = cq.from(Table1.class);
    Join<Table1, Table2> join = (Join<Table1, Table2>) root
            .fetch(Table1_.table2);
    List<Predicate> conditions = new ArrayList<>();
    conditions.add(cb.equal(root.get(Table1_.Xid), join.get(
        Table2_.Xid)));
    cq.where(conditions.toArray(new Predicate[]{}));
    Query query= session.createQuery(cq);

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