2010-02-02 54 views
0

可能重复:
Hibernate: different object with the same identifier value was already associated with the session将具有相同标识符的对象保存到同一会话中的数据库中吗?

我有通过许多连接到一个realtionship 2个entiies。

许多[类别] ---------酮[游戏]

idgame ------------------- --- gameid
类别------------------游戏名称

我需要在realtionship的category部分有很多游戏主键的时机。我曾尝试在会话中做到这一点,但我得到的错误。 “具有相同标识符值的不同对象已与会话相关联:[org.POJO.Category#1]”。

我想我的配置文件是错误的,但我可能错了。继承我的代码。

try{ 
     SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
     session = sessionFactory.openSession(); 
      //Create new instance of Contact and set 
     Transaction tx = session.beginTransaction(); 
     Game gam = new Game(); 

     gam.setgenre(game.getString("genre")); 
     gam.setgname(game.getString("game_name")); 
     gam.setplatform(game.getString("platform")); 
     gam.setdescription(game.getString("description")); 

     session.saveOrUpdate(gam); 

     session.update(gam); 
     JSONObject cate = game.getJSONObject("Category"); 

     int gid = gam.getgameid(); 

     Category cat1 = new Category(); 

     cat1.setgameid(gid); 
     cat1.setcategory(cate.getString("Category1")); 

     session.save(cat1); 


     Category cat2 = new Category(); 

     cat2.setgameid(gid); 
     cat2.setcategory(cate.getString("Category2")); 

     session.save(cat2); 

我的配置文件的类别。它的XML。

-hibernate-mapping- 

-class名称= “org.POJO.Category” 表= “类别” -

-id名称= “游戏ID” 列= “Game_idGame” -

-/ID-

-property 名称= “类别” 栏 = “类别”/ -

- /类 - - /休眠-mapping-

sdfdsfsdfsdf

回答

3

标识符(id)在逻辑上(和技术上)等于主键。不能有两个具有相同主键的对象,因此不能有两个具有相同标识符的对象。

关系表的主键唯一标识表中的每条记录。

如果需要两个对象具有相同的主键,有什么不对您的设计。

0

类别不能使用gameid作为主键。它需要有自己的主键。游戏ID将是游戏表中引用游戏ID的外键。

+0

非常感谢你们的帮助。 – Shino88

0

你已经选择了很多gameid-s。主键旨在唯一标识表中的每个实体(行),而不是关联的实体。因此,你应该在类别中有一个类别ID,并且在idgame上有一个简单的索引。

相关问题