Hibernate 4.3.7使用例子

今天心血来潮下了Hibernate 4.3.7,咋一用发现跟Hibernate 3不太一样,特此记录。

首先在Hibernate的官网下载
hibernate-release-4.3.7.Final.zip

解压Hibernate发现目录结构跟以前没多大区别
documentation目录下面放的是文档
lib目录下面放的是jar包
project目录下面放的的源码

在Eclipse中新建Java工程HelloHibernate
将hibernate-release-4.3.7.Final/lib/required中的所有包都放到工程的lib目录下
数据库使用的是H2,所以还要将H2的jar包h2-1.4.184.jar放到lib目录下

新建User实体类
package com.lnc.hello.hibernate;

public class User {

	private int id;

	private String username;

	private String password;

	public int getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

新建实体类映射文件User.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.lnc.hello.hibernate">

	<class name="User" table="T_USER">
		<id name="id" column="ID">
			<generator class="increment" />
		</id>
		<property name="username" column="USERNAME" />
		<property name="password" column="PASSWORD" />
	</class>

</hibernate-mapping>

新建Hibernate配置文件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>
		<property name="connection.driver_class">org.h2.Driver</property>
		<property name="connection.url">jdbc:h2:mem:hello;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
		<property name="connection.username">sa</property>
		<property name="connection.password" />
		<property name="connection.pool_size">1</property>
		<property name="dialect">org.hibernate.dialect.H2Dialect</property>
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>

		<mapping resource="com/lnc/hello/hibernate/User.hbm.xml" />
	</session-factory>

</hibernate-configuration>


新建Main测试类
package com.lnc.hello.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class Main {

	private static SessionFactory sf = null;

	public static SessionFactory createSessionFactory() {

		if (sf == null) {
			Configuration cfg = new Configuration().configure();
			ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
					.applySettings(cfg.getProperties()).build();
			sf = cfg.buildSessionFactory(serviceRegistry);
		}

		return sf;
	}

	public static void closeSessionFactory() {
		if (sf != null) {
			sf.close();
			sf = null;
		}
	}

	public static void setUser() {
		SessionFactory sf = createSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		User user = new User();
		user.setUsername("username");
		user.setPassword("password");
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}

	public static User getUser() {
		SessionFactory sf = createSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		User user = (User) session.get(User.class, 1);
		session.getTransaction().commit();
		session.close();

		return user;
	}

	public static void main(String[] args) {

		setUser();

		User user = getUser();
		System.out.println(user.getUsername());

	}

}


运行Main输出
Hibernate: drop table T_USER if exists
Hibernate: create table T_USER (ID integer not null, USERNAME varchar(255), PASSWORD varchar(255), primary key (ID))
Hibernate: select max(ID) from T_USER
Hibernate: insert into T_USER (USERNAME, PASSWORD, ID) values (?, ?, ?)
Hibernate: select user0_.ID as ID1_0_0_, user0_.USERNAME as USERNAME2_0_0_, user0_.PASSWORD as PASSWORD3_0_0_ from T_USER user0_ where user0_.ID=?
username


跟Hibernate 3的区别在于获取SessionFactory的方式
以前Hibernate 3下面方式获取
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();


buildSessionFactory方法在Hibernate 4中已经不推荐使用了
Hibernate 4中推荐使用带参数的buildSessionFactory方法
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
		.applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);


但发现ServiceRegistryBuilder也是不推荐使用的
最后上网查了一把发现需要使用StandardServiceRegistryBuilder类
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
		.applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);


还有一个session的get方法跟load方法的区别
get方法是在执行方法的时候就会去查数据库
load方法是在使用的时候才会去查数据库
如果上面的例子把get方法换成load方法会报如下异常
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
	at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
	at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
	at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
	at com.lnc.hello.hibernate.User_$$_jvst81d_0.getUsername(User_$$_jvst81d_0.java)
	at com.lnc.hello.hibernate.Main.main(Main.java:61)

这是因为在getUsername方法执行的时候才去查数据库,而这时候session已经被关闭。

猜你喜欢

转载自liunancun.iteye.com/blog/2171704
今日推荐