Reputation: 786
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,
PS:the primary key for the table mapped using SampleBean is of the INT type.
Upvotes: 0
Views: 166
Reputation: 11767
I want to know, whether here the id is the primary key?
Yes. The id should be unique.
Can some body explain me , how this method works,
Looks up the DB for the specified ID and returns a instance of clazz .
Whether it returns only one row in the SampleBean object?
Yes. Since id is unique and there should be only one row.
What will happen if it returns more than one row?
Can't happen if id is unique or primary key.
Upvotes: 2
Reputation: 54816
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 (SampleBean
in this case) and executing a fetch based upon primary key. In essence, it runs an SQL query that is roughly like SELECT * 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
.
Upvotes: 1