如果Address嵌套在User中,为什么我必须保留两个对象?
我想更好地熟悉JPA,所以我创建了一个非常简单的项目。 我有一个User Class和一个Address类。 看来我必须坚持两个,即使我正在为我的用户类添加地址?
用户:
import javax.persistence.*; import java.util.HashSet; import java.util.List; import java.util.Set; @Entity @Table(name = "usr") // @Table is optional, but "user" is a keyword in many SQL variants @NamedQuery(name = "User.findByName", query = "select u from User u where u.name = :name") public class User { @Id // @Id indicates that this it a unique primary key @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server private Long id; @Column(length = 32, unique = true) // the optional @Column allows us makes sure that the name is limited to a suitable size and is unique private String name; // note that no setter for ID is provided, Hibernate will generate the ID for us @OneToMany(fetch=FetchType.LAZY, mappedBy="user") private List addresses;
地址:
@Entity public class Address { @Id // @Id indicates that this it a unique primary key @GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server private Long id; @Column(length=50) private String address1; @ManyToOne @JoinColumn(name="user_id") private User user;
EntityManager的:
EntityManager entityManager = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager(); entityManager.getTransaction().begin(); User user = new User(); user.setName("User"); List addresses = new ArrayList(); Address address = new Address(); address.setAddress1("Address1"); addresses.add(address); user.setAddresses(addresses); entityManager.persist(user); entityManager.persist(address); entityManager.getTransaction().commit(); entityManager.close();
可能做错了什么……只是不确定它是什么?
任何建议,将不胜感激。
谢谢,
小号
尝试注释的cascade
元素。
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade=CascadeType.PERSIST) private List addresses;
文档说默认情况下没有级联操作。 它还声明级联操作是可选的,因此它实际上取决于您正在使用的实现。
此外,在设置关系时,请确保设置关系的两侧。 将地址设置为用户,将用户设置为地址。
你在说什么叫做Cascading。 这意味着对嵌套对象执行相同的操作,例如User
的Address
。 默认情况下,如果未指定任何CascadeType
,则根本没有级联。
您可以一次定义各种级联类型
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) private List addresses;
或者告诉JPA级联每个操作:
@OneToMany(fetch=FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL) private List addresses;
例如,在删除User
时,两种方式都会导致User
持久保留Address
或删除相关Address
。
但是!…如果从第一个示例中删除CascadeType.REMOVE
,删除User
将不会删除其关联的Address
(删除操作不会应用于嵌套对象)。
您正在使用oneToMany注释。 根据我的理解,当你想要为它添加子类(地址)时,你必须坚持父类(USer)。
通过持久化User类,您可以让JPA知道要更新的行。