Your UserDAO.java will now look like this:
package org.confucius;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class UserDAO {
public static void persist (User user) throws Exception{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
try {
session.persist(user);
tx.commit();
}
catch (Exception e){
tx.rollback();
throw e;
}
session.close();
}
}
We start by getting a new session from the Hibernate SessionFactory.
We start a new transaction, persist the user, then commit (or rollback) the transaction.
Strictly speaking, we did not have to do this in a transaction. Because there is only one database interaction. However, it is highly recommended in Hibernate to do all database interactions inside a transaction. It keeps the internal state of the Hibernate session clean.
Finally, update the TestPersistence.java to use the new DAO, like this:
package org.confucius;
public class TestPersistence {
public static void main(String[] args) {
User joe = new User();
joe.setFirstName("Joe");
joe.setLastName("Trumpet");
try {
UserDAO.persist(joe);
} catch (Exception e) {
e.printStackTrace();
}
}
}
R-click on TestPersistence.java in Eclipse Navigator view. Select Run As-->Java Application.
Now if you go to your MySQL Command Line Client, you will see a new table 'user' containing 'Joe Trumpet', like this:
mysql> select * from user;
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
| 1 | Joe | Trumpet |
+----+-----------+----------+
1 row in set (0.00 sec)
No comments:
Post a Comment