首页 > 代码库 > sessionFactory的创建和四种查询方式

sessionFactory的创建和四种查询方式

1,关于sessionFactory的创建

5.0版本之前,下面这种方式在5.0及之后,可能会出问题,建议修改为5.0之后的方式

	// 实例化Configuration
		Configuration configuration = new Configuration();
		// 加载hibernate.cfg.xml文件
		configuration.configure("/hibernate.cfg.xml");
		// 创建SessionFactory
		StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
		standardServiceRegistryBuilder.applySettings(configuration
				.getProperties());
		SessionFactory sessionFactory = configuration
				.buildSessionFactory(standardServiceRegistryBuilder.build());

5.0版本以及5.0之后

SessionFactory sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();

官方建议的方法

		
		StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
	    .configure( "hibernate.cfg.xml" )
	    .build();

	Metadata metadata = http://www.mamicode.com/new MetadataSources( standardRegistry )>

hibernate获取sessionFactory的工具类

 

public class HibernateUtils {
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal 
									= new ThreadLocal<Session>();
	private static SessionFactory sessionFactory;
	private static String configFile = CONFIG_FILE_LOCATION;
	/* 静态代码块创建SessionFactory */
	static {
		try {
			sessionFactory = new Configuration().configure(configFile).buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	private HibernateUtils() {
	}
	/**
	 * 返回ThreadLocal中的session实例
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}
		return session;
	}
	/**
	 * 返回Hibernate的SessionFactory
	 */
	public static void rebuildSessionFactory() {
		try {
			sessionFactory = new Configuration().configure(configFile).buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	/**
	 * 关闭Session实例并且把ThreadLocal中副本清除
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}
	/**
	 * 返回SessionFactory
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public static void setConfigFile(String configFile) {
		HibernateUtils.configFile = configFile;
		sessionFactory = null;
	}
}

  

2.hibernate的使用

这里要注意,hibernate不会自动产生数据库,所以你需要自己先建立一个空数据库,编码设置为utf8,hibernate自己建表时会参考数据库的编码格式

1)配置文件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>
        <!-- 配置访问Oracle数据库参数信息 -->
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="connection.url">
        jdbc:mysql://127.0.0.1:3306/hibTest?useUnicode=true&amp;characterEncoding=UTF-8
            <!-- jdbc:oracle:thin:@localhost:1521:orcl -->
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>
        <!-- 在控制台显示SQL语句 -->
        <property name="show_sql">true</property>
        <!--根据需要自动生成、更新数据表 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 注册所有ORM映射文件 -->
        <mapping resource="com/qst/chapter05/pojos/Student.hbm.xml" />
        <!-- <mapping resource="com/qst/chapter05/pojos/User.hbm.xml" /> -->
        <mapping class="com.qst.chapter05.pojos.TestAno" /> 
        <mapping class="com.qst.chapter05.pojos.User" /> 

    </session-factory>
</hibernate-configuration>

 

 

2)POJO 不建议用xml的方式,用注解更简单易读

package com.qst.chapter05.pojos;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user") 
public class User implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/* 用户ID */
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "id", insertable = false, updatable = false)
	private Integer id;
	/* 用户名 */
	@Column(name = "user_name")
	private String userName;
	/* 密码 */
	@Column(name = "user_pwd")
	private String userPwd;
	/* 权限 */
	@Column(name = "role")
	private Integer role;
	/* 默认构造方法 */
	public User() {
	}
	/* 根据属性创建 构造方法 */
	public User(String userName, String userPwd,Integer role) {
		this.userName = userName;
		this.userPwd=userPwd;
		this.role=role;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	public Integer getRole() {
		return role;
	}
	public void setRole(Integer role) {
		this.role = role;
	}

}

  

测试代码

session自带的方法

保存

public class UserDemo {

	public static void main(String[] args) {
		// 创建User对象
		User user = new User("zhangsan", "123", 1);
		SessionFactory sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
		// 打开Session
		Session session = sessionFactory.openSession();
		// 开始一个事务
		Transaction trans = session.beginTransaction();
		// 持久化操作
		session.save(user);
		// 提交事务
		trans.commit();
		// 关闭Session
		session.close();
	}

}

 

更新

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Monaco; color: #7e504f } span.s1 { color: #000000 }</style>

session.update(user);

查询

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Monaco } span.s1 { color: #7e504f } span.s2 { color: #931a68 }</style>

User user = (User) session.get(User.class, key);

 

HQL语句

Query query = session.createQuery("from User");
		// 执行查询
		List<User> list = query.list();
		// 遍历输出
		for (User u : list) {
			System.out.println(u.getId() + "\t" + u.getUserName() + "\t"
					+ u.getUserPwd() + "\t" + u.getRole());
		}

 

SQL查询,这个查完了需要手工映射,比较麻烦

Query query = session.createSQLQuery("select * from user");
        // 执行查询
        List<Object[]> list = query.list();
        // 遍历输出
        for (Object[] u : list) {
            System.out.println(u[0] + "\t" + u[1] + "\t"
                    + u[2] + "\t" + u[3]);
        }

 

Criteria查询

 

Criteria criteria = session.createCriteria(User.class);
        // 执行查询
        List<User> list = criteria.list();
        // 遍历输出
        for (User stu : list) {
            System.out.println(stu.getId() + "\t" + stu.getUserName() + "\t"+stu.getUserPwd());
        }

 

 

 

 

 

 

 

 

 

 

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Monaco; color: #7e504f }</style>

sessionFactory的创建和四种查询方式