---
title: "hibernate简便查询测试"
author: "phoenixocean"
date: "2012-02-12T20:22:12Z"
tags: ["Hibernate", "Java", "MySQL", "sessionfactory"]
categories: ["数据库"]
slug: "hibernate"
draft: false
lastmod: "2012-02-12T20:22:12Z"
id: 1403338
url: "https://phoenixocean.iteye.com/blog/1403338"
---

为了方便hibernate查询测试，可以直接使用SessionFactory进行创建连接，而不需要部署环境，在这记录一下：

 

```
package com.picshowsys.common;

import java.util.List;

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

public class Test {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		SessionFactory sf = new Configuration()
			.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
			.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
			.setProperty("hibernate.connection.url", "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=latin1")
			.setProperty("hibernate.connection.username", "root")
			.setProperty("hibernate.connection.password", "root")
//			.setProperty("hibernate.hbm2ddl.auto", "create")
//			validate               加载hibernate时，验证创建数据库表结构
//			create                  每次加载hibernate，重新创建数据库表结构，这就是导致数据库表数据丢失的原因。
//			create-drop        加载hibernate时创建，退出是删除表结构
//			update                 加载hibernate自动更新数据库结构
			.addAnnotatedClass(Order.class)
			.addAnnotatedClass(Item.class)
	    	.buildSessionFactory();
		
		Session session = sf.openSession();
		session.beginTransaction();

		List<Order> result = session.createQuery("from Order").list();
	    for(Order order : result){
	    	List<Item> items = session.createFilter(order.getItems(), "where this.price > 100").list();
	    	order.setItems(items);
	    }
	    
	    for(Order order : result){
	    	System.out.println(order.getItems().size());
	    }

	    session.getTransaction().commit();
	    
	    System.out.println("done...");
	}

}
```