<!-- Database connection settings -->
<property>
Oracle.jdbc.OracleDriver
</property>
<property>
jdbc:oracle:thin:@localhost:1521:orcl
</property>
<property>happy</property>
<property>1</property>
<!-- SQL dialect 方言-->
<property>
org.hibernate.dialect.Oracle10gDialect
</property>
<!-- Disable the second-level cache 二级缓存-->
<!--<property>org.hibernate.cache.NoCacheProvider</property>-->
<!-- Echo all executed SQL to stdout 是否在控制台显示sql语句-->
<property>true</property>
<!-- 格式化显示SQL -->
<property>true</property>
<!-- Drop and re-create the database schema on startup -->
<property>create</property>
<!-- 关联小配置 -->
<mapping resource="cn/manytomany/doubleanother/emploees.hbm.xml" />
<mapping resource="cn/manytomany/doubleanother/projects.hbm.xml" />
</session-factory>
</hibernate-configuration>
3.最后就是测试类了
package cn.manytomany.one;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class ManyToManyDoubleTest {
/**
* 多对多的双向关联测试
*/
public static void main(String[] args) {
Session session = HibernateUtil.currentSession();
Transaction tsc = session.beginTransaction();
//创建雇员
Emploee emp=new Emploee();
emp.setEmpName("田超");
Emploee emp1=new Emploee();
emp1.setEmpName("施强");
//创建工程
Project pro=new Project();
pro.setProName("开发工程");
pro.getEmploees().add(emp);
pro.getEmploees().add(emp1);
try {
session.save(pro);
tsc.commit();
} catch (Exception e) {
// 回滚
tsc.rollback();
}
HibernateUtil.closeSession();
}
}
3.1 最后补充一下工具类,看看就行
package cn.manytomany.one;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
/*
* session工具类
*/
public class HibernateUtil {
private static final ThreadLocal<Session> sessionTL=new ThreadLocal<Session>();
private static Configuration cfg;
private static final SessionFactory sf;
static{
try {
cfg=new Configuration().configure();
sf = cfg.buildSessionFactory();
} catch (Exception e) {
//异常
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public static Session currentSession(){
Session session=sessionTL.get();
//如果session为null,则打开一个新的session
if (session==null) {
session=sf.openSession();
sessionTL.set(session);
}
return session;
}
public static void closeSession(){
Session session=sessionTL.get();
sessionTL.set(null);
session.close();
}
}
二、创建一个中间的实体类来关联
1.跟第一个方案差不多,先实现三个实体类,代码如下:
package cn.manytomany.doubleanother;
import java.util.HashSet;
import java.util.Set;