views:

33

answers:

3

Hey

i have two entiies connected through a many to one realtionship.

many[category]---------one[game]

columns

idgame----------------------gameid
category------------------game name

I need to have many occureneces of the game primaary key in the category part of the realtionship. I have tried to do this in a session but i get the error. "a different object with the same identifier value was already associated with the session: [org.POJO.Category#1]".

I think my config file is wrong but i maybe wrong. heres my code.

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);

My config file for category. its xml.

-hibernate-mapping-

-class name="org.POJO.Category" table="Category"-

-id name="gameid" column="Game_idGame" -

-/id-

-property name="category" column="category"/-

-/class- -/hibernate-mapping-

sdfdsfsdfsdf

+2  A: 

The identifier (id) is logically (and technically) equal to the primary key. You can't have two objects with the same primary key, therefore you can't have two objects with the same idenetifier.

The primary key of a relational table uniquely identifies each record in the table.

If you need two objects with the same primary key, there is something wrong with your design.

Bozho
A: 

Category cannot use the gameid as primary key. It needs to have its own primary key. The game id will be a foreign key referencing the game id from game table.

Vinodh Ramasubramanian
Thanks guys that was really helpful.
Shino88
A: 

You have chosen to have many of the gameid-s. Primary keys are meant to uniquely identify each entity (row) in the table, not an associated one. Therefore you should have an categoryid as PK in categories, and a plain index on the idgame.

sibidiba