我有一个图像映射表,可以将图像映射到具有图像的各种项目。当我手动在数据库中创建条目并且正在检索时,这可以正常工作,但是当我尝试进行测试时,它们会因以下错误而失败。我正在使用hibernate和h2进行测试,并使用mysql进行hibernate for dev。
以下是表创建所遇到的错误。
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]
ImageMapping实体。
@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;
答案 0 :(得分:2)
看起来您正在错误地使用JoinTable注释。您实际上是在创建ImageMapping表两次:一次是您的实体,一次是ProductOptions中的JoinTable注释。
查看此帖子,了解连接表注释的含义:JPA "@JoinTable" annotation
他举了一个如何使用它的好例子。我不完全是你的域对象的用途,在ImageMapping中似乎有很多。但是使用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注释中。