If I use getCurrentSession() to obtain session and I don't begin transaction and save gives exception but when I use openSession() to get session then in the same scenario the program runs without any exception."hibernate.current_session_context_class" is configured with thread in hibernate configuration file.So what is the difference when I use getCurrentSession() and openSession().
Here is the code that gets session using getCurrentSession()-
public static void main(String ar[])
{
SessionFactory sfac=null;
sfac=new Configuration().configure("hibernateconfig/rs.xml")
.buildSessionFactory();
try {
Session session=sfac.getCurrentSession();
Student stu=new Student();
stu.setFirstName("abc23");
stu.setLastName("xyz");
System.out.println("-------------"+stu);
session.save(stu);
}
catch(Exception e)
{
System.out.println(e);
}
}
output-
-------------Student [id=0, firstName=abc23, lastName=xyz]
org.hibernate.HibernateException: save is not valid without active transaction
Here is the code that gets session using openSession()-
public static void main(String ar[])
{
SessionFactory sfac=null;
sfac=new Configuration().configure("hibernateconfig/rs.xml")
.buildSessionFactory();
try {
Session session=sfac.openSession();
Student stu=new Student();
stu.setFirstName("abc23");
stu.setLastName("xyz");
System.out.println("-------------"+stu);
session.save(stu);
}
catch(Exception e)
{
System.out.println(e);
}
}
output-
-------------Student [id=0, firstName=abc23, lastName=xyz]
Hibernate:
insert
into
student
(firstName, lastName)
values
(?, ?)