hibernate 将外键作为主键的一部分进行休眠

pgky5nke  于 2023-03-23  发布在  其他
关注(0)|答案(4)|浏览(165)

我不得不使用hibernate,不太确定如何解决这个问题,我有两个表,其中有一个1..n的关系,如下所示:

-------
TABLE_A
-------
first_id (pk)
second_id (pk)
[other fields]

-------
TABLE_B
-------
first_id (pk)(fk TABLE_A.first_id)
second_id (pk)(fk TABLE_A.second_id)
third_id (pk)
[other fields]

我怎么能用Hibernate来管理呢???
我不知道如何管理第二个表的主键。

91zkwejq

91zkwejq1#

在Hibernate参考文档中有一个例子与你的例子完全相似。在这个例子之前,你可以找到解释。下面是这个例子,它符合你的问题(User是表A,Customer是表B):

@Entity
class Customer {
   @EmbeddedId CustomerId id;
   boolean preferredCustomer;

   @MapsId("userId")
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   })
   @OneToOne User user;
}

@Embeddable
class CustomerId implements Serializable {
   UserId userId;
   String customerNumber;

   //implements equals and hashCode
}

@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
}

@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;

   //implements equals and hashCode
}

注意:如果你为这两个表指定了一个代理标识符,那就简单多了。除非你不得不处理一个遗留模式,否则请使用代理键。

lb3vh1jj

lb3vh1jj2#

使用@PrimaryKeyJoinColumn@PrimaryKeyJoinColumns注解。来自Hibernate手册:
@PrimaryKeyJoinColumn注解确实指出实体的主键用作关联实体的外键值。

avkwfej4

avkwfej43#

public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 5478661842746845130L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
}
@Entity
public class Author {

    @Id
    @Column(name = "AUTHOR_ID", nullable = false)
    private int authorId;
    @Column(name = "ENABLED", nullable = false, length = 1)
    private boolean enabled;

    @OneToOne
    @MapsId
    @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID", nullable = false, insertable = false, updatable = false)
    User user;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
e5nqia27

e5nqia274#

对于表A,您可以使用embeddedId

@Emebddable
class PrimaryKeyIdTableA{
 private Integer firstId,

 private Integer secondId
}

class A {
 @EmebddedId
 private PrimaryKeyIdTableA id
}

对于表B,也可以使用Idclass,如下所示

Class PrimaryKeyIdTableB {

private PrimaryKeyIdTableA id,

private Integer thirdId

 }

 @Idclass(PrimaryKeyIdTableB.class)
 Class TableB{
 @Id
 private Integer thirdId,
 
  @Id
  @onetoone
  @Joincolumns({
  @Joincolumn(name=firstid),
  @Joincolumn(name=secondId)})
 private PrimaryKeyIdTableA id
    }

相关问题