1、现在有优惠券Coupon表,用户User表和一张希望可以保存用户对优惠券是否使用信息的表
User.class
package com.life.hibernate.bean; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; /** * @author JL * 用户类 */ @Entity // 实体类配置 @Table(name="tb_user") // 表格配置 public class User { @Id //在表中的名称 @GeneratedValue(strategy=GenerationType.AUTO) //自动增长 private Integer id; /** * 一个用户可以用友多个优惠券 但优惠券只有自己的属性,没有用户的引用 单边的一对多关系 */ @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST }) @JoinTable(name = "tb_user_coupon", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "coupon_id", referencedColumnName = "id")) // fetch配置加载方式(延迟或即时) // cascade配置级联方式,表示在增删查改user类时,会自动在数据库中保存、删除、修改、刷新属于他的Email对象 private List<Coupon> coupons = new ArrayList<Coupon>(); //get-set方法略 }
Coupon.class
package com.life.hibernate.bean; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "tb_coupon") public class Coupon extends BaseBean { @Id //在表中的名称 @GeneratedValue(strategy=GenerationType.AUTO) //自动增长 private Integer id; /** * 优惠券名称 */ private String name; @ManyToMany(mappedBy="coupons") private List<User> users=new ArrayList<User>(); //get/set省略 }
2、在第三张表tb_user_coupon加一个字段布尔used
package com.life.hibernate.bean; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "tb_user_coupon") public class UserCoupon { @Id //在表中的名称 @GeneratedValue(strategy=GenerationType.AUTO) //自动增长 private Integer id; private Boolean used = false; @ManyToOne @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "coupon_id") private Coupon coupon; }
3、注意第三张表的几点配置
(1)表名要与@JoinTable一致
(2)两个@JoinTable的name分别保持一致,不然会产生其他的字段
Done