1, User table users and coupons coupon There are many-to-many relationships, a user can have multiple coupons, a coupon can belong to multiple users.
2, User.java, created the intermediate table Tb_user_coupon
(1) jointable indicates that the intermediate table
(2)
/** * One user can have multiple coupons but coupons have only their own attributes, no user references single-sided one-to- Many relationships * /= fetchtype.eager, Cascade = {cascadetype.persist}) = "Tb_user_coupon", Joincolumns = @JoinColumn (name = "User_ID", referencedcolumnname = "id"), Inversejoincolumns = @JoinCo Lumn (name = "coupon_id", referencedcolumnname = "id")) // Fetch configuration load mode (delayed or instant) // CASCADE configuration cascade means that the user class is automatically saved, deleted, modified, and refreshed in the database. list<coupon> coupons =new arraylist<coupon> ();
3, Coupon.java
(1) Since the mapping of the database table has been configured in user, Mappedby specifies the variable name coupon inside the user class
@ManyToMany (mappedby= "coupons")private set<user> users=new hashset<post> () ;
4. Add a field to the intermediate table
Note Several configurations of the third table
(1) The table name should be consistent with @jointable
(2) The name of two @jointable is consistent, otherwise it will produce other fields
Done
@Entity @table (name= "Tb_user_coupon") Public classusercoupon {@Id @GeneratedValue (strategy=Generationtype.auto)PrivateInteger ID; @ManyToOne @JoinColumn (Name= "user_id", nullable=false) Privateuser User; @ManyToOne @JoinColumn (Name= "coupon_id", nullable=false) PrivateCoupon Coupon; @Column (Updatable=false, nullable =false, columndefinition = "timestamp default current_timestamp on UPDATE current_timestamp") @Temporal (temporaltype.timestamp)PrivateDate CreatedDate =NewDate ();}
Done