javax持久化回滚异常

标签 java jpa

我是 JPA 新手,正在尝试一些基本关系。

我有两个实体

 @Entity
@Table(name = "relationshipDepartment")
public class Department implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue()
    private Long id;
    @Version
    @Column(name = "OPTLOCK")
    private long version;
    private String name;
    private String code;
    @OneToOne
    private Employee manager;

    public Department() {
        super();
    }

     getters and setters

    @Entity
@Table(name = "relationshipEmployee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue()
    private Long id;
    @Version
    @Column(name = "OPTLOCK")
    private long version;
    private String name;
    private String title;
    private double salary;
    @ManyToOne
    private Employee supervisor;
    // A employee is a member of one department
    @ManyToOne
    private Department department;

    public long getVersion() {
        return version;
    }
    getters and setters

当我尝试添加一些像这样的实体时;

   public class Starter {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Employee ceo  = new Employee ();
        Employee manager1 = new Employee ();
        Employee manager2 = new Employee ();

        ceo.setName("Bill Clinton");
        ceo.setTitle("CEO");
        ceo.setSalary(3800.0);
        ceo.setSupervisor(ceo);

        manager1.setName("Hilary Clinton");
        manager1.setTitle("Manager");
        manager1.setSalary(3200.0);
        manager1.setSupervisor(ceo);

        manager2.setName("Tim Reyback");
        manager2.setTitle("Manager");
        manager2.setSalary(3200.0);
        manager2.setSupervisor(ceo);

        Department finance = new Department ();
        Department research = new Department ();

        finance.setCode("FIN");
        finance.setName("Finance");

        research.setCode("RES");
        research.setName("Research");

        ceo.setDepartment(finance);
        manager1.setDepartment(finance);
        manager2.setDepartment(research);

        finance.setManager(manager1);
        research.setManager(manager2);

        addEmployee(manager1);
        addEmployee(manager2);

        addDepartement(finance);
        addDepartement(research);

        System.out.println("All the employees");

        List<Employee> employees = retrieveEmployees();
        for (Employee aEmployee : employees) {
            System.out.println(aEmployee.toString());
        }       

        System.out.println("All the departments");

        List<Department> departments = retrieveDepartments();
        for (Department aDepartment : departments) {
            System.out.println(aDepartment.toString());
        }   
    }


    private static void addEmployee(Employee employee) {
        EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("JPAex4");
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(employee);
            em.getTransaction().commit();
        } catch (Exception e) {
            logging.error("erorr at adding a employee"
                    + " :" + e);
        } finally {
            // Close all the connections:
            em.close();
            emf.close();
        }
    }


    private static List<Employee> retrieveEmployees() {
        EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("JPAex4");
        EntityManager em = emf.createEntityManager();
        List<Employee> results = null;
        try {
            // Retrieve all the Employee objects from the database:
            TypedQuery<Employee> query = em.createQuery(
                    "SELECT e FROM Employee e", Employee.class);
            // Creation of the Userlist
            results = query.getResultList();
            return results;
        } catch (Exception e) {
            logging.error("error at the employeelist"
                    + " :" + e);
        } finally {
            // Close all the connections:
            em.close();
            emf.close();
        }
        return results;
    }

    private static void addDepartement(Department department) {
            EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("JPAex4");
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(department);
            em.getTransaction().commit();
        } catch (Exception e) {
            logging.error("error department"
                    + " :" + e);
        } finally {
            // Close all the connections:
            em.close();
            emf.close();
        }
    }


    private static List<Department> retrieveDepartments() {

        EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("JPAex4");
        EntityManager em = emf.createEntityManager();
        List<Department> results = null;
        try {
            // Retrieve all the Employee objects from the database:
            TypedQuery<Department> query = em.createQuery(
                    "SELECT e FROM Department e", Department.class);
            // Creation of the Userlist
            results = query.getResultList();
            return results;
        } catch (Exception e) {
            logging.error("Error departementlist"
                    + " :" + e);
        } finally {
            // Close all the connections:
            em.close();
            emf.close();
        }
        return results;
    }

}

我得到一个:

:javax.persistence.RollbackException:提交事务时出错

at JPA.starter.Starter.main(Starter.java:52) -> first adding line

我没看出有什么问题。有什么建议吗?

谢谢大家

最佳答案

一个问题是,即使对于已经持久化的对象,您也可以调用持久化。当你持久化manager1(通过addEmployee())时,JPA也会持久化finance。因此,您无法在 addDepartment() 中再次保留它。我建议只保留一个用于持久化对象的函数,并在传递根对象后调用此函数。

关于javax持久化回滚异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031858/

相关文章:

java - 如何创建通过延迟加载显示文本日志文件的 JSF 页面

java - 如何获取用户当前登录的帖子的 key

java - 如何使用java将最后修改的文件的内容从一个文件夹复制到另一个文件夹?

java - 如何更改所使用的房间

java - 构造函数 Time 已弃用

java - 使用 QueryDSL JPA 在 MySQL 中查找重复的行

java - "Repeated column in mapping for collection"用于具有相同外键的 hibernate 多对多?

java - hibernate ORM : How to avoid fetching @OneToOne mapped objects?

java - JPA Criteria 查询与 child 不工作的谓词的一对多关系

java - 如何判断2张 table 的情况