日期:2014-05-19  浏览次数:20855 次

MyEclipse中如何使用Hibernate配置多对多映射
一般使用MyEclipse+Hibernate的模式有两种,一种是先在数据库写SQL,然后用MyEclipse生成XML和JAVA类,第二种方法是在MyEclipse中写好XML和JAVA类后,用Hibernate自动生成表,这两种方法哪种比较好.

我使用的前者,因为我希望我能把握数据库的一切,毕竟数据库非常重要,但是我的同事一直用的后者,他说Hibernate的本意就是减轻开发者对数据库的工作量,而采用完全面向对象的思想.

这几天碰到一个问题,就是hibernate的多对多问题,我先写SQL,在数据库中建好两张表的关系表以实现多对多关系,却不知道如何在MyEclipse中配置好这样的映射关系,因为用MyEclipse的生成工具是将每一张表生成JAVA和XML的,而关系表并不能这么做,并不需要建立关系表的XML和JAVA,而是在两张实体表中的XML中配置many-to-many.朋友的做法轻而易举,他先写JAVA和XML,配置好以后自动生成了中间表,虽然他对SQL不管不问,甚至不知道数据库的结构,可是多对多的关系确实建立起来了.

最后,各位兄弟朋友,能否告诉我,如何在MyEclipse中配置好两张表的多对多关系,这两张表的关系表我已经在数据库中建好了,一对一和一对多的关系我都是右击MyEclipse的DB Browser中的table然后选Hibernate工具生成的.我的MyEclipse版本是7.1

------解决方案--------------------
自己手写就是了
------解决方案--------------------
可以自动生成啊·
 但是你要选择双向映射,一般会生成2个一对多代替多对多
------解决方案--------------------
程序HibernateSessionFactory.java

package com;

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;

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;
 }

}

程序BaseHibernateDAO.java

package com;

import org.hibernate.Session;

public class BaseHibernateDAO {

 public Session getSession() {
return HibernateSessionFactory.getSession();
 }

 public void closeSession(){
HibernateSessionFactory.closeSession();
 }
}


------解决方案--------------------
官方推荐的是第二种。
------解决方案--------------------
建议在数据库再建一个表,把1个多对多关系转换为2个一对多关系。再用第一种方法就可以了!