【发布时间】:2014-10-07 09:00:52
【问题描述】:
在使用 hibernate 和 MySQL 的 spring mvc 应用程序中,我收到一个错误,这似乎表明 Name 实体找不到 Patient 实体的 BaseEntity 超类的 id 属性的设置器.
如何解决此错误?
这里是错误信息:
Caused by: org.hibernate.PropertyAccessException: could not set a field value by
reflection setter of myapp.mypackage.Name.patient
这是触发错误的代码行:
ArrayList<Name> names = (ArrayList<Name>) this.clinicService.findNamesByPatientID(patntId);
这里是BaseEntity,它是Patient和Name的超类:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorFormula("(CASE WHEN dtype IS NULL THEN 'BaseEntity' ELSE dtype END)")
public class BaseEntity {
@Transient
private String dtype = this.getClass().getSimpleName();
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
protected Integer id;
public void setId(Integer id) {this.id = id;}
public Integer getId() {return id;}
public void setDtype(String dt){dtype=dt;}
public String getDtype(){return dtype;}
public boolean isNew() {return (this.id == null);}
}
这里是Patient 实体:
@Entity
@Table(name = "patient")
public class Patient extends BaseEntity{
@OneToMany(mappedBy = "patient")
private Set<Name> names;
protected void setNamesInternal(Set<Name> nms) {this.names = nms;}
protected Set<Name> getNamesInternal() {
if (this.names == null) {this.names = new HashSet<Name>();}
return this.names;
}
public List<Name> getNames() {
List<Name> sortedNames = new ArrayList<Name>(getNamesInternal());
PropertyComparator.sort(sortedNames, new MutableSortDefinition("family", true, true));
return Collections.unmodifiableList(sortedNames);
}
public void addName(Name nm) {
getNamesInternal().add(nm);
nm.setPatient(this);
}
//other stuff
}
这里是Name 实体:
@Entity
@Table(name = "name")
public class Name extends BaseEntity{
@ManyToOne
@JoinColumn(name = "patient_id")
private Patient patient;
public Patient getPatient(){return patient;}
public void setPatient(Patient ptnt){patient=ptnt;}
//other stuff
}
完整的堆栈跟踪可以查看at this link。
Hibernate 为上述查询生成的 SQL 为:
select distinct hl7usname0_.id as id1_0_0_, givennames1_.id as id1_45_1_,
hl7usname0_.family as family1_44_0_, hl7usname0_.patient_id as patient3_44_0_,
hl7usname0_.person_id as person4_44_0_, hl7usname0_.suffix as suffix2_44_0_,
hl7usname0_.usecode as usecode5_44_0_, hl7usname0_.codesystem as codesyst6_44_0_,
givennames1_.given as given2_45_1_, givennames1_.name_id as name3_45_1_,
givennames1_.name_id as name3_0_0__, givennames1_.id as id1_45_0__
from hl7_usname hl7usname0_
left outer join hl7_usname_given givennames1_ on hl7usname0_.id=givennames1_.name_id
where hl7usname0_.patient_id=1
当我通过 MySQL 命令行客户端运行此查询时,它返回测试数据库表中的唯一记录。
【问题讨论】:
-
完整的堆栈跟踪是什么样的?对于这个特定的错误消息,通常在堆栈跟踪的下半部分存在更精确、更精细的错误。
-
@isim 我也有类似的问题。你愿意帮助我吗?这是链接:stackoverflow.com/questions/25316761/…
标签: java mysql spring hibernate