many-to-many

  第一种
就是定义两个实体对应数据库中的两张表,并且再定义一个中间实体对应数据库中的第三张表,用于维护两个实体间的多对多关联关系
1.Student.java

Java代码
package com.template.model;

import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: ZhongGang
* Date: 11-7-20
* Time: 下午9:31
* To change this template use File | Settings | File Templates.
*/
public class Student {
private Integer id;
private String name;

private List<Borrowed> borroweds;

public Student() {
}
}


2.Student.hbm.xml

Xml代码
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-access="field">

<class name="com.template.model.Student" table="student">
<id name="id" column="id" type="java.lang.Integer">
<generator class="native"/>
</id>
<property name="name" column="name" type="java.lang.String"/>

<bag name="borroweds" table="borrowed">
<key column="studentid"/>
<one-to-many class="com.template.model.Borrowed"/>
</bag>
</class>

</hibernate-mapping>

3.Book.java

Java代码
package com.template.model;

import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: ZhongGang
* Date: 11-7-20
* Time: 下午9:31
* To change this template use File | Settings | File Templates.
*/
public class Book {
private Integer id;
private String name;

private List<Borrowed> borroweds;

public Book() {
}
}

4.Book.hbm.xml

Xml代码
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-access="field">

<class name="com.template.model.Book" table="book">
<id name="id" column="id" type="java.lang.Integer">
<generator class="native"/>
</id>
<property name="name" column="name" type="java.lang.String"/>

<bag name="borroweds" table="borrowed">
<key column="bookid"/>
<one-to-many class="com.template.model.Borrowed"/>
</bag>
</class>

</hibernate-mapping>

5.Borrowed.java

Java代码
package com.template.model;

/**
* Created by IntelliJ IDEA.
* User: ZhongGang
* Date: 11-7-20
* Time: 下午9:31
* To change this template use File | Settings | File Templates.
*/
public class Borrowed {
private Integer id;
private Student student;
private Book book;

public Borrowed() {
}
}

你可能感兴趣的:(9)