I’m a beginner in hibernate.I saw some samples in the internet,
org.hibernate.Session session;
//assuming session instance is initialized
SampleBean msoft=(SampleBean)session.get(SampleBean.class,id);
//**id** is of the type Long
The documentation explanation is,
Object get(Class clazz, Serializable id)
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.
I want to know,
- whether here the id is the primary key?
- Can some body explain me how this method works? Whether it returns only one row in the SampleBean object?
- What will happen if it returns more than one row?
PS:the primary key for the table mapped using SampleBean is of the INT type.
Yes, the id here is the primary key. It will be an instance of whatever type the specified Entity uses are its primary key (so typically Integer, Long, or String, though other types are entirely possible).
The method works by going to the table in the database that corresponds to the given Entity type (
SampleBeanin this case) and executing a fetch based upon primary key. In essence, it runs an SQL query that is roughly likeSELECT * FROM sampleBeanTable t WHERE t.primaryKey = [id];.At most 1 row (or more accurately, 1 instance of the Entity) will be returned (or your database instance is very, very broken because if there are multiple rows that would mean that two or more objects have the same key). If no object is found with the given key then the method returns
null.