我是Hibernate的新手,我正在学习自己。我执行程序时遇到了问题。我已经尝试了很多来解决错误,但没有运气。这是我的主要和配置文件以及hbm文件。
package com.HibernateLearn;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Client {
public static void main(String[] args) {
// creating configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");// populates the data of the
// configuration file
// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();
// creating session object
Session session = factory.openSession();
// creating transaction object
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setId(103);
e1.setF_name("Ahammed");
e1.setL_name("Naseer");
//e1.getId();
//e1.getF_name();
e1.getL_name();
session.persist(e1);// persisting the object
t.commit();// transaction is committed
session.close();
System.out.println("successfully saved");
}
}
我的hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate
Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<!-- <property name="hbm2ddl.auto">create-update</property> -->
<!--Below are other values for hbm2ddl.auto validate: validate the schema,
makes no changes to the database. update: update the schema. create: creates
the schema, destroying previous data. create-drop: drop the schema at the
end of the session. -->
<!--property name="hibernate.cache.use_query_cache">true</property -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/joctopusdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">abc123</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
我的hibernate.hbm.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.HibernateLearn.Employee" table="emp_table">
<id name="Id">
<generator class="increment"></generator>
</id>
<property name="F_name"></property>
<property name="L_name"></property>
</class>
</hibernate-mapping>
我收到错误
Exception in thread "main" org.hibernate.PersistentObjectException: detached entity passed to persist: com.HibernateLearn.Employee
答案 0 :(得分:0)
在为您生成新实体的唯一ID时执行e1.setId(103);
:
<id name="Id">
<generator class="increment"></generator>
</id>
Hibernate期望您的Employee
实例已经在数据库中,因为它已设置id
。换句话说,Hibernate期望它正在将附加的现有实例更新为session
。因此分离的错误消息。
因此,要解决此问题,您不应自行为新实体设置id
。