小编典典

使用Hibernate和Spring实现乐观锁

hibernate

我试图按顺序实施乐观锁定,以避免丢失更新情况。在我的应用程序中,当两个用户获取相同的记录,而第一个用户通过一些更改对其进行更新时。查看相同记录的第二个用户看不到此更改,并且他自己进行了一些更改并更新了该记录。因此,第一人称更改丢失。为了防止这种情况,我写了以下内容,但问题仍然存在。我是这个概念的新手,无法发现问题。

我试图通过阅读doc
11.3.4 来实现这一目标。自定义自动版本控制部分。

  • 配置文件
        <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <tx:annotation-driven transaction-manager="txManager"/>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
      <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="annotatedClasses">
        <list>
            <value>server.bo.Dept</value>
            <value>server.bo.Emp</value>
        </list>
      </property>
      <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props>
      </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
      <property name="url" value="${db.url}"/>
      <property name="username" value="${db.username}"/>
      <property name="password" value="${db.password}"/>
    </bean>
    <bean id="deptDAO" class="server.dao.DeptDAOImpl">
      <property name="hibernateTemplate" ref="hibernateTemplate"/>
    </bean>
    </beans>
  • 实体类
        @Entity
    @Table(name = "Dept")
    @org.hibernate.annotations.Entity(dynamicUpdate = true,optimisticLock = OptimisticLockType.ALL)
    public class Dept{
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        Long id;

        @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "deptId")
        @Fetch(FetchMode.SELECT)
        @OrderBy(value = "id DESC")
        List<Emp> Emplist;

        public Dept() {}
        // Getters and setters
    }
  • DAO Impl
        public class DeptDAOImpl extends HibernateDaoSupport implements DeptDAO {
        @Transactional(readOnly = true, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
        public Dept getDeptById(Long id) {
                Object param[] = new Object[]{id};
                String  query = "select d from Dept d where d.id=? and d.deleted='0'";
                List<Dept> deptDetailsList = getHibernateTemplate().find(query,param);
                Dept deptDetails = null;
                if(deptDetailsList !=null && deptDetailsList .size()>0)
                    deptDetails = (Dept)deptDetailsList.get(0);
                return deptDetails ;
        }

        @Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
        public long updateDept(Dept dept) {
                if (dept.getId() == null) { 
                    getSession().save(dept);
                } else {
                    getSession().update(dept);
                }
                if (dept.getEmplist() != null) {
                        final int size = dept.getEmplist().size();
                        for (int i = size - 1; i >= 0; i--) { 
                            Emp emp = dept.getEmplist().get(i);
                            if (emp.getDeptId() == null) {
                                emp.setDeptId(dept.getId());
                        }
                        if (RecordStatus.NEW.equals(emp.getRecordStatus())) {
                            getSession().save(emp);
                        } else if (RecordStatus.DELETED.equals(emp.getRecordStatus())) {
                            getSession().delete(emp);
                        } else if (RecordStatus.MODIFIED.equals(emp.getRecordStatus())) {
                            getSession().update(emp);
                        }
                    }
            }
            return dept.getId();
        }
    }

提前致谢


阅读 211

收藏
2020-06-20

共1个答案

小编典典

JPA / Hibernate
Optmistic锁定的工作方式是使用某个字段来存储上次修改的版本(例如,时间戳,long),然后将会话中实体的版本与数据库中的实体进行比较,以查看是否可以保存更改。

为此,您需要在实体中使用@Version注释字段。

参见以下示例。

http://www.javacodegeeks.com/2012/11/jpahibernate-version-based-optimistic-
concurrency-control.html

为了使它在Web应用程序中起作用,需要进一步考虑,但是,好像两个人加载了相同的实体进行编辑,然后过一会儿提交他们的编辑,他们很可能都会成功,除非您使用某种长时间运行的会话,否则该实体正在编辑的文件将从表单提交的数据库中重新加载,填充和保存。

例如,修订版1中的实体

  • 用户1加载以进行编辑:版本为1
  • 用户2进行编辑加载:修订为1
  • 用户2提交表单:已加载实体(在r1处),绑定了字段,已保存实体:修订版为2。
  • 用户1提交表单:已加载实体(在r2处),绑定了字段,已保存实体:修订版为3。

因此,要使此工作正常进行,您可以看一下提交一个隐藏字段的表单,该表单在存储实体修订版本时将其存储。因此,在上面的最后一步,当用户1提交时,修订字段将被设置回1,并且更新将失败,因为数据库中的记录在r2处。

2020-06-20