如何使用JPA持久保存这些实体而不会出现重复异常

时间:2015-04-13 04:23:19

标签: java jpa eclipselink

请考虑以下事项:

public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private int id;

    @Basic(optional = false)
    @NotNull
    @Column(name = "name")
    private String name;

    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(name="employee_clients_map",
            joinColumns = {@JoinColumn(name = "employee_id")},
            inverseJoinColumns = {@JoinColumn(name = "client_id")})
    private Set<Client> clients;

    public Employee(String name) {
        this.name = name;
    } 
}

-

public class Client {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private int id;

    @Basic(optional = false)
    @NotNull
    @Column(name = "name", unique=true)
    private String name;

    public Client(String name) {
        this.name = name;
    }
}

-

// define employees
Employee e1 = new Employee("Jeff");
Employee e2 = new Employee("Matt");

// define clients
Client c1 = new Client("Company123");
Client c2 = new Client("CompanyABC");

// configure employee - client relationships
Set<Client> e1ClientRelationship = new HashSet<>();
Set<Client> e2ClientRelationship = new HashSet<>();

e1ClientRelationship.add(c1);

e2ClientRelationship.add(c1);
e2ClientRelationship.add(c2);

e1.setClients(e1ClientRelationship);
e2.setClients(e2ClientRelationship);

// persist employees
em.persist(e1);
em.persist(e2);

运行上面的一次会很好。但是说我希望在客户端坚持这样之后将相同的客户端添加到新员工中:

Employee e3 = new Employee("Kim");
Set<Client> e3ClientRelationship = new HashSet<>();
e3ClientRelationship.add(new Client("Company123"));

em.persist(e3);

我会收到此错误:

  

&#34;重复录入&#39; Company123&#39;关键字&#39; name_UNIQUE&#39;&#34;

我尝试使用合并但它不起作用,因为仅为插入生成ID。有哪些方法可以解决这种情况? JPA不适合这种情况吗?

我需要一个能够同时保留大量实体的解决方案 - 我展示的例子显然是做作的。

我也在使用Eclipselink。

1 个答案:

答案 0 :(得分:0)

正如您所说,您希望将相同的客户端添加到新员工中,因此您需要获取现有客户端并添加它:

String sql = "SELECT c FROM Client c WHERE c.name = :name";
TypedQuery<Client> query = EM.createQuery(sql,Client.class);
Client = query.getSingleResult();
Employee e3 = new Employee("Kim");
Set<Client> e3ClientRelationship = new HashSet<>();
e3ClientRelationship.add(client);
EM.persist(e3);

它必须与用于查找和持久的EM相同