我有一个包含多对一关系的jpa持久化对象模型:一个Account有多个transaction。一个事务有一个帐户。

下面是一段代码:

@Entity
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    private Account fromAccount;
....

@Entity
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany(cascade = {CascadeType.ALL},fetch= FetchType.EAGER, mappedBy = "fromAccount")
    private Set<Transaction> transactions;

我能够创建Account对象,向其添加事务,并正确地持久化Account对象。但是,当我创建一个事务,使用现有的已经持久化的帐户,并持久化的事务,我得到一个异常:

导致:org.hibernate.PersistentObjectException:传递给persist: com.paulsanwald.Account的分离实体 org.hibernate.event.internal.DefaultPersistEventListener.onPersist (DefaultPersistEventListener.java: 141)

因此,我能够持久化一个包含事务的Account,但不能持久化一个具有Account的Transaction。我认为这是因为帐户可能没有附加,但这段代码仍然给了我相同的异常:

if (account.getId()!=null) {
    account = entityManager.merge(account);
}
Transaction transaction = new Transaction(account,"other stuff");
 // the below fails with a "detached entity" message. why?
entityManager.persist(transaction);

如何正确地保存与已经持久化的帐户对象相关联的事务?


可能在这种情况下,您使用merge逻辑获得了帐户对象,而persist用于持久化新对象,如果层次结构有一个已经持久化的对象,它将报错。在这种情况下,应该使用saveOrUpdate,而不是持久化。

在您的实体定义中,您没有为联接到事务的帐户指定@JoinColumn。你会想要这样的东西:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

编辑:嗯,我想如果您在类上使用@Table注释,那么这将是有用的。哈。:)

这是一个典型的双向一致性问题。在这个链接和这个链接中都有很好的讨论。

根据前两个链接中的文章,您需要在双向关系的两侧修复您的setter。一方的示例setter在此链接中。

在此链接中有一个用于多方的示例setter。

在你纠正你的setter之后,你想要声明实体访问类型为“属性”。声明“Property”访问类型的最佳实践是将所有注释从成员属性移动到相应的getter。一个重要的警告是不要在实体类中混合使用“Field”和“Property”访问类型,否则JSR-317规范没有定义行为。

也许这是OpenJPA的bug,当回滚时它重置了@Version字段,但pcVersionInit保持true。我有一个声明@Version字段的AbstraceEntity。我可以通过重置pcVersionInit字段来解决它。但这不是一个好主意。我认为它不工作时,级联坚持实体。

    private static Field PC_VERSION_INIT = null;
    static {
        try {
            PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
            PC_VERSION_INIT.setAccessible(true);
        } catch (NoSuchFieldException | SecurityException e) {
        }
    }

    public T call(final EntityManager em) {
                if (PC_VERSION_INIT != null && isDetached(entity)) {
                    try {
                        PC_VERSION_INIT.set(entity, false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                    }
                }
                em.persist(entity);
                return entity;
            }

            /**
             * @param entity
             * @param detached
             * @return
             */
            private boolean isDetached(final Object entity) {
                if (entity instanceof PersistenceCapable) {
                    PersistenceCapable pc = (PersistenceCapable) entity;
                    if (pc.pcIsDetached() == Boolean.TRUE) {
                        return true;
                    }
                }
                return false;
            }

解决方案很简单,只需使用CascadeType。MERGE而不是CascadeType。PERSIST或CascadeType.ALL。

我也遇到过同样的问题和CascadeType。MERGE对我很有效。

我希望你已经整理好了。

使用合并是有风险和棘手的,所以在您的情况下,这是一种肮脏的变通方法。您至少需要记住,当您将一个实体对象传递给merge时,它将停止附加到事务,而是返回一个新的、现在已附加的实体。这意味着如果任何人仍然拥有旧的实体对象,那么对它的更改将被无声地忽略并在提交时丢弃。

You are not showing the complete code here, so I cannot double-check your transaction pattern. One way to get to a situation like this is if you don't have a transaction active when executing the merge and persist. In that case persistence provider is expected to open a new transaction for every JPA operation you perform and immediately commit and close it before the call returns. If this is the case, the merge would be run in a first transaction and then after the merge method returns, the transaction is completed and closed and the returned entity is now detached. The persist below it would then open a second transaction, and trying to refer to an entity that is detached, giving an exception. Always wrap your code inside a transaction unless you know very well what you are doing.

使用容器管理的事务,它看起来像这样。注意:这假设方法在会话bean中,并通过本地或远程接口调用。

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void storeAccount(Account account) {
    ...

    if (account.getId()!=null) {
        account = entityManager.merge(account);
    }

    Transaction transaction = new Transaction(account,"other stuff");

    entityManager.persist(account);
}

即使正确地声明了注释以正确地管理一对多关系,您仍然可能遇到这种异常。当向附加的数据模型添加新的子对象Transaction时,您需要管理主键值—除非您不需要这样做。如果在调用persist(T)之前为如下声明的子实体提供主键值,则会遇到此异常。

@Entity
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
....

在本例中,注释声明数据库将在插入时管理实体主键值的生成。自己提供一个(比如通过Id的setter)会导致此异常。

或者,但实际上是一样的,这个注释声明会导致相同的异常:

@Entity
public class Transaction {
    @Id
    @org.hibernate.annotations.GenericGenerator(name="system-uuid", strategy="uuid")
    @GeneratedValue(generator="system-uuid")
    private Long id;
....

因此,当应用程序代码已经被管理时,不要在应用程序代码中设置id值。

如果没有任何帮助,并且您仍然得到这个异常,请检查equals()方法—并且不要在其中包含子集合。特别是当你有嵌入式集合的深层结构时(例如A包含B, B包含c,等等)。

以Account ->为例:

  public class Account {

    private Long id;
    private String accountName;
    private Set<Transaction> transactions;

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (!(obj instanceof Account))
        return false;
      Account other = (Account) obj;
      return Objects.equals(this.id, other.id)
          && Objects.equals(this.accountName, other.accountName)
          && Objects.equals(this.transactions, other.transactions); // <--- REMOVE THIS!
    }
  }

在上面的例子中,从equals()检查中删除事务。这是因为hibernate将暗示您不尝试更新旧对象,而是在更改子集合上的元素时传递一个新对象来持久化。 当然,这种解决方案并不适用于所有应用程序,您应该仔细设计想要包含在equals和hashCode方法中的内容。

您需要为每个帐户设置事务。

foreach(Account account : accounts){
    account.setTransaction(transactionObj);
}

或者在许多方面将id设置为null就足够了(如果合适的话)。

// list of existing accounts
List<Account> accounts = new ArrayList<>(transactionObj.getAccounts());

foreach(Account account : accounts){
    account.setId(null);
}

transactionObj.setAccounts(accounts);

// just persist transactionObj using EntityManager merge() method.

不要将id(pk)传递给persist方法或尝试save()方法而不是persist()。

cascadeType.MERGE,fetch= FetchType.LAZY

从子实体Transaction中移除级联,它应该是:

@Entity class Transaction {
    @ManyToOne // no cascading here!
    private Account account;
}

(FetchType。EAGER可以被删除,它是默认的@ManyToOne)

这是所有!

为什么?通过在子实体Transaction上说“cascade ALL”,你要求每个DB操作都被传播到父实体Account。如果执行持久化(事务),也会调用持久化(帐户)。

但是只有暂时的(新的)实体可以被传递给持久化实体(在本例中是事务)。分离的(或其他非瞬态)可能不会(在本例中是Account,因为它已经在DB中)。

因此,您会得到异常“传递给持久化的分离实体”。Account实体的意思是!而不是调用持久化的事务。


一般来说,你不希望从子繁殖到父。不幸的是,在书中(甚至是很好的书)和网上有许多代码示例,它们正是这样做的。我不知道,为什么……也许有时只是一遍又一遍地复制,没有多想……

猜猜如果你调用remove(transaction)在@ManyToOne中仍然有“级联ALL”会发生什么?帐户(顺便说一下,所有其他交易!)也将从数据库中删除。但这不是你的本意,对吧?

在我的情况下,我正在提交事务时,持久化方法被使用。 在更改persist to save方法时,该问题得到了解决。

如果上述解决方案不工作,只需一次注释实体类的getter和setter方法,并且不设置id的值。(主键) 这样就可以了。

@OneToMany(mappedBy = "xxxx", cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE})

为我工作。

移除子关联级联

因此,您需要删除@CascadeType。这些都来自@ManyToOne协会。子实体不应该级联到父关联。只有父实体应该级联到子实体。

@ManyToOne(fetch= FetchType.LAZY)

注意,我将fetch属性设置为FetchType。LAZY,因为急切抓取对性能非常不利。

设置关联的双方

当你有一个双向关联时,你需要在父实体中使用addChild和removecchild方法来同步双方:

public void addTransaction(Transaction transaction) {
    transcations.add(transaction);
    transaction.setAccount(this);
}

public void removeTransaction(Transaction transaction) {
    transcations.remove(transaction);
    transaction.setAccount(null);
}

我基于Spring Data jpa的回答是:我只是在外部方法中添加了一个@Transactional注释。

为什么它有效

由于没有活动的Hibernate Session上下文,子实体立即被分离。提供一个Spring (Data JPA)事务可以确保存在Hibernate会话。

参考:

https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/

通过在下一个对象之前保存依赖对象来解决。

这发生在我身上,因为我没有设置Id(这不是自动生成的)。并试图拯救@ManytoOne的关系

这是一个老问题,但最近又遇到了同样的问题。在这里分享我的经验。

实体

@Data
@Entity
@Table(name = "COURSE")
public class Course  {

    @Id
    @GeneratedValue
    private Long id;
}

保存实体(JUnit)

Course course = new Course(10L, "testcourse", "DummyCourse");
testEntityManager.persist(course);

Fix

Course course = new Course(null, "testcourse", "DummyCourse");
testEntityManager.persist(course);

结论:如果实体类的主键(id)有@GeneratedValue,那么确保您没有传递主键(id)的值

这是我的药。

Below is my Entity. Mark that the id is annotated with @GeneratedValue(strategy = GenerationType.AUTO), which means that the id would be generated by the Hibernate. Don't set it when entity object is created. As that will be auto generated by the Hibernate. Mind you if the entity id field is not marked with @GeneratedValue then not assigning the id a value manually is also a crime, which will be greeted with IdentifierGenerationException: ids for this class must be manually assigned before calling save()

@Entity
@Data
@NamedQuery(name = "SimpleObject.findAll", query="Select s FROM SimpleObject s")
public class SimpleObject {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String key;

    @Column
    private String value;

}

这是我的主类。

public class SimpleObjectMain {

    public static void main(String[] args) {

        System.out.println("Hello Hello From SimpleObjectMain");

        SimpleObject simpleObject = new SimpleObject();
        simpleObject.setId(420L); // Not right, when id is a generated value then no need to set this.
        simpleObject.setKey("Friend");
        simpleObject.setValue("Bani");

        EntityManager entityManager = EntityManagerUtil.getEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(simpleObject);
        entityManager.getTransaction().commit();

        List<SimpleObject> simpleObjectList = entityManager.createNamedQuery("SimpleObject.findAll").getResultList();
        for(SimpleObject simple : simpleObjectList){
            System.out.println(simple);
        }

        entityManager.close();
        
    }
}

我想救它的时候,它把它扔出去了

PersistentObjectException: detached entity passed to persist.

我所需要修复的是删除主方法中simpleObject的id设置行。

我遇到这个问题的另一个原因是事务中存在未经过Hibernate版本控制的实体。

向所有映射实体添加@Version注释

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @Version
    private Integer version;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "orders")
    private CustomerOrders orders;

}
@Entity
public class CustomerOrders {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @Version
    private Integer version;

    private BigDecimal value;

}

此错误来自JPA生命周期。 要解决,不需要使用特定的装饰器。只需要像这样使用merge来连接实体:

entityManager.merge(transaction);

不要忘记正确设置你的getter和setter,这样你的两边都是同步的。

所以我偶然发现了这个问题和答案,因为我得到了相同的错误,但一个非常基本的对象,只有字符串和整数。

但在我的情况下,我试图将一个值设置为一个带@Id注释的字段。

所以,如果你使用@Id,似乎你不能在一个类上创建一个新的对象,并自己设置一个Id,并将其持久化到数据库。然后,您应该将Id留空。我不知道,也许这对其他人有帮助。

这里的问题是缺乏控制。

当我们使用CrudRepository/JPARepository保存方法时,我们失去了事务控制。

为了解决这个问题,我们有了事务管理

我更喜欢@Transactional机制

进口

import javax.transaction.Transactional;

完整源代码:

package com.oracle.dto;

import lombok.*;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

@Entity
@Data
@ToString(exclude = {"employee"})
@EqualsAndHashCode(exclude = {"employee"})
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO,generator = "ps")
    @SequenceGenerator(name = "ps",sequenceName = "project_seq",initialValue = 1000,allocationSize = 1)
    @Setter(AccessLevel.NONE)
    @Column(name = "project_id",updatable = false,nullable = false)
    private Integer pId;
    @Column(name="project_name",nullable = false,updatable = true)
    private String projectName;
    @Column(name="team_size",nullable = true,updatable = true)
    private Integer teamSize;
    @Column(name="start_date")
    private Date startDate;
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name="projectemp_join_table",
        joinColumns = {@JoinColumn(name = "project_id")},
        inverseJoinColumns = {@JoinColumn(name="emp_id")}
    )
    private List<Employee> employees;
}
package com.oracle.dto;

import lombok.*;

import javax.persistence.*;
import java.util.List;

@Entity
@Data
@EqualsAndHashCode(exclude = {"projects"})
@ToString(exclude = {"projects"})
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO,generator = "es")
    @SequenceGenerator(name = "es",sequenceName = "emp_seq",allocationSize = 1,initialValue = 2000)
    @Setter(AccessLevel.NONE)
    @Column(name = "emp_id",nullable = false,updatable = false)
    private Integer eId;
    @Column(name="fist_name")
    private String firstName;
    @Column(name="last_name")
    private String lastName;
    @ManyToMany(mappedBy = "employees")
    private List<Project> projects;
}


package com.oracle.repo;

import com.oracle.dto.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
}

package com.oracle.repo;

import com.oracle.dto.Project;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProjectRepo extends JpaRepository<Project,Integer> {
}

package com.oracle.services;

import com.oracle.dto.Employee;
import com.oracle.dto.Project;
import com.oracle.repo.ProjectRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Component
public class DBServices {
    @Autowired
    private ProjectRepo repo;
    @Transactional
    public void performActivity(){

        Project p1 = new Project();
        p1.setProjectName("Bank 2");
        p1.setTeamSize(20);
        p1.setStartDate(new Date(2020, 12, 22));

        Project p2 = new Project();
        p2.setProjectName("Bank 1");
        p2.setTeamSize(21);
        p2.setStartDate(new Date(2020, 12, 22));

        Project p3 = new Project();
        p3.setProjectName("Customs");
        p3.setTeamSize(11);
        p3.setStartDate(new Date(2010, 11, 20));

        Employee e1 = new Employee();
        e1.setFirstName("Pratik");
        e1.setLastName("Gaurav");

        Employee e2 = new Employee();
        e2.setFirstName("Ankita");
        e2.setLastName("Noopur");

        Employee e3 = new Employee();
        e3.setFirstName("Rudra");
        e3.setLastName("Narayan");

        List<Employee> empList1 = new LinkedList<Employee>();
        empList1.add(e2);
        empList1.add(e3);

        List<Employee> empList2 = new LinkedList<Employee>();
        empList2.add(e1);
        empList2.add(e2);

        List<Project> pl1=new LinkedList<Project>();
        pl1.add(p1);
        pl1.add(p2);

        List<Project> pl2=new LinkedList<Project>();
        pl2.add(p2);pl2.add(p3);

        p1.setEmployees(empList1);
        p2.setEmployees(empList2);

        e1.setProjects(pl1);
        e2.setProjects(pl2);

        repo.save(p1);
        repo.save(p2);
        repo.save(p3);

    }
}