问题描述
我用注解生成了3张表,DepartmentPersonnel还有一张中间表personnel_department我应该怎么保存信息呢?
解决方案
解决方案二:
@Entity@Table(name="department")publicclassDepartment{privateintid;privateStringdepartname;privateSet<Personnel>set=newHashSet<Personnel>();//privatePersonnelpersonnel;@Id@GeneratedValue@Column(name="ID")publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}@Column(name="DEPARTNAME")publicStringgetDepartname(){returndepartname;}publicvoidsetDepartname(Stringdepartname){this.departname=departname;}@OneToMany@JoinTable(name="personnel_department",joinColumns={@JoinColumn(name="department_id",referencedColumnName="id")},inverseJoinColumns={@JoinColumn(name="personnel_id",referencedColumnName="id")})//name的值为要建的一张中间表,其中有表department名称加上“_”再加上表personnel名称组成,后边第一个name对应的是中间表列名,对应第一张表的id//第二个name也是中间表的另一个列名,对应第二张表的idpublicSet<Personnel>getSet(){returnset;}publicvoidsetSet(Set<Personnel>set){this.set=set;}}@Entity@Table(name="personnel")publicclassPersonnel{privateintid;privateStringname;//privateSet<Department>set=newHashSet<Department>();privateDepartmentdepartment;@Id@GeneratedValue@Column(name="ID")publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}@Column(name="P_NAME",length=50)publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}@ManyToOne@JoinTable(name="personnel_department",joinColumns={@JoinColumn(name="personnel_id",referencedColumnName="id")},inverseJoinColumns={@JoinColumn(name="department_id",referencedColumnName="id")})publicDepartmentgetDepartment(){returndepartment;}publicvoidsetDepartment(Departmentdepartment){this.department=department;}}@RepositorypublicclassUserDaoImplimplementsUserDao{@ResourceprivateSessionFactorysessionFactory;publicvoidsetSessionFactory(SessionFactorysessionFactory){this.sessionFactory=sessionFactory;}privateSessionsession;publicSessiongetSession(){returnsession=this.sessionFactory.getCurrentSession();}@OverridepublicvoidaddUser(Useruser){}@OverridepublicvoidaddPersonnel(Personnelpersonnel){this.getSession().save(personnel);this.getSession().save(personnel.getDepartment());}@OverridepublicvoidaddDepartment(Departmentdepartment){this.sessionFactory.getCurrentSession().saveOrUpdate(department);}
解决方案三:
解决方案四:
如果有中间表的情况请使用ManyToMany的注解方式;参考以下用户与权限关联:User.java@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)@JoinTable(name="tr_user_privilege",joinColumns=@JoinColumn(name="user_id"),inverseJoinColumns=@JoinColumn(name="privilege_id"))@OrderBy("privilege_idASC")privateList<Privilege>privileges;