Reputation: 5396
I am learning Hibernate from beginning. I downloaded hibernated demo from RoseIndia. Setup configuration of hibernate.cfg.xml for specific database. And ran below code. Tables specified overhere 'contact' is created automatically but below code can't save the new record. Is there any thing wrong in below code?
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* Hibernate example to inset data into Contact table
*/
public class FirstExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
//contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("[email protected]");
System.out.println("Before Save");
session.save(contact);
System.out.println("After Save");
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
My Out put is as below
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Before Save
After Save
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Upvotes: 2
Views: 5135
Reputation: 7894
You need to wrap your code in a transaction:
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// your code
transaction.commit();
Upvotes: 7