草庐IT

java - hibernate 非法尝试将集合与两个打开的 session 相关联

coder 2024-03-12 原文

我在学校项目中使用持久性,当我尝试删除和更新对象时遇到问题,所有其他查询都有效。

异常(exception)是:

Illegal attempt to associate a collection with two open sessions

我关闭我打开的每个 session 。

HibernateUtils 代码

public class Hibernate
{
 protected static final SessionFactory sessionFactory;

 private Session session;

 static 
 {
  try 
  {
   // Create the SessionFactory from hibernate.cfg.xml
   sessionFactory = new Configuration().configure().buildSessionFactory();
   session
  } 
  catch (Throwable ex) 
  {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }

 public void create(Object obj)
 {
  this.session = sessionFactory.openSession();
  session.getTransaction().begin();
  session.save(obj);
  session.getTransaction().commit(); 
  session.close();
 }

 public void refresh(Object obj)
 {
  this.session = sessionFactory.openSession();
  session.getTransaction().begin();
  session.refresh(obj);
  session.getTransaction().commit();
  session.close();
 }

 public void update(Object obj)
 {
  this.session = sessionFactory.openSession();
  session.getTransaction().begin();  
  session.saveOrUpdate(obj);
  session.getTransaction().commit();
  session.close();

 }
 public void delete(Object obj)
 {
  this.session = sessionFactory.openSession();
  session.getTransaction().begin();
  session.delete(obj);
  session.flush();
  session.getTransaction().commit();  
  session.close();
 }
 protected String protectString(String toProtect)
 {
  return (toProtect.replace("'", "''"));
 }

}

道人:

public class DAOPerson extends Hibernate
{

 public void remove(Person p)
 {
  if (p instanceof Student)
  {
   Student s = (Student)p;
   Set<persistenceClass.Class> set = s.getClasses();
   Iterator<persistenceClass.Class> it = set.iterator();
   while (it.hasNext())
   {
    persistenceClass.Class r = it.next();
    r.getStudents().remove(s);
   }
   p.getBirthCountry();
   p.getCountry();
   this.delete(p);
  }
  else
   this.delete(p);
}

有关信息,我的学生映射文件是:

 <class name="persistenceClass.Person" table="T_PERSON">
  <id name="Id" column="PERSON_ID">
   <generator class="native" />
  </id>
  <property name="FirstName" column="PERSON_FIRST_NAME" not-null="true" />
  <property name="LastName" column="PERSON_LAST_NAME" not-null="true" />
  <property name="Type" column="PERSON_TYPE" not-null="true" />
  <property name="BirthDate" column="PERSON_BIRTH_DATE" />
  <property name="BirthCity" column="PERSON_BIRTH_CITY" />
  <property name="PhoneNumber" column="PERSON_PHONE_NUMBER" />
  <property name="MobileNumber" column="PERSON_MOBILE_NUMBER" />
  <property name="Mail" column="PERSON_MAIL" />
  <property name="Address" column="PERSON_ADDRESS_ADDRESS" />
  <property name="ZipCode" column="PERSON_ADDRESS_ZIPCODE" />
  <property name="City" column="PERSON_ADDRESS_CITY" />
  <property name="Image" column="PERSON_IMAGE" type="image" />
  <many-to-one name="Country" column="PERSON_ADDRESS_COUNTRY" class="persistenceClass.Country" />
  <many-to-one name="BirthCountry" column="PERSON_BIRTH_COUNTRY" class="persistenceClass.Country" />
  <many-to-one name="Civility" column="PERSON_CIVILITY" class="persistenceClass.Civility" />
  <many-to-one name="Sex" column="PERSON_SEX" class="persistenceClass.Sex" />
  <joined-subclass name="persistenceClass.Student" table="T_STUDENT">
   <key column="PERSON_ID" />
   <set name="Classes" table="T_CLASS_STUDENT" inverse="true" >
    <key column="PERSON_ID" />
    <many-to-many class="persistenceClass.Class" column="CLASS_ID" />  
   </set>
  </joined-subclass>
  <joined-subclass name="persistenceClass.Teacher" table="T_TEACHER">
   <key column="PERSON_ID" />
  </joined-subclass>
 </class>

和主映射文件:

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/projet</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- Drop and re-create the database schema on start-up, also try with “update” to keep the previous values -->
<property name="hbm2ddl.auto">update</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource="persistenceConfigurations/Person.hbm.xml"/>
<mapping resource="persistenceConfigurations/Country.hbm.xml"/>
<mapping resource="persistenceConfigurations/Civility.hbm.xml"/>
<mapping resource="persistenceConfigurations/Sex.hbm.xml"/>
<mapping resource="persistenceConfigurations/Formation.hbm.xml"/>
<mapping resource="persistenceConfigurations/Year.hbm.xml"/>
<mapping resource="persistenceConfigurations/Class.hbm.xml"/>
<mapping resource="persistenceConfigurations/Subject.hbm.xml"/>
<mapping resource="persistenceConfigurations/Room.hbm.xml"/>
<mapping resource="persistenceConfigurations/Lesson.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我尝试了很多配置,但每次都遇到相同的异常,如果有人有想法,我想要它!

谢谢!

抱歉我的英语不好

最佳答案

session 并不意味着用于一次调用和关闭。使用实用程序类作为 POJO 的基础并不是一个好主意。

被删除的实体应该使用从中检索到它的同一 session ,或者至少在删除之前在新 session 上刷新。

此外,通过删除依赖“类”实体的迭代应该替换为级联删除。

关于java - hibernate 非法尝试将集合与两个打开的 session 相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4260310/

有关java - hibernate 非法尝试将集合与两个打开的 session 相关联的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  7. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby - Rails 关联 - 同一个类的多个 has_one 关系 - 2

    我的问题的一个例子是体育游戏。一场体育比赛有两支球队,一支主队和一支客队。我的事件记录模型如下:classTeam"Team"has_one:away_team,:class_name=>"Team"end我希望能够通过游戏访问一个团队,例如:Game.find(1).home_team但我收到一个单元化常量错误:Game::team。谁能告诉我我做错了什么?谢谢, 最佳答案 如果Gamehas_one:team那么Rails假设您的teams表有一个game_id列。不过,您想要的是games表有一个team_id列,在这种情况下

  10. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

随机推荐