Hibernate save()
This tutorial explain how save() works in hibernate.
Hibernate save() :
The function of save() is to save content into database. It saves new record without caring of existence of ID.
session.save(Object object) : saves the instance of
persistent class into database table.
Here object is your persistent class.
session.save(String entityName, Object object) : Persist the
given transient instance, first assigning a generated identifier.
Here is two parameter one is entityName and other is Object, your persistent
class.
Example : In this example we are saving student record by using save().
package net.roseindia.main; import net.roseindia.table.Student; import net.roseindia.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; public class MainClazz { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try {transaction=session.beginTransaction(); Student student=new Student(); student.setRoll(7); student.setName("Glinto"); student.setCourse("Hibernate"); session.save(student); transaction.commit(); System.out.println("Record saved"); session.flush(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }
Output:
Hibernate: insert into student (course, name) values (?, ?) Record saved