我有一个图像映射表,可将图像映射到具有图像的各种项目。当我手动在数据库中输入条目并进行检索时,这按预期工作,但是当我尝试进行测试时,它们会失败并出现以下错误。我使用 hibernate 和 h2 进行测试,使用 hibernate 和 mysql 进行开发。
以下是表创建时出现的错误。
ERROR - Unsuccessful: create table ImageMapping (image_mapping_id integer not null, category_id integer, image_id integer, product_id integer, product_item_id integer, product_option_id integer generated by default as identity, primary key (product_option_id, image_id), unique (image_id))
ERROR - Attempt to define a second primary key; SQL statement:
create table ImageMapping (image_mapping_id integer not null, category_id integer, image_id integer, product_id integer, product_item_id integer, product_option_id integer generated by default as identity, primary key (product_option_id, image_id), unique (image_id)) [90017-168]
图像映射实体。
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name="ImageMapping")
public class ImageMapping {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "image_mapping_id")
private int imageMappingId;
@Column(name="product_option_id")
private int productOptionId;
@Column(name="product_item_id")
private int productItemId;
@Column(name="product_id")
private int productId;
@Column(name="image_id")
private int imageId;
@Column(name="category_id")
private int categoryId;
由于错误提到的另一个字段是我包含该实体的product_option_id。
@JsonAutoDetect
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name="ProductOptions")
public class ProductOptions implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "product_option_id")
private int productOptionId;
@JoinTable(
name="ImageMapping",
joinColumns = @JoinColumn(name = "product_option_id"),
inverseJoinColumns = @JoinColumn(name = "image_id")
)
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Image> productOptionImageGroup;
@JoinColumn(name = "image_id")
@OneToOne
private Image optionImage;
@Column(name = "product_option_description")
private String productOptionDescription;
最佳答案
您似乎错误地使用了 JoinTable 注释。您实际上创建了两次 ImageMapping 表:一次为您的实体创建,一次在 ProductOptions 的 JoinTable 注释中创建。
查看这篇文章,了解连接表注释的含义:JPA "@JoinTable" annotation
他给出了一个很好的例子来说明如何使用它。我不完全是你的域对象的目的,图像映射中似乎发生了很多事情。但使用 JoinTable 的一种方案可能是
Table: Image
id integer
data blob
name varchar
Table: ProductOption
id integer
desc varchar
partnum varchar
Table: Image_Option
image_id integer foreign key
prod_opt_id integer foreign key
因此,在此示例中,我将使用 Image 和 ProductOption 的 Hibernate 实体,并且表 Image_Option 将仅出现在 JoinTable 注释中。
关于java - 无法在测试中创建表(Hibernate 和 H2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159201/