我正在使用Hibernate注释并拥有一个非常基本的数据对象:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class State implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String stateCode;
private String stateFullName;
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public String getStateFullName() {
return stateFullName;
}
public void setStateFullName(String stateFullName) {
this.stateFullName = stateFullName;
}
}
我正在尝试运行以下测试用例:
public void testCreateState(){
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction t = s.beginTransaction();
State state = new State();
state.setStateCode("NE");
state.setStateFullName("Nebraska");
s.save(s);
t.commit();
}
并获得
org.hibernate.MappingException: Unknown entity: $Proxy2
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:628)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1366)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
....
我无法找到引用错误的$ Proxy部分的任何内容 - 而且我不知所措。任何指向我缺少的内容都将非常感激。
的hibernate.cfg.xml
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/xdb</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="current_session_context_class">thread</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<mapping class="com.test.domain.State"/>
在HibernateUtil.java中
public static SessionFactory getSessionFactory(boolean testing ) {
if ( sessionFactory == null ){
try {
String configPath = HIBERNATE_CFG;
AnnotationConfiguration config = new AnnotationConfiguration();
config.configure(configPath);
sessionFactory = config.buildSessionFactory();
} catch (Exception e){
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
return sessionFactory;
}
答案 0 :(得分:0)
如果您将代码更改为以下
,您的应用程序的输出是什么Transaction t = s.beginTransaction();
State state = new State();
System.out.println(state.getClass().getName());
state.setStateCode("NE");
答案 1 :(得分:0)
我的想法:也许你必须将状态代码的@Id注释更改为@NaturalId。我认为@Id是指自动生成的ID,也是错误消息中提到的内容。
答案 2 :(得分:0)
我收到了同样的错误消息。它不会对你有所帮助,但无论如何,我会为遇到这篇文章的其他人发布解决方案。
这不起作用:
import org.hibernate.annotations.Entity;
这确实有效:
import javax.persistence.Entity;