阿O、不拽

导航

hibernate 注解和xml配置入门

下面使用学生-课程为例:

 

首先是使用注解的方式:

 

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.entity;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import javax.persistence.CascadeType;  
  6. import javax.persistence.Column;  
  7. import javax.persistence.Entity;  
  8. import javax.persistence.GeneratedValue;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.JoinTable;  
  12. import javax.persistence.ManyToMany;  
  13. @Entity  
  14. public class Student {  
  15.       
  16.     private int id;  
  17.     private String name;  
  18.     private Set<Course> courses = new HashSet<Course>();  
  19.     @Id  
  20.     @GeneratedValue  
  21.     @Column(name="id")  
  22.     public int getId() {  
  23.         return id;  
  24.     }  
  25.     public void setId(int id) {  
  26.         this.id = id;  
  27.     }  
  28.     @Column(name="name")  
  29.     public String getName() {  
  30.         return name;  
  31.     }  
  32.     public void setName(String name) {  
  33.         this.name = name;  
  34.     }  
  35.     @ManyToMany  
  36.     @JoinTable(name="student_course",  
  37.             joinColumns=@JoinColumn(name="student_Id"),  
  38.             inverseJoinColumns=@JoinColumn(name="course_Id"))  
  39.     public Set<Course> getCourses() {  
  40.         return courses;  
  41.     }  
  42.     public void setCourses(Set<Course> courses) {  
  43.         this.courses = courses;  
  44.     }  
  45.   
  46.   
  47. }  

 

 

 

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.entity;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.JoinColumn;  
  11. import javax.persistence.JoinTable;  
  12. import javax.persistence.ManyToMany;  
  13. @Entity  
  14. public class Course {  
  15.       
  16.     private int id;  
  17.     private String name;  
  18.     private Set<Student> students  = new HashSet<Student>();  
  19.     @Id  
  20.     @GeneratedValue  
  21.     @Column(name="id")  
  22.     public int getId() {  
  23.         return id;  
  24.     }  
  25.     public void setId(int id) {  
  26.         this.id = id;  
  27.     }  
  28.     @Column(name="name")  
  29.     public String getName() {  
  30.         return name;  
  31.     }  
  32.     public void setName(String name) {  
  33.         this.name = name;  
  34.     }  
  35.     @ManyToMany(mappedBy="courses")  
  36.     public Set<Student> getStudents() {  
  37.         return students;  
  38.     }  
  39.     public void setStudents(Set<Student> students) {  
  40.         this.students = students;  
  41.     }  
  42.   
  43. }  

 

 

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://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.   
  10.         <!-- Database connection settings -->  
  11.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  12.         <property name="connection.url">jdbc:mysql://localhost:3306/test</property>  
  13.         <property name="connection.username">root</property>  
  14.         <property name="connection.password">root</property>  
  15.   
  16.         <!-- JDBC connection pool (use the built-in) -->  
  17.         <!--<property name="connection.pool_size">1</property>-->  
  18.   
  19.         <!-- SQL dialect -->  
  20.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  21.   
  22.         <!-- Enable Hibernate's automatic session context management -->  
  23.         <property name="current_session_context_class">thread</property>  
  24.   
  25.         <!-- Disable the second-level cache  -->  
  26.         <!--<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->  
  27.   
  28.         <!-- Echo all executed SQL to stdout -->  
  29.         <property name="show_sql">true</property>  
  30.           
  31.         <!-- format_sql -->  
  32.         <property name="format_sql">true</property>  
  33.   
  34.         <!-- Drop and re-create the database schema on startup -->  
  35.         <property name="hbm2ddl.auto">update</property>  
  36.   
  37.         <mapping class="com.tch.test.hibernate.entity.Course"/>  
  38.         <mapping class="com.tch.test.hibernate.entity.Student"/>  
  39.   
  40.     </session-factory>  
  41.   
  42. </hibernate-configuration>  

 

 

 

log4j.properties(查看事务的日志信息):

 

 

Properties代码  收藏代码
  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=warn, stdout  
  16.   
  17. ### 查看事务的日志信息  
  18. log4j.logger.org.hibernate.transaction=debug  
  19.   
  20. #log4j.logger.org.hibernate=info  
  21. log4j.logger.org.hibernate=info  
  22.   
  23. ### log HQL query parser activity  
  24. #log4j.logger.org.hibernate.hql.ast.AST=debug  
  25.   
  26. ### log just the SQL  
  27. #log4j.logger.org.hibernate.SQL=debug  
  28.   
  29. ### log JDBC bind parameters ###  
  30. #log4j.logger.org.hibernate.type=info  
  31. #log4j.logger.org.hibernate.type=debug  
  32.   
  33. ### log schema export/update ###  
  34. #log4j.logger.org.hibernate.tool.hbm2ddl=debug  
  35.   
  36. ### log HQL parse trees  
  37. #log4j.logger.org.hibernate.hql=debug  
  38.   
  39. ### log cache activity ###  
  40. #log4j.logger.org.hibernate.cache=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  

 

 

工具类:

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.util;  
  2. import org.hibernate.SessionFactory;  
  3. import org.hibernate.cfg.AnnotationConfiguration;  
  4.   
  5. public class HibernateUtil {  
  6.   
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();  
  8.   
  9.     private static SessionFactory buildSessionFactory() {  
  10.         try {  
  11.             //注解的时候使用AnnotationConfiguration  
  12.             return new AnnotationConfiguration().configure().buildSessionFactory();  
  13.         }  
  14.         catch (Throwable ex) {  
  15.             System.err.println("Initial SessionFactory creation failed." + ex);  
  16.             throw new ExceptionInInitializerError(ex);  
  17.         }  
  18.     }  
  19.   
  20.     public static SessionFactory getSessionFactory() {  
  21.         return sessionFactory;  
  22.     }  
  23.   
  24. }  

 

 

测试类:

 

 

Java代码  收藏代码
  1. public class Test {  
  2.       
  3.     @org.junit.Test  
  4.     public void test1(){  
  5.         Student student = new Student();  
  6.         student.setName("张三");  
  7.         Student student2 = new Student();  
  8.         student2.setName("李四");  
  9.           
  10.         Course course = new Course();  
  11.         course.setName("数学");  
  12.         Course course2 = new Course();  
  13.         course2.setName("英语");  
  14.           
  15.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
  16.         Session session = sessionFactory.getCurrentSession();  
  17.         try {  
  18.             session.beginTransaction();  
  19.             session.save(student);  
  20.             session.save(student2);  
  21.             session.save(course);  
  22.             session.save(course2);  
  23.             student.getCourses().add(course);  
  24.             session.getTransaction().commit();  
  25.         } catch (HibernateException e) {  
  26.             e.printStackTrace();  
  27.             session.getTransaction().rollback();  
  28.         }finally{  
  29.             sessionFactory.close();  
  30.         }  
  31.     }  
  32. }  

 

 

最后就会发现中间表里面加入了记录,说明操作成功。

 

 

下面是xml配置方式:

 

实体类:

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.entity;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6.   
  7. public class Student {  
  8.       
  9.     private int id;  
  10.     private String name;  
  11.     private Set<Course> courses = new HashSet<Course>();  
  12.   
  13.     public int getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(int id) {  
  17.         this.id = id;  
  18.     }  
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.     public void setName(String name) {  
  23.         this.name = name;  
  24.     }  
  25.   
  26.     public Set<Course> getCourses() {  
  27.         return courses;  
  28.     }  
  29.     public void setCourses(Set<Course> courses) {  
  30.         this.courses = courses;  
  31.     }  
  32.   
  33.   
  34. }  

 

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.entity;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6.   
  7. public class Course {  
  8.       
  9.     private int id;  
  10.     private String name;  
  11.     private Set<Student> students  = new HashSet<Student>();  
  12.   
  13.     public int getId() {  
  14.         return id;  
  15.     }  
  16.     public void setId(int id) {  
  17.         this.id = id;  
  18.     }  
  19.     public String getName() {  
  20.         return name;  
  21.     }  
  22.     public void setName(String name) {  
  23.         this.name = name;  
  24.     }  
  25.     public Set<Student> getStudents() {  
  26.         return students;  
  27.     }  
  28.     public void setStudents(Set<Student> students) {  
  29.         this.students = students;  
  30.     }  
  31.   
  32. }  

 

 

 映射文件:

 

Xml代码  收藏代码
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.   
  7.     <class name="com.tch.test.hibernate.entity.Student" table="student">  
  8.         <id name="id" column="id" type="java.lang.Integer" length="4">  
  9.             <generator class="native"/>  
  10.         </id>  
  11.         <property name="name" column="name" type="java.lang.String"/>  
  12.         <set name="courses" table="student_course">  
  13.             <key column="studentId"></key>  
  14.             <many-to-many column="courseId" class="com.tch.test.hibernate.entity.Course"></many-to-many>  
  15.         </set>  
  16.     </class>  
  17.   
  18. </hibernate-mapping>  

 

 

Xml代码  收藏代码
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  5. <hibernate-mapping>  
  6.   
  7.     <class name="com.tch.test.hibernate.entity.Course" table="course">  
  8.         <id name="id" column="id" type="java.lang.Integer" length="4">  
  9.             <generator class="native"/>  
  10.         </id>  
  11.         <property name="name" column="name" type="java.lang.String"/>  
  12.         <set name="students" table="student_course">  
  13.             <key column="courseId"></key>  
  14.             <many-to-many column="studentId" class="com.tch.test.hibernate.entity.Student"></many-to-many>  
  15.         </set>  
  16.     </class>  
  17.   
  18. </hibernate-mapping>  

 

 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://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.   
  10.         <!-- Database connection settings -->  
  11.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  12.         <property name="connection.url">jdbc:mysql://localhost:3306/test</property>  
  13.         <property name="connection.username">root</property>  
  14.         <property name="connection.password">root</property>  
  15.   
  16.         <!-- JDBC connection pool (use the built-in) -->  
  17.         <!--<property name="connection.pool_size">1</property>-->  
  18.   
  19.         <!-- SQL dialect -->  
  20.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  21.   
  22.         <!-- Enable Hibernate's automatic session context management -->  
  23.         <property name="current_session_context_class">thread</property>  
  24.   
  25.         <!-- Disable the second-level cache  -->  
  26.         <!--<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->  
  27.   
  28.         <!-- Echo all executed SQL to stdout -->  
  29.         <property name="show_sql">true</property>  
  30.           
  31.         <!-- format_sql -->  
  32.         <property name="format_sql">true</property>  
  33.   
  34.         <!-- Drop and re-create the database schema on startup -->  
  35.         <property name="hbm2ddl.auto">update</property>  
  36.   
  37.         <mapping resource="com/tch/test/hibernate/entity/Student.hbm.xml" />  
  38.         <mapping resource="com/tch/test/hibernate/entity/Course.hbm.xml" />  
  39.   
  40.     </session-factory>  
  41.   
  42. </hibernate-configuration>  

 

 工具类:

 

Java代码  收藏代码
  1. package com.tch.test.hibernate.util;  
  2. import org.hibernate.SessionFactory;  
  3. import org.hibernate.cfg.Configuration;  
  4.   
  5. public class HibernateUtil {  
  6.   
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();  
  8.   
  9.     private static SessionFactory buildSessionFactory() {  
  10.         try {  
  11. //            return new AnnotationConfiguration().configure().buildSessionFactory();  
  12.             return new Configuration().configure().buildSessionFactory();  
  13.         }  
  14.         catch (Throwable ex) {  
  15.             System.err.println("Initial SessionFactory creation failed." + ex);  
  16.             throw new ExceptionInInitializerError(ex);  
  17.         }  
  18.     }  
  19.   
  20.     public static SessionFactory getSessionFactory() {  
  21.         return sessionFactory;  
  22.     }  
  23.   
  24. }  

 

测试类:

 

Java代码  收藏代码
  1. public class Test {  
  2.       
  3.     @org.junit.Test  
  4.     public void test1(){  
  5.         Student student = new Student();  
  6.         student.setName("张三");  
  7.         Student student2 = new Student();  
  8.         student2.setName("李四");  
  9.           
  10.         Course course = new Course();  
  11.         course.setName("数学");  
  12.         Course course2 = new Course();  
  13.         course2.setName("英语");  
  14.           
  15.         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();  
  16.         Session session = sessionFactory.getCurrentSession();  
  17.         try {  
  18.             session.beginTransaction();  
  19.             session.save(student);  
  20.             session.save(student2);  
  21.             session.save(course);  
  22.             session.save(course2);  
  23.             student.getCourses().add(course);  
  24.             session.getTransaction().commit();  
  25.         } catch (HibernateException e) {  
  26.             e.printStackTrace();  
  27.             session.getTransaction().rollback();  
  28.         }finally{  
  29.             sessionFactory.close();  
  30.         }  
  31.     }  
  32. }  

 

 OK,结果一样

posted on 2013-09-24 08:57  阿O、不拽  阅读(241)  评论(0)    收藏  举报