如何在新实体中将现有对象合并为@OneToMany关系?

时间:2015-08-18 09:33:01

标签: java spring hibernate

是否可以更新现有的@OneToMany实体而不提取它? (合并)在父实体的上下文中?

@Entity
public class Person {
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="fk_address_id", foreignKey = @ForeignKey(name="fk_addres"))
    private Address address;
}


@Entity
public class Address {
    @Id
    private Long id; //asume I can control the id

    private String city;
    private int zip;
    private String street;

    @OneToMany(mappedBy = "address")
    private Set<Person> persons;
}

在DB中存在id=12的地址。

现在我正在尝试将此地址分配给new Person(),但不从DB中获取地址实体。是address是否有可能通过hibernate在人的上下文中合并?

@Transactional
public void create() {
    Person person = new Person();
    Address address = new Address();
    address.setId(12); //exists in DB
    address.setCity("test");
    person.setAddress(address);
    dao.merge(person);
}

结果:SQL Error: 0, SQLState: 23505 - UniqueConstraintViolation - duplicate key "12" in address

1 个答案:

答案 0 :(得分:1)

如果你想用12作为id的地址,你必须从数据库中获取它然后分配它...

@Transactional
public void create() {
    Person person = new Person();
    Address address = dao.getAddressByID(12);
    person.setAddress(address);
    dao.merge(person);
}

其他,您要创建一个具有相同ID的新地址,因此您无法按照问题中的说明进行操作...