创建数据库
create database student;
use student;
create table studentInfo(
stuNo integer auto_increment not null primary key,
stuName varchar(50) not null
);
create table courseInfo(
courseNo integer auto_increment not null primary key,
courseName varchar(30) not null
);
create table student_course(
stuNo int,
courseNo int,
foreign key(stuNo) references studentInfo(stuNo),
foreign key(courseNo) references courseInfo(courseNo)
);
show databases;
Pojo
package com.etp.zsh.pojo;
import java.util.HashSet;
import java.util.Set;
public class Courseinfo implements java.io.Serializable {
private Integer courseNo;
private String courseName;
private Set studentinfos = new HashSet(0);
public Courseinfo() {
}
public Courseinfo(String courseName) {
this.courseName = courseName;
}
public Courseinfo(String courseName, Set studentinfos) {
this.courseName = courseName;
this.studentinfos = studentinfos;
}
// Property accessors
public Integer getCourseNo() {
return this.courseNo;
}
public void setCourseNo(Integer courseNo) {
this.courseNo = courseNo;
}
public String getCourseName() {
return this.courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Set getStudentinfos() {
return this.studentinfos;
}
public void setStudentinfos(Set studentinfos) {
this.studentinfos = studentinfos;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.etp.zsh.pojo.Courseinfo" table="courseinfo" catalog="student">
<id name="courseNo" type="java.lang.Integer">
<column name="courseNo" />
<generator class="native" />
</id>
<property name="courseName" type="java.lang.String">
<column name="courseName" length="30" not-null="true" />
</property>
<set name="studentinfos" table="student_course" catalog="student">
<key>
<column name="courseNo" />
</key>
<many-to-many entity-name="com.etp.zsh.pojo.Studentinfo">
<column name="stuNo" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
package com.etp.zsh.pojo;
import java.util.HashSet;
import java.util.Set;
public class Studentinfo implements java.io.Serializable {
// Fields
private Integer stuNo;
private String stuName;
private Set courseinfos = new HashSet(0);
// Constructors
public Studentinfo() {
}
public Studentinfo(String stuName) {
this.stuName = stuName;
}
public Studentinfo(String stuName, Set courseinfos) {
this.stuName = stuName;
this.courseinfos = courseinfos;
}
// Property accessors
public Integer getStuNo() {
return this.stuNo;
}
public void setStuNo(Integer stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return this.stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Set getCourseinfos() {
return this.courseinfos;
}
public void setCourseinfos(Set courseinfos) {
this.courseinfos = courseinfos;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.etp.zsh.pojo.Studentinfo" table="studentinfo"
catalog="student">
<id name="stuNo" type="java.lang.Integer">
<column name="stuNo" />
<generator class="native" />
</id>
<property name="stuName" type="java.lang.String">
<column name="stuName" length="50" not-null="true" />
</property>
<set name="courseinfos" table="student_course" catalog="student">
<key>
<column name="stuNo" />
</key>
<many-to-many entity-name="com.etp.zsh.pojo.Courseinfo">
<column name="courseNo" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
HibernateSessionFactory
package com.etp.zsh.pojo;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory
{
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch (Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory()
{
}
public static Session getSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen())
{
if (sessionFactory == null)
{
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory()
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch (Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null)
{
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void setConfigFile(String configFile)
{
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration()
{
return configuration;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="myeclipse.connection.profile">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/student
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="com/etp/zsh/pojo/Studentinfo.hbm.xml" />
<mapping resource="com/etp/zsh/pojo/Courseinfo.hbm.xml" />
</session-factory>
</hibernate-configuration>
测试类
package com.etp.zsh.pojo;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Test
{
// 实体表中插入数据
public void testManyToMany_1()
{
Studentinfo s1 = new Studentinfo("张三");
Studentinfo s2 = new Studentinfo("李四");
Studentinfo s3 = new Studentinfo("王五");
Courseinfo c1 = new Courseinfo("物理");
Courseinfo c2 = new Courseinfo("数学");
Courseinfo c3 = new Courseinfo("化学");
Session session = null;
Transaction tran = null;
try
{
session = HibernateSessionFactory.getSession();
tran = session.beginTransaction();
session.save(c1);
session.save(c2);
session.save(c3);
session.save(s1);
session.save(s2);
session.save(s3);
tran.commit();
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
tran.rollback();
}
finally
{
HibernateSessionFactory.closeSession();
}
}
// 从Student端维护关系表
public void testManyToManay_2()
{
Session session = null;
Transaction tran = null;
try
{
session = HibernateSessionFactory.getSession();
tran = session.beginTransaction();
Studentinfo st = (Studentinfo) session.get(Studentinfo.class, 1);
Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 2);
st.getCourseinfos().add(cs);
tran.commit();
}
catch (Exception e)
{
e.printStackTrace();
tran.rollback();
}
finally
{
HibernateSessionFactory.closeSession();
}
}
// 从课程端维护
public void testManyToMany_3()
{
Session session = null;
Transaction tran = null;
try
{
session = HibernateSessionFactory.getSession();
tran = session.beginTransaction();
Studentinfo st = (Studentinfo) session.get(Studentinfo.class, 2);
Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 1);
cs.getStudentinfos().add(st);
tran.commit();
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
tran.rollback();
}
finally
{
HibernateSessionFactory.closeSession();
}
}
// 从关系表中删除数据
// 而实体表中不会有变化
public void DeleteFromRelationTable()
{
Session session = null;
Transaction tran = null;
try
{
session = HibernateSessionFactory.getSession();
tran = session.beginTransaction();
// 删除学号为1,课程号为2的关系表中的记录(从学生端维护)
Studentinfo stu = (Studentinfo) session.createQuery
("from Studentinfo s where s.stuNo = 1").uniqueResult();
Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 2);
stu.getCourseinfos().remove(cs);
// 删除学号为1的同学关联表中所有相关记录
Studentinfo s = (Studentinfo) session.createQuery
("from Studentinfo s where s.stuNo = 1").uniqueResult();
s.getCourseinfos().clear();
// 删除课程为2的课程关联表中所有相关记录
Courseinfo c = (Courseinfo) session.get(Courseinfo.class, 2);
c.getStudentinfos().clear();
tran.commit();
}
catch (Exception e)
{
e.printStackTrace();
tran.rollback();
}
finally
{
HibernateSessionFactory.closeSession();
}
}
public static void main(String[] args)
{
Test t = new Test();
// t.testManyToMany_1();
// t.testManyToMany_2();
t.DeleteFromRelationTable();
}
}