Почему я должен сохранять оба объекта, если Address вложен в User?
Я пытаюсь лучше ознакомиться с JPA, поэтому я создал очень простой проект. У меня есть класс пользователя и класс адреса. Похоже, что я должен сохранить оба, даже если я добавляю адрес в мой класс пользователя?
Пользователь:
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();
Возможно, что-то не так ... просто не уверен, что это такое?
Мы ценим любые предложения.
Спасибо, S