4

首先抱歉。我知道它有很多相同的主题,但也许我的英语不好,或者我没有找到正确的答案。

我使用乐观锁定@Version 注释。我需要一个表中的一对一的行有来自不同表的许多行,我确实像这样插入:

所以它必须看起来像这样:

机构(这是我的表(机构)的行之一)

       - CreationDate A (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)

       - CreationDate B (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)

       - CreationDate C (this is row from different table(CreationDate) bind with Institution with JoinTable, ManyToMany)

因此,为了将这个 CreationDate 放在不同的变体中,我决​​定为我想要添加我的 CreationDate 的特定机构手动输入 id。

我的主要方法类:

CreationDate crdate = new CreationDate();   
Institution inst= new Institution();
Set<Institution> instituset = new HashSet<Institution>();

***inst.setInstitutionId(2);***

inst.setNameOfInstitution("MyInstitution");
inst.setTypeName("Education");
instituset.add(inst);

当我想将另一行数据附加到我的机构时,用星号标记的行在我的代码中添加了第一次在数据库中插入我的版本行之后更改为一个

这是我的机构实体:

@Entity
@Table(name="INSTITUTION")
public class Institution implements Serializable{


    private static final long serialVersionUID = -7636394097858726922L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="INSTITUTION_ID")
    private int institutionId;


    @Version
    @Column(name="VERSION")
    private int version;


    @Column(name="NAME_INSTITUTION")
    private String nameOfInstitution;

    @Column(name="TYPE_NAME")
    private String typeName;


    @ManyToMany(mappedBy="institution", fetch = FetchType.LAZY)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    private Set<CreationDate> creationDate = new HashSet<CreationDate>();

    //getter and setter methods ommited

    public String toString() {
        return institutionId + " , " + nameOfInstitution + " , " + typeName 
    }       
}

还有我的 CreateDate 实体:

@Entity
@Table(name="CREATION_DATE")
public class CreationDate implements Serializable {


    private static final long serialVersionUID = 1648102358397071136L;

    @Id
    @GeneratedValue(strategy=IDENTITY)
    @Column(name="DATE_ID")
    private int dateId;


    @Column(name="PARTICULAR_DATE")
    private Date particularDate;

    @Version
    @Column(name="VERSION")
    private int version;

    @Temporal(TemporalType.DATE)
    @Column(name="CHILD_GO_SCHOOL_DATE")
    private Date childGoSchoolDate;

    @Temporal(TemporalType.DATE)
    @Column(name="CHILD_ADMISSION_DATE")
    private Date childAdmissionDate;


    @ManyToMany(fetch = FetchType.LAZY)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @JoinTable(name="CREATIONDATE_INSTITUTION", 
                                    joinColumns=@JoinColumn(name="DATE_ID"), 
                    inverseJoinColumns=@JoinColumn(name="INSTITUTION_ID"))
    private Set<Institution> institution = new HashSet<Institution>();

    @OneToMany(fetch=FetchType.EAGER, orphanRemoval=true)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @JoinTable(name="SRC_DATE", joinColumns=@JoinColumn(name="DATE_ID"),
                    inverseJoinColumns=@JoinColumn(name="SRC_ID"))
    private List<ScheduleRotationChild> scheduleRotationChild = new ArrayList<ScheduleRotationChild>();


        //getter and setter methods ommited


    public String toString() {

        return  dateId + " , " 
            + particularDate + " , " 
            + childGoSchoolDate + " , " 
            + childAdmissionDate + "  " + scheduleRotationChild ;

    }
}

我的道:

public CreationDate insertData(CreationDate creationdate) {
        sessionFactory.getCurrentSession().saveOrUpdate(creationdate);
        log.info(creationdate.getDateId());
        return creationdate;

    }

因此,当我第二次尝试将我的数据插入我的机构时,就会发生异常。

 Hibernate: insert into CREATION_DATE (CHILD_ADMISSION_DATE,
 CHILD_GO_SCHOOL_DATE, PARTICULAR_DATE, VERSION) values (?, ?, ?, ?)

 Hibernate: insert into SCHEDULE_ROTATION_CHILD (CHILD_ADMITTED,
 CHILD_GO_SCHOOL, CHILD_UNDER_3_YEARSOLD, CHILD_UPPER_3_YEARSOLD,
 DAY_SCHEDULE, NUMBER_OF_CHILD, ROTATION, VERSION, WORK_SCHEDULE)
 values (?, ?, ?, ?, ?, ?, ?, ?, ?)

 Hibernate: update INSTITUTION set
 NAME_INSTITUTION=?, TYPE_NAME=?, VERSION=? where INSTITUTION_ID=? and
 VERSION=? Exception in thread "main"

org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException:
     Object of class [edu.demidov.dom.Institution] with identifier [2]:
     optimistic locking failed; nested exception is
     org.hibernate.StaleObjectStateException: Row was updated or deleted by
    another transaction (or unsaved-value mapping was incorrect):
     [edu.demidov.dom.Institution#2]
4

4 回答 4

20

我遇到了同样的问题,它是 spring 和 hibernate 的组合。折腾了 3-4 个小时后,我只是随机检查了我的与版本相关的专栏。因为我使用的是一个旧表,我最近在其中引入了版本列,并且没有默认为零 - 所以它已经添加null了所有行和我试图删除的行。所以就像我猜测的那样,我输入了 0,并且神奇地它在下一次运行中起作用。我希望这会有所帮助。

于 2015-06-10T20:33:19.613 回答
3

If I understand correctly, you're trying to add an existing Institution, with the ID 2, to a new CreationDate. Since the Institution already exists, you shouldn't create a new one. You should simply get it from the Hibernate Session:

Institution institution = (Institution) session.load(Institution.class, 2);
creationDate.addInstitution(institution);
于 2013-05-22T16:44:43.597 回答
1

检查您将要更新的模型对象。基本上你应该检查你的“非空”值;就像已经定义的和主键等。这将有所帮助。

于 2020-05-16T07:39:48.437 回答
0

对我来说,问题是我总是使用save相关的方法JpaRepository而不首先获取现有实体。因此,第一次保存总是很顺利,但是当我更新实体时抛出了异常。我检查了version数据库中的列,发现版本永远不会超过 1。确保在更新之前总是尝试获取实体!

于 2021-04-10T21:58:46.930 回答