我正在开发一个使用hibernate的简单练习应用程序。它具有简单的映射,就像制造商可以拥有许多手机一样。但移动设备只能由单一制造商生产。这是我认为代码应该是什么。
package mobileconsumers.entity.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="ms_ref_mobile")
public class MobileDTO {
private Long id;
private String model;
private ManufacturerDTO manufacturerDTO;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="MOBILE_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="MANUFACTURER_ID")
public ManufacturerDTO getManufacturer() {
return manufacturerDTO;
}
public void setManufacturer(ManufacturerDTO manufacturer) {
this.manufacturerDTO = manufacturer;
}
}
这是第二个dto
package mobileconsumers.entity.dto;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="ms_ref_manufacturer")
public class ManufacturerDTO {
private Long id;
private String name;
private Set<MobileDTO> mobileDTOs = new HashSet<>(0);
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="MANUFACTURER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(fetch=FetchType.LAZY,mappedBy="manufacturerDTO")
public Set<MobileDTO> getMobileDTOs() {
return mobileDTOs;
}
public void setMobileDTOs(Set<MobileDTO> mobileDTOs) {
this.mobileDTOs = mobileDTOs;
}
}
当我尝试启动服务器时,它给出了一个错误说...
org.hibernate.AnnotationException: mappedBy reference anunknown target entity property: mobileconsumers.entity.dto.MobileDTO.manufacturerDTO in mobileconsumers.entity.dto.ManufacturerDTO.mobileDTOs
映射似乎对我来说没问题。我错过了一些非常愚蠢的东西。只需要新鲜的双眼来看我的代码并弄清楚什么是错的..
答案 0 :(得分:8)
更改mappedBy
值,以便它引用关联的manufacturer
一侧的@ManyToOne
属性:
@OneToMany(fetch=FetchType.LAZY,mappedBy="manufacturer")
public Set<MobileDTO> getMobileDTOs() {
return mobileDTOs;
}