【问题标题】:Join 2 entities with a column other than PK and FK使用 PK 和 FK 以外的列连接 2 个实体
【发布时间】:2019-08-30 16:07:37
【问题描述】:

我目前正在研究实体映射,想知道是否有任何方法可以在不使用主键的情况下映射@OneToMany。 所有映射都需要至少一个被映射实体的主键。

例如: 我有 2 张桌子

Table 1
ID(PK),
Name,
Xid

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

我不想执行例如:

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

@ManyToOne()
public Table1 id;

有没有办法使用@JoinTable 将 Table1 的 Xid 映射/关联到 Table2 的 Xid?

【问题讨论】:

    标签: java hibernate join mapping one-to-many


    【解决方案1】:

    是的,您可以将关系映射到主键和外键以外的其他位置。

    表 1:

    @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
    }
    

    表2:

    @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    
    
    }
    

    在 Query 中,您将指定 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 2013-07-10
      相关资源
      最近更新 更多