使用Hibernate和Spring实现乐观锁

使用Hibernate和Spring实现乐观锁,spring,hibernate,optimistic-locking,optimistic-concurrency,Spring,Hibernate,Optimistic Locking,Optimistic Concurrency,我试图实现乐观锁定,以避免丢失更新的情况。在我的应用程序中,两个用户获取同一条记录,第一个用户用一些更改来更新它。此更改对于查看同一记录的第二个用户不可见,他自己进行了一些更改并对其进行了更新。因此,第一批人员变更丢失。为了防止这种情况,我写了以下内容,但问题仍然存在。我不熟悉这个概念,无法确定问题所在 我试图通过阅读11.3.4来实现这一点。自定义自动版本控制部分 配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmln

我试图实现乐观锁定,以避免丢失更新的情况。在我的应用程序中,两个用户获取同一条记录,第一个用户用一些更改来更新它。此更改对于查看同一记录的第二个用户不可见,他自己进行了一些更改并对其进行了更新。因此,第一批人员变更丢失。为了防止这种情况,我写了以下内容,但问题仍然存在。我不熟悉这个概念,无法确定问题所在

我试图通过阅读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>
    
    
    服务端
    server.bo.Emp
    org.hibernate.dialogue.sqlserver2008dialogue
    假的
    
  • 实体类

    @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
    }
    
    @实体
    @表(name=“Dept”)
    @org.hibernate.annotations.Entity(dynamicUpdate=true,optimisticLock=OptimisticLockType.ALL)
    公共课部{
    @身份证
    @GeneratedValue(策略=GenerationType.AUTO)
    @列(name=“ID”)
    长id;
    @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.EAGER,mappedBy=“deptId”)
    @Fetch(FetchMode.SELECT)
    @订购人(value=“id DESC”)
    雇主名单;
    公共部门(){}
    //接球手和接球手
    }
    
  • 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();
        }
    }
    
    public类DeptDAOImpl扩展了HibernateDaoSupport实现DeptDAO{
    @事务性(只读=true,传播=propagation.REQUIRED,隔离=isolation.REPEATABLE\u READ)
    公共部门getDeptById(长id){
    对象参数[]=新对象[]{id};
    String query=“从d部门中选择d,其中d.id=?和d.deleted='0';
    List deptDetailsList=getHibernateTemplate().find(查询,参数);
    Dept deptDetails=null;
    if(deptDetailsList!=null&&deptDetailsList.size()>0)
    deptDetails=(Dept)deptDetailsList.get(0);
    返回部门详细信息;
    }
    @事务性(readOnly=false,propagation=propagation.REQUIRED,isolation=isolation.REPEATABLE\u READ)
    公共长期更新部分(部门){
    如果(dept.getId()==null){
    getSession().save(部门);
    }否则{
    getSession()更新(部门);
    }
    如果(部门getEmplist()!=null){
    final int size=dept.getEmplist().size();
    对于(inti=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);
    }
    }
    }
    退货部门getId();
    }
    }
    

提前感谢

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

要使其工作,您需要在实体中有一个用@Version注释的字段

请参见下面的示例

为了在web应用程序中工作,需要进一步考虑,如果两个人加载相同的实体进行编辑,然后在稍后提交他们的编辑,他们很可能都会成功,因为除非您使用某种长时间运行的会话,否则正在编辑的实体将在表单提交时从数据库重新加载,填充并保存

e、 g.第1版实体

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

因此,为了实现这一点,您可以考虑使用表单提交一个隐藏字段,该表单在加载实体修订时存储实体修订。因此,在上面的最后一步中,当用户1提交时,修订字段将设置回1,更新将失败,因为数据库中的记录在r2处。

我将避免使用隐藏字段,因为恶意用户可以更改这些值,并使系统进入意外状态。为了安全起见,应该在服务器端维护状态。再见,你好,内森。我熟悉参数篡改的危险性。鉴于到达此屏幕的用户显然具有编辑权限,您能建议用户篡改版本号的任何后果吗?除非我遗漏了什么,否则不要求用户能够将版本号设置为任意值,因此不应从用户输入中读取版本。服务器应该在会话中维护版本号,而不是让用户能够更改他们不需要的内容(例如)。是的,您可以将其放在会话中,但是我不太喜欢将内容放在会话中。此外,将它放在会话中并不能解决这个问题:与其编辑隐藏字段,我只需附加一个额外的参数。事实上,在给出的示例中,我不在乎用户是否将版本从10更改为100:这是一个没有意义的任意数字。@Nathan隐藏字段版本号对我来说不是问题。如何防止用户简单地刷新页面、忽略所做的修改、将所有字段设置为原来的字段并再次提交?你不能阻止那些有令状的人