我的应用程序正在尝试保存Project
对象和Photo
Media
对象。 Photo
表中有media_id
作为外键。
我的课程
Project.java
@Entity
@Table(name = "tbl_project", catalog = "chetak")
public class Project implements java.io.Serializable {
private Long projectId;
private String projectName;
private Set<Media> projectMedias = new HashSet<Media>(0);
@OneToMany(fetch = FetchType.EAGER)
@Cascade({CascadeType.SAVE_UPDATE})
public Set<Media> getProjectMedias() {
return this.projectMedias;
}
public void setProjectMedias(Set<Media> projectMedias) {
this.projectMedias = projectMedias;
}
Media.java
@Entity
@Table(name = "tbl_media", catalog = "chetak")
@Inheritance(strategy=InheritanceType.JOINED)
public class Media implements java.io.Serializable {
private Integer mediaId;
private String type;
private String mime;
Photo.java
@Entity
@Table(name = "tbl_photo", catalog = "chetak")
@PrimaryKeyJoinColumn(name="mediaId")
public class Photo extends Media implements java.io.Serializable {
//private Integer photoId;
private Integer height;
private Integer width;
private String photoType;
在主课程中,我正在为项目中的媒体集添加照片。
Photo photo = new Photo();
photo.setPhotoType("logo");
photo.setWidth(100);
photo.setHeight(100);
project.getProjectMedias().add(photo);
在保存项目对象时,我收到以下日志。请在最后看到对不存在的表有不必要的插入,这会导致错误:
Hibernate: insert into chetak.tbl_project (addressId, availableUnits, basicSellingPrice, bhk, builtUpAreaHigh, builtUpAreaLow, category, contactId, currentProjectStatus, description, developer, endPrice, latitude, listingTitle, listingType, longitude, numberOfBuildings, postedByName, postedByUserId, postedByUserType, projectLaunchDate, projectName, sourceListedDate, startPrice, totalUnits) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into chetak.tbl_media (caption, dateCreated, description, isApproved, mime, size, source, title, type, url) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into chetak.tbl_photo (height, photoType, width, mediaId) values (?, ?, ?, ?)
Hibernate: insert into tbl_project_tbl_media (tbl_project_projectId, projectMedias_mediaId) values (?, ?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1146, SQLState: 42S02
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Table 'chetak.tbl_project_tbl_media' doesn't exist
这是由于某些hibernate映射错误造成的吗?
答案 0 :(得分:1)
Hibernate为您的一对多关系创建一个名为tbl_project_tbl_media的链接表。我想你只需要Media表中的一个列引用该项目,从而避免使用链接表。
@JoinColumn注释正是这样做的。我现在无法编译和运行它来测试,所以不会发布任何代码,但基本上你可以在Media类中创建一个Project字段,然后在@之前或之后使用@JoinColumn(“yourColumnName”)一对多。
看到这个问题: @OneToMany without inverse relationship and without a join table?
答案 1 :(得分:1)
不确定您使用的是哪种版本的Hibernate。我映射bidirectionnal @OneToMany关系的标准方法如下。它不会为关系创建中间表:
@Entity
public class Actor implements Serializable {
...
@OneToMany(mappedBy="actor", fetch=FetchType.EAGER)
private Set<Account> account;
...
}
@Entity
public class Account implements Serializable
{
...
@ManyToOne
private Actor actor;
...
}
我怀疑Photo延伸Media的事实与你的问题有关。