Hibernate: How to get new id created as a result of insert - java

I have a hibernate code which insert a new role to the table as follows:
Staff staff = new Staff(staffDTO);
Session session = sessionManager.getSession();
session.beginTransaction();
session.save(staff);
session.getTransaction().commit();
Staff is defined as entity.
My question is that how can I get the newly generated row id by the database?
Many thanks.

Hibernate is smart enough :).
After you save the Object in database If you see ,the object have the generated id. Check it.
After save done, just inspect the object and see.

Related

Hibernate how to get updated properties

How to get which properties were updated after hibernate update?
For example if I got
SomeEntity se = new SomeEntity();
getHibernateTemplate().save(se);
//then in some other method
se.setProp1("some new value");
//then in 3th method
getHibernateTemplate().update(se);
If you tell hibernate to do dynamic update it will know witch properties were changed and update only them. Is there a way to get the ones that were changed or to check is specific property was changed?
Ended up doing native sql query to compare the state in the db with the state in the entity before flush the session.
Query query = session.createSQLQuery(
"select t.someProp1 from someTable t where t.id = :entityId")
.setParameter("entityId", entity.getId());
List result = query.list();

Hibernate delete object without deleting related objects

I have a database with 3 tables: Slideshows, MediaItemsInSlideshows and Mediaitems. I am using this database with a jsp site using hibernate.
I would like to be able to delete a slideshow without deleting the mediaitems. The rows in the MediaItemsInSlideshows should be deleted though.
Currently I use the following code to remove the slideshow. When I use this all mediaitems that were used in the slideshow are gone.
Session session = HibernateUtil.getSessionFactory().openSession();
Slideshow s = this.getSlideshowById(id, session);
session.beginTransaction();
session.delete(s);
session.getTransaction().commit();
This is a visual representation of the database:
Deleting A will set the reference to it in B to null which is forbidden by the schema. An alternative to changing the order of deletions would be to add a reverse one-to-many collection in B, with cascaded deletes. Only the deletion of A would than be needed.
(source: Deleting of related objects in hibernate)

Execute Insert and Select queries simultaneously from Hibernate

I have the following pl/sql query,
INSERT INTO Table(ID,..................)
VALUES(SEQ.nextval,....................);
SELECT SEQ.currval ID FROM DUAL;
I need to get ID using hibernate. I am using the following query which showing error,
.....getDataSession().createSQLQuery(hQuery).list()
Any one help me.
Create new Object and save it using session.save() method it will return this object id.
Object object = new Object();
//add object properties
object.setXXX(value);
//now save the object
String id =(String)getDataSession().save(object);
Hope it helps.

Hibernate - how to create list of pojos?

I am very new to Hibernate. I have MySQL database and mapped pojos. What should I do next? I know little bit LINQ to SQL from .NET, and it generates me List of mapped objects.
So basically, what are my next steps after creating POJOS if I want to have List of them and do CRUD operations upon them and data will be also saved in DB not only in java objects ?
kthx
please see the hibernate document - Chapter 10. Working with objects
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html#objectstate-querying-executing
You can createQuery() or createCriteria() to get a list of your pojos. for example:
List cats = session.createQuery("from Cat").list();
or
List cats = session.createCriteria(Cat.class).list();
To answer your question about the rest of CRUD, once you've got your list of objects, as described by qrtt1, then you can manipulate the objects in the session:
Session session = // obtain session
Transaction tx = session.beginTransaction();
List cats = session.createQuery("from Cat").list();
Cat firstCat = (Cat)cats.get(0);
firstCat.setName("Cooking Fat");
firstCat.setOwner("Richard O'Sullivan");
// etc for other cats in the collection
tx.commit();
session.close();
Any objects that you obtained via the query are "dirty checked" at the tx.commit(); this means that in this case an update statement will be issued for the first cat retrieved from the query.

Save more than object with the same identifier into a database in the same session? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Hibernate: different object with the same identifier value was already associated with the session
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
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.
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.
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.

Categories

Resources