多_对_多

//Hibernate--多对多
--学生表
create table Studentv(
id number primary key,
stuId varchar2(20) not null,
stuName varchar2(50) not null,
stuAge number not null
);
--课程表
create table Coursev(
id number primary key,
couId varchar2(20) not null,
couName varchar2(50) not null
);
--中间表
create table Stu_Couv(
sId number not null,
cId number not null
);

//课程表实体类
public class Coursev implements Serializable
{
    private int id;
    private String cId;
    private String cName;
    private Set<Studentv> stus = new HashSet<Studentv>();
//省略get(),set();
}
//学生实体类
public class Studentv implements Serializable
{
    private int id;
    private String sId;
    private String sName;
    private int sAge;
    private Set<Coursev> cous = new HashSet<Coursev>();
//省略get(),set();
}

//Coursev.hbm.xml
<hibernate-mapping package="com.rt.xbliuc.pojo">
<class name="Coursev" table="Coursev">
<id name="id" column="id">
<generator class="assigned"/>
</id>
<property name="cId" column="couId"/>
<property name="cName" column="couName"/>
<set name="stus" table="Stu_Couv" lazy="true" cascade="all">
<key column="cId"/>
<many-to-many class="com.rt.xbliuc.pojo.Studentv" column="sId"/>
</set>
</class>
</hibernate-mapping>

//Studentv.hbm.xml
<hibernate-mapping package="com.rt.xbliuc.pojo">
<class name="Studentv" table="Studentv">
<id name="id" column="id">
<generator class="assigned"/>
</id>
<property name="sId" column="stuId"/>
<property name="sName" column="stuName"/>
<property name="sAge" column="stuAge"/>
<set name="cous" inverse="true" table="Stu_Couv" lazy="true" cascade="all">
<key column="sId"/>
<many-to-many class="com.rt.xbliuc.pojo.Coursev" column="cId"/>
</set>
</class>
</hibernate-mapping>

//测试类
Transaction transaction = session.beginTransaction();
HashSet<Studentv> cSet = new HashSet<Studentv>();
HashSet<Coursev> sSet = new HashSet<Coursev>();
Studentv s = new Studentv();
Coursev c = new Coursev();
s.setId(1);
s.setsId("s001");
s.setsName("sName");
s.setsAge(20);
c.setId(2);
c.setcId("c001");
c.setcName("cName");
cSet.add(s);
sSet.add(c);
c.setStus(cSet);
s.setCous(sSet);
session.save(s);
transaction.commit();
session.close();

你可能感兴趣的:(多_对_多)