Abhishek3 1
Abhishek3 1
Abhishek3 1
Task to be done:
Here is a simple program in Hibernate that demonstrates how to create an entity, persist it to the
/**
* A sample program that demonstrates how to perform simple CRUD operations * with Hibernate
framework. * @author www.codejava.net
*
*/ public class ContactManager { public static void
main(String[] args) {
// loads configuration and creates a session factory
Configuration configuration = new Configuration().configure(); ServiceRegistryBuilder registry
= new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// opens a new session from the session factory Session session
= sessionFactory.openSession();
session.beginTransaction();
// persists two new Contact objects
Contact contact1 = new Contact("Nam", "hainatuatgmail.com", "Vietnam",
"0904277091"); session.persist(contact1);
Contact contact2 = new Contact("Bill", "billatgmail.com", "USA", "18001900");
Serializable id = session.save(contact2);
System.out.println("created id: " + id);
// deletes an object
Contact contact7 = new Contact();
contact7.setId(7); session.delete(contact7);
// deletes a loaded instance of an object
Contact contact8 = (Contact) session.load(Contact.class, new Integer(8)); session.delete(contact8);
}
}
This program defines an Employee entity class with three fields: id, name, and department. It uses
Hibernate to persist an instance of this class to a database, and then retrieves and prints the
persisted data.
Working with Hibernate transaction –
session.beginTransaction();
try {
session.persist(Object); session.update(Object);
session.delete(Object); } catch (Exception ex)
{ session.getTransaction().rollback();
} session.getTransaction().commit();
session.close();
3. Result/Output/Writing Summary:
2. Worksheet 10
3. Lab Quiz 5