hibernate 注解和xml配置入门
下面使用学生-课程为例:
首先是使用注解的方式:
- package com.tch.test.hibernate.entity;
- import java.util.Set;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- @Entity
- public class Student {
- private int id;
- private String name;
- private Set<Course> courses = new HashSet<Course>();
- @Id
- @GeneratedValue
- @Column(name="id")
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- @Column(name="name")
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @ManyToMany
- @JoinTable(name="student_course",
- joinColumns=@JoinColumn(name="student_Id"),
- inverseJoinColumns=@JoinColumn(name="course_Id"))
- public Set<Course> getCourses() {
- return courses;
- }
- public void setCourses(Set<Course> courses) {
- this.courses = courses;
- }
- }
- package com.tch.test.hibernate.entity;
- import java.util.Set;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- @Entity
- public class Course {
- private int id;
- private String name;
- private Set<Student> students = new HashSet<Student>();
- @Id
- @GeneratedValue
- @Column(name="id")
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- @Column(name="name")
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @ManyToMany(mappedBy="courses")
- public Set<Student> getStudents() {
- return students;
- }
- public void setStudents(Set<Student> students) {
- this.students = students;
- }
- }
hibernate.cfg.xml:
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <!--<property name="connection.pool_size">1</property>-->
- <!-- SQL dialect -->
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <!-- Enable Hibernate's automatic session context management -->
- <property name="current_session_context_class">thread</property>
- <!-- Disable the second-level cache -->
- <!--<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->
- <!-- Echo all executed SQL to stdout -->
- <property name="show_sql">true</property>
- <!-- format_sql -->
- <property name="format_sql">true</property>
- <!-- Drop and re-create the database schema on startup -->
- <property name="hbm2ddl.auto">update</property>
- <mapping class="com.tch.test.hibernate.entity.Course"/>
- <mapping class="com.tch.test.hibernate.entity.Student"/>
- </session-factory>
- </hibernate-configuration>
log4j.properties(查看事务的日志信息):
- ### direct log messages to stdout ###
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.Target=System.out
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
- ### direct messages to file hibernate.log ###
- #log4j.appender.file=org.apache.log4j.FileAppender
- #log4j.appender.file.File=hibernate.log
- #log4j.appender.file.layout=org.apache.log4j.PatternLayout
- #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
- ### set log levels - for more verbose logging change 'info' to 'debug' ###
- log4j.rootLogger=warn, stdout
- ### 查看事务的日志信息
- log4j.logger.org.hibernate.transaction=debug
- #log4j.logger.org.hibernate=info
- log4j.logger.org.hibernate=info
- ### log HQL query parser activity
- #log4j.logger.org.hibernate.hql.ast.AST=debug
- ### log just the SQL
- #log4j.logger.org.hibernate.SQL=debug
- ### log JDBC bind parameters ###
- #log4j.logger.org.hibernate.type=info
- #log4j.logger.org.hibernate.type=debug
- ### log schema export/update ###
- #log4j.logger.org.hibernate.tool.hbm2ddl=debug
- ### log HQL parse trees
- #log4j.logger.org.hibernate.hql=debug
- ### log cache activity ###
- #log4j.logger.org.hibernate.cache=debug
- ### log JDBC resource acquisition
- #log4j.logger.org.hibernate.jdbc=debug
- ### enable the following line if you want to track down connection ###
- ### leakages when using DriverManagerConnectionProvider ###
- #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
工具类:
- package com.tch.test.hibernate.util;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.AnnotationConfiguration;
- public class HibernateUtil {
- private static final SessionFactory sessionFactory = buildSessionFactory();
- private static SessionFactory buildSessionFactory() {
- try {
- //注解的时候使用AnnotationConfiguration
- return new AnnotationConfiguration().configure().buildSessionFactory();
- }
- catch (Throwable ex) {
- System.err.println("Initial SessionFactory creation failed." + ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
测试类:
- public class Test {
- @org.junit.Test
- public void test1(){
- Student student = new Student();
- student.setName("张三");
- Student student2 = new Student();
- student2.setName("李四");
- Course course = new Course();
- course.setName("数学");
- Course course2 = new Course();
- course2.setName("英语");
- SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
- Session session = sessionFactory.getCurrentSession();
- try {
- session.beginTransaction();
- session.save(student);
- session.save(student2);
- session.save(course);
- session.save(course2);
- student.getCourses().add(course);
- session.getTransaction().commit();
- } catch (HibernateException e) {
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- sessionFactory.close();
- }
- }
- }
最后就会发现中间表里面加入了记录,说明操作成功。
下面是xml配置方式:
实体类:
- package com.tch.test.hibernate.entity;
- import java.util.HashSet;
- import java.util.Set;
- public class Student {
- private int id;
- private String name;
- private Set<Course> courses = new HashSet<Course>();
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<Course> getCourses() {
- return courses;
- }
- public void setCourses(Set<Course> courses) {
- this.courses = courses;
- }
- }
- package com.tch.test.hibernate.entity;
- import java.util.HashSet;
- import java.util.Set;
- public class Course {
- private int id;
- private String name;
- private Set<Student> students = new HashSet<Student>();
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<Student> getStudents() {
- return students;
- }
- public void setStudents(Set<Student> students) {
- this.students = students;
- }
- }
映射文件:
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="com.tch.test.hibernate.entity.Student" table="student">
- <id name="id" column="id" type="java.lang.Integer" length="4">
- <generator class="native"/>
- </id>
- <property name="name" column="name" type="java.lang.String"/>
- <set name="courses" table="student_course">
- <key column="studentId"></key>
- <many-to-many column="courseId" class="com.tch.test.hibernate.entity.Course"></many-to-many>
- </set>
- </class>
- </hibernate-mapping>
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="com.tch.test.hibernate.entity.Course" table="course">
- <id name="id" column="id" type="java.lang.Integer" length="4">
- <generator class="native"/>
- </id>
- <property name="name" column="name" type="java.lang.String"/>
- <set name="students" table="student_course">
- <key column="courseId"></key>
- <many-to-many column="studentId" class="com.tch.test.hibernate.entity.Student"></many-to-many>
- </set>
- </class>
- </hibernate-mapping>
hibernate.cfg.xml:
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <!--<property name="connection.pool_size">1</property>-->
- <!-- SQL dialect -->
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <!-- Enable Hibernate's automatic session context management -->
- <property name="current_session_context_class">thread</property>
- <!-- Disable the second-level cache -->
- <!--<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->
- <!-- Echo all executed SQL to stdout -->
- <property name="show_sql">true</property>
- <!-- format_sql -->
- <property name="format_sql">true</property>
- <!-- Drop and re-create the database schema on startup -->
- <property name="hbm2ddl.auto">update</property>
- <mapping resource="com/tch/test/hibernate/entity/Student.hbm.xml" />
- <mapping resource="com/tch/test/hibernate/entity/Course.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
工具类:
- package com.tch.test.hibernate.util;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- public class HibernateUtil {
- private static final SessionFactory sessionFactory = buildSessionFactory();
- private static SessionFactory buildSessionFactory() {
- try {
- // return new AnnotationConfiguration().configure().buildSessionFactory();
- return new Configuration().configure().buildSessionFactory();
- }
- catch (Throwable ex) {
- System.err.println("Initial SessionFactory creation failed." + ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- }
测试类:
- public class Test {
- @org.junit.Test
- public void test1(){
- Student student = new Student();
- student.setName("张三");
- Student student2 = new Student();
- student2.setName("李四");
- Course course = new Course();
- course.setName("数学");
- Course course2 = new Course();
- course2.setName("英语");
- SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
- Session session = sessionFactory.getCurrentSession();
- try {
- session.beginTransaction();
- session.save(student);
- session.save(student2);
- session.save(course);
- session.save(course2);
- student.getCourses().add(course);
- session.getTransaction().commit();
- } catch (HibernateException e) {
- e.printStackTrace();
- session.getTransaction().rollback();
- }finally{
- sessionFactory.close();
- }
- }
- }
OK,结果一样
 
                    
                 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号