powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Hibernate 3, Транзакции и Session.flush()
4 сообщений из 4, страница 1 из 1
Hibernate 3, Транзакции и Session.flush()
    #33984366
Alexey Turn
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Клиент отправляет сервлету данные о товаре (Заказ).

Хочется сделать транзакцию, в которой:

При удачном исходе заказ ляжет в базу данных.

При неудачном - не ляжет.

Написал такой код(Session - ThreadLocal):

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
 Hibernate3Support.currentSession().beginTransaction();

                Hibernate3Support.currentSession().setFlushMode(FlushMode.NEVER);

                Client client =  new  Client();

                client.setEmail("temp@temp.ru");

                client.setIsTemporary(Client.IS_TEMPORARY__TRUE);

                Order order =  new  Order();

                order.setClient(client);

                Hibernate3Support.currentSession().save(order);

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
< class  name="Client" table="clients">

		<id name="id" type="string" unsaved-value="null">
			<column name="id" sql-type="varchar(38)" not- null ="true" />
			<generator  class ="guid" />
		</id>
<set name="orders" order-by="order_date desc" cascade="delete"> 
			<key column="client_id" />
			<one-to-many  class ="Order" />
		</set>
...

Hibernate вызывает flush() сам, хотя по докам вроде бы не должен. Изменения ложатся в базу. А мне это нежелательно. Хочу чтобы они были только после commit().

2. Что делает tx.rollback()?
...
Рейтинг: 0 / 0
Hibernate 3, Транзакции и Session.flush()
    #33985815
pretender
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Есть предположение, что проблема в методе
Код: plaintext
Hibernate3Support.currentSession()
похоже, что он возвращает Вам каждый раз новую сессию. Поэтому, уставнока FlashMode сделанная вами, не имеет эффекта в месте сохранения объекта, так как там уже другая сессия. Можете это проверить?

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
Session session =  Hibernate3Support.currentSession();
session.setFlushMode(FlushMode.NEVER);

Client client =  new  Client();
client.setEmail("temp@temp.ru");
client.setIsTemporary(Client.IS_TEMPORARY__TRUE);

Order order =  new  Order();
order.setClient(client);

session.save(order);
...
Рейтинг: 0 / 0
Hibernate 3, Транзакции и Session.flush()
    #33985829
Alexey Turn
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 pretender: попробовал так. Тоже самое. Это та же сессия.

Вот мой Hibernate3Support:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
 public   class  Hibernate3Support
    {
         private   static  Log log = LogFactory.getLog(Hibernate3Support. class );

         protected   static  ClassPathResource[] resources =  new  ClassPathResource[] {  new  ClassPathResource("ru/nnews/kernel/applicationContext-hibernate.xml") };

         private   static   final  SessionFactory sessionFactory;

         public   static   final  ThreadLocal transaction =  new  ThreadLocal();

         static 
            {
                 try 
                    {
                        // Create the SessionFactory

                        GenericApplicationContext ctx =  new  GenericApplicationContext();
                        XmlBeanDefinitionReader reader =  new  XmlBeanDefinitionReader(ctx);
                        reader.loadBeanDefinitions(resources);
                        ctx.refresh();
                        sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
                    }
                 catch  (Throwable ex)
                    {

                        log.error("Initial SessionFactory creation failed.", ex);
                         throw   new  ExceptionInInitializerError(ex);
                    }
            }

         public   static   final  ThreadLocal session =  new  ThreadLocal();

         public   static  Session currentSession()
            {
                Session s = (Session) session.get();
                // Open a new Session, if this Thread has none yet
                 if  (s ==  null )
                    {
                        s = sessionFactory.openSession();
                        session.set(s);
                    }
                 return  s;
            }

         public   static   void  closeSession()
            {
                Session s = (Session) session.get();
                 if  (s !=  null )
                    s.close();
                session.set( null );
            }

        /**
         * Begin Hibernate transaction
         */
         public   static   void  beginTransaction()
            {
                Transaction tx = (Transaction) transaction.get();
                 try 
                    {
                         if  (tx ==  null )
                            {
                                tx = currentSession().beginTransaction();
                                transaction.set(tx);
                            }
                    }
                 catch  (HibernateException e)
                    {
                        log.error("Begin transaction error: " + e.getMessage());
                    }
            }

        /**
         * Commit Hibernate transaction
         */
         public   static   void  commitTransaction()
            {
                Transaction tx = (Transaction) transaction.get();
                 try 
                    {
                         if  (tx !=  null  && !tx.wasCommitted() && !tx.wasRolledBack())
                            {
                                tx.commit();
                            }
                        transaction.set( null );
                    }
                 catch  (HibernateException e)
                    {
                        rollbackTransaction();
                        log.error("Commit transaction error: " + e.getMessage());
                    }
            }

        /**
         * Rollback Hibernate transaction
         */
         public   static   void  rollbackTransaction()
            {
                Transaction tx = (Transaction) transaction.get();
                 try 
                    {
                        transaction.set( null );
                         if  (tx !=  null  && !tx.wasCommitted() && !tx.wasRolledBack())
                            {
                                tx.rollback();
                            }
                    }
                 catch  (HibernateException e)
                    {
                        log.error("Rollback transaction error: " + e.getMessage());
                    }  finally 
                    {
                        closeSession();
                    }
            }

    }




hibernate 3.0 reference

The SQL statements are issued in the following order
1. all entity insertions, in the same order the corresponding objects were saved using Session.save()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions, in the same order the corresponding objects were deleted using Session.delete()

(An exception is that objects using native ID generation are inserted when they are saved.)

Except when you explicity flush(), there are absolutely no guarantees about when the Session executes the
JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the
Query.list(..) will never return stale data; nor will they return the wrong data.



Может из-за этого?:

An exception is that objects using native ID generation are inserted when they are saved
...
Рейтинг: 0 / 0
Hibernate 3, Транзакции и Session.flush()
    #33985940
pretender
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Хм. поэкспериментировал с Вашим примером. Действительно когда переделал
Код: plaintext
<generator  class ="assigned"/>
Все стало работать как и ожидается, т.е. если FlashMode.NEVER, то в базу в не зависимости от save или commit-а транзакции ничего не падает.

Если же
Код: plaintext
<generator  class ="native"/>
ну или как у Вас
Код: plaintext
<generator  class ="guid" />

то Hibernate не обращает никакого внимания на уставноку FlashMode.NEVER и сохраняет объекты в момент их создания.
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Hibernate 3, Транзакции и Session.flush()
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]