下面是User类:
@onetomany
@Entity @Table(name="user") public class User implements Serializable{ private static final long serialVersionUID = 6177417450707400228L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") private int id; @Column(name="name") private String name; @Column(name="password") private String password; /* * cascade:为级联操作,里面有级联保存,级联删除等,all为所有 * fetch:加载类型,有lazy和eager二种, * eager为急加载,意为立即加载,在类加载时就加载,lazy为慢加载,第一次调用的时候再加载,由于数据量太大,onetomany一般为lazy * mappedBy:这个为manytoone中的对象名,这个不要变哦 * Set:这个类型有两种,一种为list另一种为set * * */ @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="user") private Set setRole; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set getSetRole() { return setRole; } public void setSetRole(Set setRole) { this.setRole = setRole; } }
@manytoone
@Entity @Table(name="role") public class Role { private static final long serialVersionUID = 6177417450707400228L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="role_id") private int role_id; @Column(name="role_name") private String role_name; @ManyToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER) @JoinColumn(name="user_id")//加入一列作为外键 private User user; public int getRole_id() { return role_id; } public void setRole_id(int role_id) { this.role_id = role_id; } public String getRole_name() { return role_name; } public void setRole_name(String role_name) { this.role_name = role_name; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
有了这二个注解,我们不需要建表,hibernate会为我们自动建立表以及各种表级联系
其中@table为映射表名,@column为映射列名,其他的我不一一细说了。
下面就是操作了,定义了级联操作,下面是保存的。
public Role save() { User user=new User(); user.setName("123456"); user.setPassword("123456"); Role role=new Role(); role.setRole_name("student"); role.setUser(user); Role roler=registerDao.save(role); return roler; }
时间: 2024-10-09 21:17:51