Insert Data
In the previous example i taught you how to use hibernate in your application with configuration and JPA annotations. today i shall be talking about how to insert and fetch data from table which is persisted in database.this is linked to the previous tutorial : Hibernate Tutorial
Test is entity class and it is persisted in the database. to insert data inside table of database. you just need to create an object of entity class which Test and add data by using its setter methods. like this:
Test test = new Test();
test.setPassword("password");
test.setUsername("username");
after doing this. you need to create a hibernate session object like this.
Session session = configuration.buildSessionFactory().openSession();
session.beginTransaction();
//it means that you are going to make a transaction with //database.
session.saveOrUpdate(test);
// saveOrUpdate method works like if there is no record exist in //the table then the above data will be inserted if it exists //then the following record will be updated.
session.getTransaction().commit();
session.close();
Fetch Data from Database
After creating session object from the configuration file. you only need to add following line of code:List<Test> list = session.createQuery("from Test").list();
// Test is the entity class. and this HQL query. you can also add
// SQL into it like select * from Test
// Showing Outut of the data
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).username);
}