gpt4 book ai didi

java - 从 JPA 注释生成 DDL

转载 作者:行者123 更新时间:2023-12-01 15:49:18 24 4
gpt4 key购买 nike

我的 JPA 模型中有以下类(省略了 getter、setter 和不相关的字段):

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@IdClass(PricePK.class)
public class Price {

@Id
@ManyToOne(optional = false)
private Product product;

@Id
@ManyToOne(optional = false)
private Currency currency;
}

@Embeddable
public class PricePK implements Serializable {

Integer product;
Integer currency;
}

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Currency extends PersistentEntity {

@Id
private Integer ix;
}

@Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Product extends AutoIdPersistentEntity {
}

@MappedSuperclass
public abstract class AutoIdPersistentEntity extends PersistentEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}

我使用hbm2ddl hibernate3 Maven 插件的目标是从这些类生成 DDL。它为与 Price 类对应的表生成以下内容

create table PRICE (
currency_id int null,
product_id int null,
primary key (currency_id, product_id)
);

请注意,currency_idproduct_id 都可以为 null,这会在我尝试将 DDL 加载到 SQL Server 时导致以下错误

Cannot define PRIMARY KEY constraint on nullable column in table 'PRICE'

我不明白为什么这些可以为空,因为在域模型中它们被注释了@ManyToOne(可选 = false)

DDL 是使用 org.hibernate.dialect.SQLServerDialect SQL 方言生成的。

最佳答案

这有点令人困惑,但我认为可选属性(@ManyToOne、@Basic,...)不用于某些 JPA 实现的模式生成。

我认为你需要使用 @JoinColumn 注释并将 nullable 设置为 false: http://download.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html

(或者在非连接情况下@Column:http://download.oracle.com/javaee/6/api/javax/persistence/Column.html)

关于java - 从 JPA 注释生成 DDL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com