日期:2014-05-20  浏览次数:20856 次

写ssh的时候有了一个删除实体的疑惑
原来单独使用hibernate的时候,删除一个持久化对象就是用session。delete(id)。但是今天在用spring的模板api的时候看到这样一个方法:

Java code

public void delete(Object entity,LockMode lockMode)



想了想,貌似是应该加个锁。。怎么hibernate自己不提供呢?到底有必要为删除加锁么?具体加什么类型的锁呢?

------解决方案--------------------
探讨
话说删除某条记录就是一条delete sql语句,一条sql语句是原子的么?

------解决方案--------------------
昨天刚打了两行就开会去了。

大学的书其实就已经很好了,我记得应该叫做《数据库原理》。

这么说吧,你可以先考虑下,要怎么样来实现几种效果,比如:脏读 和 幻读

然后再反过来想想如果数据库啥隔离机制都不提供,你能咋办,然后再想想应该用数据库的什么隔离机制。
------解决方案--------------------
这个问题以前还真没有注意到。刚研究了下。
spring 这个方法的实现是这样的。
Java code

    public void delete(final Object entity, final LockMode lockMode) throws DataAccessException {
        executeWithNativeSession(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException {
                checkWriteOperationAllowed(session);
                if (lockMode != null) {
                    session.lock(entity, lockMode);
                }
                session.delete(entity);
                return null;
            }
        });
    }

------解决方案--------------------
一般书籍中将对象的状态分为三中,但在《Hibernate in Action 2th》分为了四种

多出来的一种原文摘录如下:
Removed objects
You can delete an entity instance in several ways: For example, you can remove it
with an explicit operation of the persistence manager. It may also become available
for deletion if you remove all references to it, a feature available only in
Hibernate or in Java Persistence with a Hibernate extension setting (orphan deletion
for entities).
An object is in the removed state if it has been scheduled for deletion at the end
of a unit of work, but it’s still managed by the persistence context until the unit of
work completes. In other words, a removed object shouldn’t be reused because it
will be deleted from the database as soon as the unit of work completes. You
should also discard any references you may hold to it in the application (of
course, after you finish working with it—for example, after you’ve rendered the
removal-confirmation screen your users see).