如何在表中添加两个主键?

时间:2019-07-16 05:41:50

标签: java hibernate hibernate-mapping nhibernate-mapping

SalutationMst.java

@Entity
@Table(name = "SalutationMst")
@EntityListeners(AuditingEntityListener.class)

public class SalutationMst  {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = true )///////////////id
    private Long id;
    //@Id
     @Column(name = "code", nullable = false, length=15)///////////////code
    private String code;
     @Column(name = "name", nullable = false, length=15)////////////////name
    private String name;
    //private long genderid;
     @Column(name = "active", nullable = false)////////////////active
    private Boolean active;

    //@ManyToOne(targetEntity=GenderMst.class,cascade=CascadeType.ALL)
    @ManyToOne
    //@JoinColumn(name="id", nullable=false)
    private GenderMst genderMst;
    //getters snd setters
}

此处,字符串代码也应为pk。字符串ID是自动生成的,而代码不是。到了exp我需要指定代码要重复,为此我需要将代码作为pk。

GenderMst.java

@Entity
@Table(name = "GenderMst")
public class GenderMst {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "code", nullable = true,length=15)
    private String code;
    @Column(name = "name", nullable = true,length=15)
    private String name;
    //getters and setters
}

1 个答案:

答案 0 :(得分:0)

实现此目标的一种方法是,您可以为Composite Primary Key创建一个单独的类,并将其用作EmbeddedId,例如:

@Embeddable
public class SalutationMstId  {
   private Long id;
   private String code;

   //constructors

   //getter setters
}

并像这样使用它:

@Entity
@Table(name = "SalutationMst")
@EntityListeners(AuditingEntityListener.class)

public class SalutationMst  {
     @EmbeddedId
     private SalutationMstId id;
     @Column(name = "name", nullable = false, length=15)////////////////name
    private String name;
    //private long genderid;
     @Column(name = "active", nullable = false)////////////////active
    private Boolean active;

    //@ManyToOne(targetEntity=GenderMst.class,cascade=CascadeType.ALL)
    @ManyToOne
    //@JoinColumn(name="id", nullable=false)
    private GenderMst genderMst;
    //getters snd setters
}

更多信息,请访问this link