我在Hibernate中有以下类
@Entity
@Table(name="MODEL")
public class Model {
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
Long id;
@ElementCollection(fetch=FetchType.EAGER)
@CollectionTable
(
name="DEVICE_LiCENSE_ATTRIBUTE",
joinColumns=@JoinColumn(name="DEVICE")
)
@MapKeyJoinColumn(name="LICENSE_ATTRIBUTE",nullable=false)
Map<String,SoftwareLicense> softwareLicenses = new HashMap<String, SoftwareLicense>();
}
这是我的嵌入式课程
@Embeddable
public class SoftwareLicense {
@Column(name = "Type", nullable = false)
@Enumerated(EnumType.STRING)
private Type type;
@Column(name = "VALUE", nullable = false)
private String value;
}
现在,当我运行Hibernate时,它真正构建了表
create table DEVICE_LiCENSE_ATTRIBUTE (DEVICE bigint not null, Type varchar(255) not null, VALUE varchar(255) not null, softwareLicenses_KEY varchar(255), primary key (DEVICE, softwareLicenses_KEY))
create table DMS_DEVICE_MODEL (id bigint not null, DESCRIPTION varchar(255) not null, DISPLAYNAME varchar(255) not null, UNIQUENAME varchar(255) not null, primary key (id), unique (UNIQUENAME))
创建DEVICE_LICENSE_ATTRIBUTE
表时出现问题。
只需查看DEVICE_LICENSE_ATTRIBUTE表:
softwareLicenses_KEY varchar(255)
可以为空,Hibernate尝试在可以为空的行上创建复合主键。
primary key (DEVICE, softwareLicenses_KEY)
它适用于某些数据库(HSQLDB),但将我的代码切换到另一个环境(MS SQL 2008)会给我一个错误。
Cannot define PRIMARY KEY constraint on nullable column in table 'DEVICE_LICENSE_ATTRIBUTE'
我该如何解决这个问题?
答案 0 :(得分:0)
我的映射错了:
映射它的正确方法是使用map column属性:
@ElementCollection(fetch=FetchType.EAGER)
@MapKeyColumn(name = "LICENSE_NAME", insertable = false, updatable = false)
@CollectionTable
(
name="DEVICE_LiCENSE_ATTRIBUTE",
joinColumns=@JoinColumn(name="DEVICE")
)
@MapKeyJoinColumn(name="LICENSE_ATTRIBUTE",nullable=false)
Map<String,SoftwareLicense> softwareLicenses = new HashMap<String, SoftwareLicense>();
家里对某人有帮助。