Take a look at the following sample code:
1 Configuration config = new Configuration();
2 SessionFactory sessionFactory = null;
3 Session session = null;
4
5 try {
6 sessionFactory = config. configure()
7 .buildSessionFactory();
8 session = sessionFactory.openSession();
9 Transaction transaction = session.beginTransaction();
10 Employee employee = new Employee();
11 employee.setEmpno(new Integer(1));
12 employee.setName("tanaka");
13 employee.setAge(new Integer(25));
14 session.save(employee); // duplicated primary key error.
15 transaction.commit();
16 } catch (HibernateException e) {
17 try {
18 List employees = session
19 .find("from Employee where Empno = 1");
20 System.out.println((Employee) employees.get(0));
21 } catch (HibernateException he) {
22 he.printStackTrace();
23 } finally {
24 try {
25 if (session != null) {
26 session.close();
27 }
28 } catch (HibernateException e) {
29 e.printStackTrace();
30 }
31 }
32 }
Output from line 20:
emnno = 1
name = tanaka
age = 25
Database:
>> select * from Employee;
+----------+--------+------+
| empno | name | age |
+----------+--------+------+
| 1 | sato | 27 |
+----------+--------+------+
Initialize Employee instance between line 10 to 13.
Persistent employee at line 14.
We've encounted duplicated primary key error at line 14,
so program jumped catch block at line 16.
Session#find() at line 19 returns employee which name is tanaka (Our expectation is sato).
1. It's more than probable that the session cache was not clear when Session#save() failed
and rollback happened and the session cache was not consistent with database. Is it a bug or not?
2. We expected that the session cache was updated by the results of Session#find()
and avoided noted above situation, but not. Why?
3. We've inserted Session#evict() or Session#refresh() between line 17 and 18 to avoid this.
Is there any solution for this problem ?
Thank you.
|