Hibernate学习笔记

关于Hibernate的学习我是先看的马士兵老师的视频在看书的 真的很不错 发个链接   视频地址

就目前所学的东西来对Hibernate做一个定义:Hibernate就是一个将面向对象中的类对应变成数据库中数据的一个工具,比如在业务逻辑中我们定义了一个学生,对于这个学生的信息我们是定义了一个类来保存到内存中的,而Hibernate就可以很方便的把它保存到数据库中以便永久储存。

一。关于何如配置Hibernate

1.首先下载hibernate-distribution-3.5.2-Final-dist.zip 以及mysql-connector-java-5.1.22.tar.gz,视频中提到的一个和日志有关的东西还不太清楚 先不说了,叫slf4j-1.5.8.zip。

2.下载完后,将如图所示的文件都通过build path 加入到项目,其中slf4j是日志、mysql是数据库驱动。

hibernate.zip中除了hibernate3.jar之外,别的jar都在lib\required里面 顾名思义 必须的嘛!


3.然后是配置hibernate.cfg.xml文件,这个东西是hibernate最核心的配置文件,需要自己写,马老师给了一个很好的建议,这种代码都从DOC文件里copy,那么在我们刚才下载的hibernate.zip里面找到documentation\manual,打开doc文档

在这里找到XmL代码复制



在这个XML里我们要配置连接数据库的各种参数,看下我写的

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/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/hibernate</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 是否显示生成的SQl语句-->
        <property name="show_sql"
>true</property>

        <!-- Drop and re-create the database schema on startup让hibernate自动生成建表语句 -->
       <!--  <property name="hbm2ddl.auto"
>update</property> -->

        <mapping resource="model/Student.hbm.xml"/>

    </session-factory>

</hibernate-configuration
>

<mapping resource="model/Student.hbm.xml"/>我写了一个Student类作为例子,会用到这个映射,这个后面再说。


4.然后我们需要建这么几个文件

model/Student.java 学生类的模型

model/Student.hbm.xml 用来映射类和数据库之间列名对应关系的映射表

来看代码

package model;

public class Student {
	private int id;
	private String name;
	private int age;
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="model">
   <class name="Student" table="student">
	 <id name="id"><!-- id是主键 -->
        </id>
         <property name="name"/>
          <property name="age"/>
    </class>
</hibernate-mapping
>

这里我们就可以解释<mapping resource="model/Student.hbm.xml"/>的意思了,当hibernate想知道类和数据库表之间的详细对应关系时 他就会在自己的配置文件中找 ,这句代码就告诉了hibernate 去model/Student.hbm.xml"读取这个对应关系。
然后就可以测试了:
这里有两个文件:

HibernateUtil.java这个是提取出来的的一个返回sessionfactory会话工厂的类,因为对一个数据库的访问只需要定义一个会话工厂即可,一个会话工厂可以产生多个session会话,就这么个意思。一个数据库需要一个sessionFactory,因为 sessionFactory不是轻量级的 占用资源比较多 所以sessionFactory最好是共享的


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//可以随时返回一个sessionfactory 不用每次都创建
public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}	

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}

然后是测试文件的代码

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import model.Student;

public class StudentTest {
	public static void main(String[] args) {
		Student s = new Student();
		s.setId(12);
		s.setName("s1");
		s.setAge(1);
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();	//相当于数据库的一个连接
		session.beginTransaction();
//		session.save(s);
//		session.delete(s);
//		session.getTransaction().commit(); //这是储存数据的例子 即insert
		session.close();
		sf.close();
		Query query = session.createQuery("from Student");	//这里的student是对应着数据模型的JAVA文件
		List<Student> list = query.list();
		for (Student student : list) {
			System.out.println(student.getId());
		}//这是查询数据的例子 即 select
		
	}
}

Query可以方便的对数据库以及持久对象进行查询,但当对数据库进行增删改的操作时,需要使用事务处理,也就是

session.beginTransaction(); 
session.getTransaction().commit();
只有当对事物提交时,对数据库的修改才更新到数据库


二.Hibernate的常见操作

查询和删除都很简单 这里光帖下更改的代码

SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession(); // 相当于数据库的一个连接
		session.beginTransaction();
		Student s = (Student) session.get(Student.class, 1);//这个1指的是主键的值
		s.setAge(99);
		session.saveOrUpdate(s);	//更新数据
		session.getTransaction().commit(); 
		session.close();
		sf.close();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值