`

Hibernate 中的多对多的关系:

阅读更多

作者:shazi.

 

数据库的生成由配置文件自动生成。例子中两个实体类,学生类和教师类。一个学生可以由多个教师,一个教师也可以有多个学生。

主要代码如下:

(一)配置文件:hibernate-cfg.xml

xml 代码
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC   
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  7. <hibernate-configuration>  
  8.   
  9.     <session-factory>  
  10.         <property name="dialect">  
  11.             org.hibernate.dialect.MySQLDialect   
  12.         </property>  
  13.         <property name="connection.url">  
  14.             jdbc:mysql://localhost:3306/good   
  15.         </property>  
  16.         <property name="connection.username">root</property>  
  17.         <property name="connection.password">admin</property>  
  18.         <property name="connection.driver_class">  
  19.             com.mysql.jdbc.Driver   
  20.         </property>  
  21.         <property name="myeclipse.connection.profile">  
  22.             database   
  23.         </property>  
  24.         <property name="show_sql">true</property>  
  25.         <property name="jdbc.fetch_size">50</property>  
  26.         <property name="jdbc.batch_size">25</property>  
  27.         <property name="hbm2ddl.auto">true</property>  
  28.         <mapping resource="mapping/student.hbm.xml" />  
  29.         <mapping resource="mapping/teacher.hbm.xml" />  
  30.     </session-factory>  
  31.   
  32. </hibernate-configuration>  

 

(二)日志文件:log4j.xml

xml 代码
  1. ### direct log messages to stdout ###   
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender   
  3. log4j.appender.stdout.Target=System.out   
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout   
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n   
  6.   
  7. ### direct messages to file hibernate.log ###   
  8. #log4j.appender.file=org.apache.log4j.FileAppender   
  9. #log4j.appender.file.File=hibernate.log   
  10. #log4j.appender.file.layout=org.apache.log4j.PatternLayout   
  11. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n   
  12.   
  13. ### set log levels - for more verbose logging change 'info' to 'debug' ###   
  14.   
  15. log4j.rootLogger=info, stdout   
  16.   
  17. #log4j.logger.org.hibernate=info  
  18. log4j.logger.org.hibernate=info  
  19.   
  20. ### log HQL query parser activity   
  21. #log4j.logger.org.hibernate.hql.ast.AST=debug  
  22.   
  23. ### log just the SQL   
  24. #log4j.logger.org.hibernate.SQL=debug  
  25.   
  26. ### log JDBC bind parameters ###   
  27. log4j.logger.org.hibernate.type=info  
  28. #log4j.logger.org.hibernate.type=debug  
  29.   
  30. ### log schema export/update ###   
  31. log4j.logger.org.hibernate.tool.hbm2ddl=debug  
  32.   
  33. ### log HQL parse trees   
  34. #log4j.logger.org.hibernate.hql=debug  
  35.   
  36. ### log cache activity ###   
  37. #log4j.logger.org.hibernate.cache=debug  
  38.   
  39. ### log transaction activity   
  40. #log4j.logger.org.hibernate.transaction=debug  
  41.   
  42. ### log JDBC resource acquisition   
  43. #log4j.logger.org.hibernate.jdbc=debug  
  44.   
  45. ### enable the following line if you want to track down connection ###   
  46. ### leakages when using DriverManagerConnectionProvider ###   
  47. #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace  

 

(三)HibernateSessionFactory.java文件,主要是SessionFactory的创建和Session的创建。

java 代码
  1. package dao;   
  2.   
  3. import org.hibernate.HibernateException;   
  4. import org.hibernate.Session;   
  5. import org.hibernate.cfg.Configuration;   
  6.   
  7. /**  
  8.  * Configures and provides access to Hibernate sessions, tied to the  
  9.  * current thread of execution.  Follows the Thread Local Session  
  10.  * pattern, see {@link http://hibernate.org/42.html }.  
  11.  */  
  12. public class HibernateSessionFactory {   
  13.   
  14.     /**   
  15.      * Location of hibernate.cfg.xml file.  
  16.      * Location should be on the classpath as Hibernate uses    
  17.      * #resourceAsStream style lookup for its configuration file.   
  18.      * The default classpath location of the hibernate config file is   
  19.      * in the default package. Use #setConfigFile() to update   
  20.      * the location of the configuration file for the current session.     
  21.      */  
  22.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";   
  23.     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();   
  24.     private  static Configuration configuration = new Configuration();   
  25.     private static org.hibernate.SessionFactory sessionFactory;   
  26.     private static String configFile = CONFIG_FILE_LOCATION;   
  27.   
  28.     private HibernateSessionFactory() {   
  29.     }   
  30.        
  31.     /**  
  32.      * Returns the ThreadLocal Session instance.  Lazy initialize  
  33.      * the <code>SessionFactory</code> if needed.  
  34.      *  
  35.      *  @return Session  
  36.      *  @throws HibernateException  
  37.      */  
  38.     public static Session getSession() throws HibernateException {   
  39.         Session session = (Session) threadLocal.get();   
  40.   
  41.         if (session == null || !session.isOpen()) {   
  42.             if (sessionFactory == null) {   
  43.                 rebuildSessionFactory();   
  44.             }   
  45.             session = (sessionFactory != null) ? sessionFactory.openSession()   
  46.                     : null;   
  47.             threadLocal.set(session);   
  48.         }   
  49.   
  50.         return session;   
  51.     }   
  52.   
  53.     /**  
  54.      *  Rebuild hibernate session factory  
  55.      *  
  56.      */  
  57.     public static void rebuildSessionFactory() {   
  58.         try {   
  59.             configuration.configure(configFile);   
  60.             sessionFactory = configuration.buildSessionFactory();   
  61.         } catch (Exception e) {   
  62.             System.err   
  63.                     .println("%%%% Error Creating SessionFactory %%%%");   
  64.             e.printStackTrace();   
  65.         }   
  66.     }   
  67.   
  68.     /**  
  69.      *  Close the single hibernate session instance.  
  70.      *  
  71.      *  @throws HibernateException  
  72.      */  
  73.     public static void closeSession() throws HibernateException {   
  74.         Session session = (Session) threadLocal.get();   
  75.         threadLocal.set(null);   
  76.   
  77.         if (session != null) {   
  78.             session.close();   
  79.         }   
  80.     }   
  81.   
  82.     /**  
  83.      *  return session factory  
  84.      *  
  85.      */  
  86.     public static org.hibernate.SessionFactory getSessionFactory() {   
  87.         return sessionFactory;   
  88.     }   
  89.   
  90.     /**  
  91.      *  return session factory  
  92.      *  
  93.      *  session factory will be rebuilded in the next call  
  94.      */  
  95.     public static void setConfigFile(String configFile) {   
  96.         HibernateSessionFactory.configFile = configFile;   
  97.         sessionFactory = null;   
  98.     }   
  99.   
  100.     /**  
  101.      *  return hibernate configuration  
  102.      *  
  103.      */  
  104.     public static Configuration getConfiguration() {   
  105.         return configuration;   
  106.     }   
  107.   
  108. }  

 

(四) 创建Student.java,POJO类。

java 代码
  1. package mapping;   
  2.   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5.   
  6. public class Student implements java.io.Serializable{   
  7.     private Integer id;   
  8.     private String name;   
  9.     private Set teacher=new HashSet();   
  10.     public Integer getId() {   
  11.         return id;   
  12.     }   
  13.     public void setId(Integer id) {   
  14.         this.id = id;   
  15.     }   
  16.        
  17.     public Set getTeacher() {   
  18.         return teacher;   
  19.     }   
  20.     public void setTeacher(Set teacher) {   
  21.         this.teacher = teacher;   
  22.     }   
  23.     public String getName() {   
  24.         return name;   
  25.     }   
  26.     public void setName(String name) {   
  27.         this.name = name;   
  28.     }   
  29. }   

 

(五)student.hbm.xml

xml 代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse - Hibernate Tools  
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="mapping.Student" table="student">  
  9.         <id name="id" type="integer">  
  10.             <column name="ID" />  
  11.             <generator class="identity"></generator>  
  12.         </id>  
  13.         <property name="name" type="string">  
  14.             <column name="name" length="100" />  
  15.         </property>  
  16.           <set name="teacher" inverse="true" cascade="save-update" table="student_teacher">  
  17.             <key column="s_id" not-null="false">  
  18.             </key>  
  19.             <many-to-many class="mapping.Teacher" column="t_id" outer-join="true" />  
  20.         </set>  
  21.     </class>  
  22. </hibernate-mapping>  

 

(六)Teacher.java

java 代码
  1. package mapping;   
  2.   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5.   
  6.   
  7. /**  
  8.  * Teacher generated by MyEclipse - Hibernate Tools  
  9.  */  
  10.   
  11. public class Teacher extends mapping.Student implements java.io.Serializable {   
  12.   
  13.   
  14.     // Fields       
  15.   
  16.      private Integer id;   
  17.      private String name;   
  18.      private Set students = new HashSet(0);   
  19.   
  20.   
  21.     // Constructors   
  22.   
  23.     /** default constructor */  
  24.     public Teacher() {   
  25.     }   
  26.   
  27.        
  28.     /** full constructor */  
  29.     public Teacher(String name, Set students) {   
  30.         this.name = name;   
  31.         this.students = students;   
  32.     }   
  33.   
  34.       
  35.     // Property accessors   
  36.   
  37.     public Integer getId() {   
  38.         return this.id;   
  39.     }   
  40.        
  41.     public void setId(Integer id) {   
  42.         this.id = id;   
  43.     }   
  44.   
  45.     public String getName() {   
  46.         return this.name;   
  47.     }   
  48.        
  49.     public void setName(String name) {   
  50.         this.name = name;   
  51.     }   
  52.   
  53.     public Set getStudents() {   
  54.         return this.students;   
  55.     }   
  56.        
  57.     public void setStudents(Set students) {   
  58.         this.students = students;   
  59.     }   
  60.       
  61.   
  62.   
  63. }  

 

(七)teacher.bhm.xml

xml 代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse - Hibernate Tools  
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="mapping.Teacher" table="teacher">  
  9.         <id name="id" type="integer">  
  10.             <column name="id" />  
  11.             <generator class="native"></generator>  
  12.         </id>  
  13.         <property name="name" type="string">  
  14.             <column name="name" length="100" />  
  15.         </property>  
  16.            
  17.         <set name="students"  cascade="save-update"   table="student_teacher">  
  18.             <key column="t_id" not-null="false">  
  19.             </key>  
  20.             <many-to-many class="mapping.Student" column="s_id" outer-join="true"/>  
  21.         </set>  
  22.           
  23.     </class>  
  24. </hibernate-mapping>  

 

(八)测试类:Test.java,使用SchemaExport schemaExport = new SchemaExport(config);生成数据库代码。

java 代码
  1. package dao;   
  2.   
  3. import mapping.Student;   
  4. import mapping.Teacher;   
  5.   
  6. import org.hibernate.Session;   
  7. import org.hibernate.Transaction;   
  8. import org.hibernate.tool.hbm2ddl.SchemaExport;   
  9.   
  10. public class Test {   
  11.   
  12.     /**  
  13.      * @param args  
  14.      */  
  15.     public static void main(String[] args) {   
  16.         org.hibernate.cfg.Configuration config=new org.hibernate.cfg.Configuration().configure();   
  17.         System.out.println("Creating tables...");   
  18.         SchemaExport schemaExport = new SchemaExport(config);   
  19.         schemaExport.create(truetrue);   
  20.         System.out.println("Table created.");   
  21.         Student s = new Student();   
  22.         s.setName("rose");   
  23.         Teacher t = new Teacher();   
  24.         t.setName("admin");   
  25.         s.getTeacher().add(t);   
  26.         t.getStudents().add(s);   
  27.        
  28.         Session session = HibernateSessionFactory.getSession();   
  29.         Transaction tx = session.beginTransaction();   
  30.         session.save(t);   
  31.         session.save(s);   
  32.         tx.commit();   
  33.         session.close();   
  34.          
  35.     }    
  36.        
  37.   
  38. }   

运行即可:

 

分享到:
评论
1 楼 meadlai 2008-11-02  
student_teacher表中有外键吧?
这个表应该有xml配置吧?

相关推荐

Global site tag (gtag.js) - Google Analytics