我是一个休眠和 EJB 初学者。我有这个简单的 ORM:
用户 -> 属于 -> 组
我习惯于在其他语言中执行以下操作来创建属于同一组的多个新用户:
Group g = new Group();
groupsManager.create(g);
User u1 = new User("Tom");
User u1 = new User("Jerry");
u1.setGroup(g);
u2.setGroup(g);
usersManager.create(u1);
usersManager.create(u2);
正在创建记录,但不是每个用户都属于同一个组,而是我最终拥有 3 个组。
这些是两个实体类:
@Entity
@Table(name="Users")
public class User extends AbstractEntity implements Serializable {
private static final long serialVersionUID = 1L;
public User() {
super();
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
//*** Some other Fields
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name="group_id")
private Group group;
//*** Setter and Getters
}
和集团:
@Entity
@Table(name="Groups")
public class Group extends AbstractEntity implements Serializable {
private static final long serialVersionUID = 1L;
public Group() {
super();
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@OneToMany(cascade = CascadeType.ALL)
private Set<User> users;
}