26 April 2011

Hibernate First Steps

For adding a new object (to database) the code below suffice (you still need to define xml files / JPA annotation still for hibernate configuration):



Configuration conf = new Configuration().configure(file);
SessionFactory sessionFactory = conf.buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object


Transaction tx;
tx = session.beginTransaction();

System.out.println("Inserting Record");
contact contact = new contact();
contact.setId(6);
contact.setFirstName("firstt");
contact.setLastName("lfirstt");
session.save(contact);

System.out.println("Done");

tx.commit();




This is not the whole code, you need to take into consideration the flush and close of the session.
For updating or deleting, one should know the uniqeIdentifier, if not you can use SQL query to get that (not described here how).
When you have that identifier, you just need to have the following code:




Long identifier = (long) 2;
contact contact1 = (contact) session.load(contact.class, identifier);
System.out.println(contact1.getEmail());

No comments:

Post a Comment