Hibernate异常:
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
环境:hibernate-core版本4.2.17.Final
POJO类:User
package com.ssh.model;
public class User {
private long id;
private String name;
private int age;
private boolean isMan;
private Group group;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isMan() {
return isMan;
}
public void setMan(boolean isMan) {
this.isMan = isMan;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
}
HBM映射文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.ssh.model"> <class name="User" table="t_user"> <id name="id" type="java.lang.Long" column="u_id"> <!-- <generator class="sequence"> <param name="sequence">user_id_seq</param> </generator> --> <generator class="native"></generator> </id> <property name="name" column="u_name"></property> <property name="age" column="u_age"></property> <property name="isMan" column="u_man" type="yes_no"></property> <many-to-one name="group" column="u_group"></many-to-one> </class> </hibernate-mapping>
解释:
出现该异常是当hibernate解析hbm文件时,看到<property name="isMan" column="u_man" type="yes_no"></property>就找到对应的实体类User,去其中找setIsMan()方法,但是可惜没有。为什么没有呢?User类中有isMan属性啊,但是在通过eclipse为我们生成getter和setter时,eclipse发现是is开始的属性生成setter方法时主动去掉了is,生成getter方法时却没有用get开头,最终变成如下结果:
public boolean isMan() {
return isMan;
}
public void setMan(boolean isMan) {
this.isMan = isMan;
}
所以当hibernate想找setIsMan方法时就找不到了。
解决方法1:修改hbm中的property标签的name属性为man(setMan的Man部分)
解决方法2:修改POJO类的setter方法为setIsMan
通过该异常我们得出结论:
POJO类的属性尽量不要使用is开头,如果使用is开头,那么就手动编写getter和setter方法,以防出现该异常。