Hibernate4.3.7初步使用

首先需要将hibernate-release-4.3.7.Final\lib\required之下的jar包全部加入到项目的classpath之中,如果希望更快的配置cfg和hbm之类的文件,可以在Eclipse中安装Hibernate tools插件,具体安装方法不谈,网上一大堆,另外注意同时加入mysql的驱动包。

先上cfg文件:

<?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>
		<property name="connection.username">root</property>
		<property name="connection.password">admin</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql:///hibernate4</property>
		<!-- 配置Hibernate数据库方言 -->
		<!-- MySQL org.hibernate.dialect.MySQLDialect -->
		<!-- MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect -->
		<!-- MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect -->
		<!-- MySQL5 org.hibernate.dialect.MySQL5Dialect -->
		<!-- MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect -->
		<!-- 注意,这里一定要与你的mysql的版本相匹配,如果是5.0之前的版本,请使用MySQLDialect配套的 -->
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		<property name="format_sql">true</property>
		<property name="show_sql">true</property>
		<!-- 指定自动生成数据表策略 -->
		<!-- 如果使用create,则每次都会生成新的数据表 -->
		<!-- 如果使用create-drop,则每次都会生成新的数据表并且关闭SessionFactory的时候会删除表 -->
		<!-- 如果使用validate,则会校验hbm文件和数据库中的表,如果hbm中的列在数据表中不存在,抛出异常 -->
		<property name="hbm2ddl.auto">update</property>

		<!-- 设置Hibernate事务隔离级别 -->
		<property name="connection.isolation">2</property>
		<mapping resource="cn/edu/shu/hibernate/helloworld/hbm/HelloWorld.hbm.xml" />
		<mapping resource="cn/edu/shu/hibernate/helloworld/hbm/News.hbm.xml" />
	</session-factory>
</hibernate-configuration>
再上一个News实体类:
package cn.edu.shu.hibernate.helloworld;

import java.sql.Date;

public class News {

	public News() {
	}

	public News(String title, String author, Date date) {
		this.title = title;
		this.author = author;
		this.date = date;
	}

	private Integer id;
	private String title;
	private String author;
	private Date date;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
	}
}

看一下hbm文件吧:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-1-12 12:34:09 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="cn.edu.shu.hibernate.helloworld.News" table="NEWS">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
		<!-- 使用数据库本地的主键策略 -->
            <generator class="native" />
        </id>
        <property name="title" type="java.lang.String">
            <column name="TITLE" />
        </property>
        <property name="author" type="java.lang.String">
            <column name="AUTHOR" />
        </property>
        <property name="date" type="java.sql.Date">
            <column name="DATE" />
        </property>
    </class>
</hibernate-mapping>
最后上一个Hibernate测试类
package cn.edu.shu.hibernate.helloworld;

import java.sql.Date;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HibernateTest {
	private SessionFactory sessionFactory = null;
	private Configuration configuration = new Configuration().configure();
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		System.out.println("before");
	}

	@After
	public void destroy() {
		System.out.println("after");
	}

	@Test
	public void test() {
		// Hibernate3.x的写法,已淘汰
		SessionFactory buildSessionFactory = configuration.buildSessionFactory();
		// Hibernate4.x之后的新方法
		// 这种写法已过时,被标准的StandardServiceRegistry所取代
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				.buildServiceRegistry();
		// 4.3.7所推荐使用的方法
		StandardServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
				.build();
		// 可以把configuration.getProperties()打印出来看看,发现就是一些系统的变量键值对
		Properties properties = configuration.getProperties();
		Set<Entry<Object, Object>> entrySet = properties.entrySet();
		for (Entry<Object, Object> entry : entrySet) {
			// System.out.println(entry);
		}
		// 获取sessionFactory对象
		sessionFactory = configuration.buildSessionFactory(registry);
		// 打开session
		session = sessionFactory.openSession();
		// 打开事务
		transaction = session.beginTransaction();

		News news = new News("java", "SHU", new Date(new java.util.Date().getTime()));
		// session.save(news);// 保存到数据库中

		// 从数据库中获取
		News load = (News) session.load(News.class, 1);
		// org.hibernate.HibernateException: Javassist Enhancement failed: cn.edu.shu.hibernate.helloworld.News
		// 在使用load方法的时候,居然出错,经查,原来是没有一个无参构造,总结只要是自己添加了构造,一定要给一个无参构造,这是一个好习惯
		System.out.println(load);
		// 无论load几次,Hibernate只会发一次查询语句,这是因为有一级缓存(session缓存 )的存在
		load = (News) session.load(News.class, 1);
		load = (News) session.get(News.class, 1);
		System.out.println(load);

		// 那么如何清理缓存呢
		// flush方法,会使数据表中的记录和Session缓存中的对象的状态保持一致,为了保持一致,则可能会发送对应的sql语句
		load.setAuthor("FLUSH TEST...。。。");
		// FLUSH TEST...成功提交到数据库 由此可以看出,即使没有调用save方法,使用flush方法一样可以将更改提交到数据库,但是flush方法不会提交事务,如果你不手动提交事务,这个改动就不会更新到数据库中
		// 那么哪些情况会执行flush方法呢?
		// 1、执行HQL或QBC查询,会先进行flush()操作,以得到数据表的最新记录
		// 2、若记录的ID是由底层数据库使用自增的方式生成的,则在调用save()方法时 ,就会立即发送INSERT语句

		// 总结:commit()和flush()方法的区别
		// 1、flush执行一系列sql语句,但不提交事务
		// 2、commit先调用flush方法,然后提交事务,提交事务就在数据库中永久保存
		session.flush();
		// load = (News) session.load(News.class, 4);
		// System.out.println(load);
		// session.save(load);

		// refresh方法会强制发送select语句,以使session缓存中对象的状态和数据表中对应的记录保持一致!

		// 提交事务
		transaction.commit();
		// 关闭session
		session.close();
		// 关闭工程
		sessionFactory.close();
	}

	@Test
	public void testClear() {
		// session.clear();
	}

	@Test
	public void testRefresh() {
		// News load = (News) session.load(News.class, 4);
		// session.refresh(load);
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值