我试图更好地熟悉 JPA,所以我创建了一个非常简单的项目。我有一个用户类和一个地址类。即使我将 Address 添加到我的 User 类中,我似乎也必须坚持两者?
用户:
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<Address> 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 = Persistence.createEntityManagerFactory("tutorialPU").createEntityManager();
entityManager.getTransaction().begin();
User user = new User();
user.setName("User");
List<Address> addresses = new ArrayList<Address>();
Address address = new Address();
address.setAddress1("Address1");
addresses.add(address);
user.setAddresses(addresses);
entityManager.persist(user);
entityManager.persist(address);
entityManager.getTransaction().commit();
entityManager.close();
可能做错了什么......只是不确定它是什么?
任何建议,将不胜感激。
谢谢,
小号