---
title: "Hibernate 4 知识点记载"
author: "空指针异常"
date: "2014-04-14T14:37:47Z"
tags: []
categories: ["编程语言"]
slug: "hibernate-4"
draft: false
lastmod: "2014-09-15T11:28:38Z"
id: 2045763
url: "https://java-zhuwei.iteye.com/blog/2045763"
---

**下载地址：**
<http://sourceforge.net/projects/hibernate/files/>

**hibernate.cfg.xml**

```java
<?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/ssh</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.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        
        <mapping class="com.utstar.model.User"/>
    </session-factory>

</hibernate-configuration>
```


**获取SessionFactory**

```java
public class HibernateUtil {
	private static SessionFactory sf;

	static {
		Configuration cfg = new Configuration().configure();

		StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
		ServiceRegistry sr = serviceRegistryBuilder.applySettings(
				cfg.getProperties()).build();
		sf = cfg.buildSessionFactory(sr);
	}

	public static SessionFactory getSessionFactory() {
		return sf;
	}
}
```


**与hibernate3的变化，参考如下帖：**
<http://hi.baidu.com/austincao/item/fc9907da3d854e44fa576861>

hibernate 执行原生SQL出现“SQL Error: 0, SQLState: S0022”解决方案文章，参考
<http://www.tuicool.com/articles/eia63m>