`
dreamoftch
  • 浏览: 495491 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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,结果一样

 

 

 

分享到:
评论

相关推荐

    非注解Springmvc+spring+hibernate 入门实例

    总的来说,这个入门实例旨在帮助初学者理解如何在没有使用注解的情况下,通过XML配置文件集成SpringMVC、Spring和Hibernate,完成一个简单的Web应用。虽然现在的最佳实践倾向于使用注解和Spring Boot,但理解非注解...

    hibernate原理与配置快速入门

    本教程将带你快速了解Hibernate的核心原理和配置过程。 ### 1. Hibernate概述 Hibernate 是一个开源的ORM框架,它的主要目标是简化Java应用与数据库之间的交互。通过ORM,Hibernate将数据库中的记录映射为Java对象...

    Hibernate原理与配置快速入门

    **Hibernate原理与配置快速入门** Hibernate 是一个强大的Java持久化框架,它简化了数据库操作,使得开发者无需直接编写SQL语句即可对数据库进行操作。在本文中,我们将深入探讨Hibernate的核心原理、配置过程以及...

    ( Hibernate原理与配置快速入门.zip )PDF高清版教程

    《Hibernate原理与配置快速入门》是一本专门为初学者和开发者准备的指南,旨在帮助读者迅速掌握Hibernate这一强大的Java对象关系映射(ORM)框架。在本文中,我们将深入探讨Hibernate的核心概念、配置方法以及实际...

    Hibernate入门

    - **Hibernate核心配置文件**(`hibernate.cfg.xml`): - 包含数据库连接信息(如数据库类型、用户名、密码等)。 - 设置Hibernate的运行参数(如缓存策略、日志级别等)。 - 引用实体映射文件的位置信息。 - *...

    Hibernate入门案例源码

    在本案例中,你会看到如何在MyEclipse和Eclipse两个集成开发环境中配置和使用Hibernate。这两个IDE都是Java开发者常用的工具,它们提供了丰富的功能,包括项目管理、代码编辑、调试以及对各种框架的支持。 首先,你...

    Hibernate原理与配置快速入门.rar

    《Hibernate原理与配置快速入门》是一本针对Java开发者的学习指南,旨在帮助初学者迅速掌握Hibernate这一流行的ORM(对象关系映射)框架。Hibernate是Java世界中解决数据库操作问题的重要工具,它通过提供一种抽象层...

    初学hibernate,hibernate入门

    Hibernate就是这种技术的典型代表,它将Java对象和数据库表之间的映射关系定义在XML配置文件或注解中。 2. **组件架构**:Hibernate包含Session、SessionFactory、Entity、Query等核心组件。SessionFactory负责创建...

    Hibernate 原理与配置快速入门(转)

    这个快速入门教程将深入探讨Hibernate的核心概念和配置,帮助初学者快速掌握其基本用法。 ### Hibernate 概述 Hibernate 提供了一种方便的方式来处理数据库交互,通过ORM机制,它自动将Java对象映射到数据库表,...

    hibernate相关原理与配置快速入门

    以上就是 Hibernate 的基本原理和配置快速入门的介绍。在实际开发中,还需要根据项目需求,学习和掌握更多高级特性和最佳实践,例如级联操作、懒加载、代理对象、多对多关系映射等。通过深入理解和实践,Hibernate ...

    Hibernate入门(代码+笔记)

    接着,配置Hibernate的主配置文件`hibernate.cfg.xml`,包括数据库连接信息、方言设置等。然后,创建一个简单的实体类,例如`User`,并使用注解或XML映射文件将其映射到数据库中的`users`表。 **第二部分:...

    Hibernate入门jar包

    Hibernate提供了丰富的API和配置选项,比如通过XML或注解定义实体类,配置数据源,使用HQL(Hibernate Query Language)或JPQL(Java Persistence Query Language)进行复杂查询,以及事务管理和缓存策略等。...

    Hibernate 的原理与配置快速入门

    在本文中,我们将深入探讨Hibernate的核心原理和配置,帮助初学者快速上手。 首先,了解ORM的概念非常重要。ORM是一种技术,它可以将Java对象(类和对象)映射到关系数据库中的表,从而在Java应用中处理数据就像...

    hibernate+spring+struts 入门例子.zip

    这通常涉及到配置文件的设置,如Hibernate的cfg.xml、Spring的beans.xml以及Struts的struts-config.xml,还有相关的Java类和JSP页面。这些示例将展示如何在实际项目中管理和控制数据访问、业务逻辑以及用户界面交互...

    struts2+hibernate3.2+spring2.0配置+入门实例

    - 创建与users表对应的Users实体类,使用Hibernate注解或XML映射文件进行关联。 - 配置Hibernate的SessionFactory,定义Bean ID,并指定数据库连接配置。 **4. Struts2配置** - 创建Struts2的Action类,用于接收...

Global site tag (gtag.js) - Google Analytics