hibernate4.2.4之环境搭建与测试实例

 1.下载hibernate-release-4.2.4.Final.zip 从点击打开链接( http://www.hibernate.org/downloads)下载

      

2.在eclipse中新建一个java project工程,名为hibernate_first,在hibernate_first中新建一个ilb文件夹,

     解压下载的hibernate-release-4.2.4.Final.zip,打开之后有几个文件夹 lib---jar库   documentation--文档说明  projetc---关于hibernate的配置/例子等等之类的

    进入到hibernate-release-4.2.4.Final\lib\required\ 目录下 将8个必须的jar包拷贝到 hibernate_first\lib\ 下面 并且将8个jar包单击右键选中--Build Path--Add to Build Path(即添加为工程引用)

   同时将mysql-connector-java-5.1.25-bin.jar 添加lib包下

   


3.编写配置文件 进入到hibernate-release-4.2.4.Final\project\etc\ 目录下 将hibernate.cfg.xml文件拷贝到项目hibernate_first\src\ 目录下

   将hibernate.cfg.xml文件修改为如下;

<!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>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hbm2ddl.auto">create</property>
		<property name="hibernate.show_sql">true</property>
		
		<mapping resource="com/undergrowth/hibernate/domain/Student.hbm.xml" />
		
	</session-factory>
</hibernate-configuration>

简单解释一下上面的hibernate.cfg.xml文件  

 


 connection.driver_class/connection.url/connection.username/connection.password  是用于mysql连接的驱动/资源定位符/登陆账号/登陆密码

hibernate.dialect是hibernate用于兼容多种数据库而做的,告诉hibernate使用的是哪一种数据库

hibernate.show_sql是在进行相应的hibernate操作时,会在控制台输出相应的sql语句

hbm2ddl.auto是在hibernate第一次进行操作时 都会自己创建一个表

mapping resource用于指明对象与表的映射关系 这里指的是Student类和学生表的一个映射文件  下面也会介绍到

上面的这些属性其实不用记 在hibernate-release-4.2.4.Final\project\etc\hibernate.properties文件中都可以找到

 

 

 

4.编写对象与对象的映射文件 引用上面的配置  建立Student.java类 如下

   

package com.undergrowth;

import java.util.Date;

public class Student {
	private int id;  
	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 Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getMajor() {
		return major;
	}
	public void setMajor(String major) {
		this.major = major;
	}
	private String name;
	private Date birthday;
	private String major;
	public Student(String name, Date birthday, String major) {
		this.name = name;
		this.birthday = birthday;
		this.major = major;
	}
	
	public Student(){}  //用于给hibernate的反射使用
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", birthday="
				+ birthday + ", major=" + major + "]";
	}
	
	
}


 

 

编写Student的ORM映射文件Student.hbm.xml  hibernate自带的模板很多 这里引用hibernate-release-4.2.4.Final\project\documentation\src\main\docbook\quickstart\tutorials\basic\src\test\java\org\hibernate\tutorial\hbm\ 目录下的Event.hbm.xml
 
Student.hbm.xml

 

<?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 package="com.undergrowth">

    <class name="Student" table="student">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name"/>
        <property name="birthday"/>
        <property name="major"/>
    </class>

</hibernate-mapping>


 

 

5.测试
StudentDaoInter.java

 

package com.undergrowth.inter;

import com.undergrowth.Student;

public interface StudentDaoInter {
      public void saveStudent(Student student);
      public void updateStudent(Student student);
      public void deleteStudent(Student student);
      public Student findIdStudent(int id);
      public Student findNameStudent(String name);
}


 

 

StudentDaoImp.java
package com.undergrowth.imple;

import com.undergrowth.Student;
import com.undergrowth.hibernate.utils.HibernateUtils;
import com.undergrowth.inter.StudentDaoInter;

public class StudentDaoImp implements StudentDaoInter {

	@Override
	public void saveStudent(Student student) {
		// TODO Auto-generated method stub
		HibernateUtils.add(student);
	}

	@Override
	public void updateStudent(Student student) {
		// TODO Auto-generated method stub
		HibernateUtils.update(student);
	}

	@Override
	public void deleteStudent(Student student) {
		// TODO Auto-generated method stub
		HibernateUtils.delete(student);
	}

	@Override
	public Student findIdStudent(int id) {
		// TODO Auto-generated method stub
		return (Student) HibernateUtils.get(Student.class, id);
	}

	@Override
	public Student findNameStudent(String name) {
		// TODO Auto-generated method stub
		return (Student) HibernateUtils.get(name);
	}

}


 

 

HibernateUtils.java
package com.undergrowth.hibernate.utils;

import java.io.Serializable;



import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
	private static SessionFactory sf;
	
	static{
		Configuration cfg=new Configuration();
		cfg.configure();
		sf=	cfg.buildSessionFactory();
	}
	
	public static Session getSession()
	{
		return sf.openSession();
	}
	
	public static void add(Object entity)
	{
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtils.getSession();
			tx=session.beginTransaction();
			session.save(entity);
			tx.commit();
		} catch (HibernateException e) {
			throw e;
		}finally{
			if(session!=null)
				session.close();
		}
	}
	
	public static void delete(Object entity)
	{
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtils.getSession();
			tx=session.beginTransaction();
			session.delete(entity);
			tx.commit();
		} catch (HibernateException e) {
			throw e;
		}finally{
			if(session!=null)
				session.close();
		}
	}
	
	public static void update(Object entity)
	{
		Session session=null;
		Transaction tx=null;
		try {
			session=HibernateUtils.getSession();
			tx=session.beginTransaction();
			session.update(entity);
			tx.commit();
		} catch (HibernateException e) {
			throw e;
		}finally{
			if(session!=null)
				session.close();
		}
	}
	
	
	public static Object get(Class clazz,Serializable id)
	{
		Session session=null;
		try {
			session=HibernateUtils.getSession();
			Object obj=session.get(clazz, id);
			return obj;
		} catch (HibernateException e) {
			throw e;
		}finally{
			if(session!=null)
				session.close();
		}
	}
	
	public static Object get(String name)
	{
		Session session=null;
		try {
			session=HibernateUtils.getSession();
			Query query=session.createQuery("from Student as student where name=:name");
			query.setParameter("name", name);
			Object obj=query.uniqueResult();
			return obj;
		} catch (HibernateException e) {
			throw e;
		}finally{
			if(session!=null)
				session.close();
		}
	}
}


 

 

HibernateTest.java
package com;

import java.util.Date;

import com.undergrowth.Student;
import com.undergrowth.imple.StudentDaoImp;

public class HibernateTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StudentDaoImp imp=new StudentDaoImp();
		//添加
		Student student=new Student("under", new Date(), "计算机");
		System.out.println(student);
		imp.saveStudent(student);
		//查询
		student=imp.findNameStudent("under");
		System.out.println(student);
		//修改
		student.setMajor("电信");
		imp.updateStudent(student);
		//查询
		student=imp.findNameStudent("under");
		System.out.println(student);
		//删除
		imp.deleteStudent(student);
		
	}

}


 

打印的控制台信息


 

 

posted on 2013-08-14 15:03  liangxinzhi  阅读(266)  评论(0编辑  收藏  举报