在此代码中,如何为组合键生成Java类(如何在hibernate状态下组合键):
create table Time ( levelStation int(15) not null, src varchar(100) not null, dst varchar(100) not null, distance int(15) not null, price int(15) not null, confPathID int(15) not null, constraint ConfPath_fk foreign key(confPathID) references ConfPath(confPathID), primary key (levelStation, confPathID) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
要映射组合键,你可以使用EmbeddedId 或在IdClass注解。我知道这个问题不仅仅涉及JPA,但规范定义的规则也适用。因此,它们是:
2.1.4主键和实体身份 …
组合主键必须对应于单个持久性字段或属性,或对应于如下所述的一组此类字段或属性。必须定义一个主键类来表示一个复合主键。当数据库密钥由几列组成时,从传统数据库进行映射时,通常会出现复合主键。的EmbeddedId和 IdClass注解用于表示复合主键。参见9.1.14和9.1.15节。
…
以下规则适用于复合主键:
serializable
equals
hashCode
With an IdClass
复合主键的类可能看起来像(可以是静态内部类):
public class TimePK implements Serializable { protected Integer levelStation; protected Integer confPathID; public TimePK() {} public TimePK(Integer levelStation, Integer confPathID) { this.levelStation = levelStation; this.confPathID = confPathID; } // equals, hashCode }
And the entity:
@Entity @IdClass(TimePK.class) class Time implements Serializable { @Id private Integer levelStation; @Id private Integer confPathID; private String src; private String dst; private Integer distance; private Integer price; // getters, setters }
该IdClass注释映射多个字段的表PK。
With EmbeddedId
@Embeddable public class TimePK implements Serializable { protected Integer levelStation; protected Integer confPathID; public TimePK() {} public TimePK(Integer levelStation, Integer confPathID) { this.levelStation = levelStation; this.confPathID = confPathID; } // equals, hashCode }
和实体:
@Entity class Time implements Serializable { @EmbeddedId private TimePK timePK; private String src; private String dst; private Integer distance; private Integer price; //... }
该@EmbeddedId注解映射一个PK类表PK。
@EmbeddedId
差异:
with IdClass
select t.levelStation from Time t
with EmbeddedId
select t.timePK.levelStation from Time t