hibernate检索的几种方式

package com.cwh.hibernate.enties.hql;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import static org.junit.Assert.*;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;

import com.cwh.hibernate.enties.hql.Goods;
import com.cwh.hibernate.enties.hql.Apple;;

public class Hibernate4Test {
	
	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	[@Before](https://my.oschina.net/u/3870904)
	public void init(){
		//4.1.1版本写法
		Configuration configuration = new Configuration().configure();
		ServiceRegistry registry = 
				new ServiceRegistryBuilder()
				.applySettings(configuration.getProperties())
				.buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(registry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
		System.out.println("begin");
	}
	
	@After
	public void destroy(){
		transaction.commit();
		session.close();
		sessionFactory.close();
		System.out.println("close");
	}
	[@Test](https://my.oschina.net/azibug)
	public void test(){
		
	}
	
	[@Test](https://my.oschina.net/azibug)
	public void testSave(){
		Goods goods = new Goods();
		goods.setName("不明物体5");
		goods.setWeigh("110g");
		
		Apple apple = new Apple();
		apple.setWeigh("315g");
		apple.setName("红富士5");
		apple.setSeason("autom");
		
		session.save(goods);
		session.save(apple);
	}
	
	[@Test](https://my.oschina.net/azibug)
	public void testQuery(){
		Apple apple = (Apple) session.get(Apple.class, 2);
		Goods goods = (Goods)session.get(Goods.class, 1);
		
		System.out.println("apple: "+apple.toString()+" ,name="+apple.getName()+" ,weigh="+apple.getWeigh()+" ,id="+apple.getId());
		System.out.println("goods: "+goods.toString());
	}
	
	@Test
	public void testHQL(){
//		String hql = "FROM Goods g WHERE g.weigh like :weigh";
//		Query query = session.createQuery(hql);
//		
//		query.setString("weigh", "%3%");
//		
//		List<Goods> goods = query.list();
//		for(Goods goods1 : goods){
//			System.out.println(goods1.toString());
//		}
//		System.out.println(goods.size());
		
		String hql = "FROM Apple g WHERE g.id = :weigh";
		Query query = session.createQuery(hql);
		
		query.setString("weigh", "2");
		
		List<Apple> goods = query.list();
		for(Apple goods1 : goods){
			System.out.println(goods1.toString()+goods1.getSeason());
		}
		System.out.println(goods.size());
		
//		Apple apple = (Apple) session.get(Apple.class, 2);
//		System.out.println(apple.toString()+apple.getSeason());
	}
	
	@Test
	public void testHQL2(){
		//"apples"可在映射文件<query> 标签配置查询语句
		Query query = session.getNamedQuery("apples");
		query.setString("name", "%红%");
		
		List<Apple> apples = query.list();
		for(Apple apple : apples){
			System.out.println(apple.toString()+apple.getSeason());
		}
		System.out.println(apples.size());
	}
	
	@Test
	public void testPage(){
		Query query = session.getNamedQuery("page2");
		int pageNum = 1;
		int pageSize = 2;
		query.setFirstResult((pageNum-1)*pageSize)
				.setMaxResults(pageSize);
		
		List<Goods> list = query.list();
		for(Goods goods : list){
			System.out.println(goods.toString());
		}
		System.out.println("长度: "+list.size());
	}
	
	@Test
	public void testQBC(){
		//创建criteria对象
		Criteria criteria = session.createCriteria(Apple.class);
		//添加查询条件(Criterion可以通过Restrictions静态方法得到)
		criteria.add(Restrictions.eq("name", "红富士5"));
//		criteria.add(Restrictions.eq("weigh", "310g"));
		//执行查询
//		Goods goods = (Goods) criteria.uniqueResult();
		List<Goods> goods =criteria.list();
		System.out.println(goods);
		
	}
	
	@Test
	public void testQBC2(){
		Criteria criteria = session.createCriteria(Goods.class);
		//and 和like语句
		Conjunction conjunction = Restrictions.conjunction();
		conjunction.add(Restrictions.like("name", "1", MatchMode.ANYWHERE));
		criteria.add(conjunction);
		//or语句
		Disjunction disjunction = Restrictions.disjunction();
		disjunction.add(Restrictions.isNotNull("name"));
		criteria.add(disjunction);
		List<Goods> list = criteria.list();
		System.out.println(list);
	}
	
	@Test
	public void testQBC3(){
		Criteria criteria = session.createCriteria(Goods.class);
		//统计函数
		criteria.setProjection(Projections.min("weigh"));
		System.out.println(criteria.uniqueResult());
	}
	
	@Test
	public void testQBC4(){
		Criteria criteria = session.createCriteria(Goods.class);
		//排序
		criteria.addOrder(Order.asc("weigh"));
		//分页
		criteria.setFirstResult(0)
				.setMaxResults(3)
				.list();
	}
	@Test
	public void testSQL(){
		String sql = "INSERT INTO Goods VALUES(?,?,?,?)";
		Query query = session.createSQLQuery(sql);
		
		query.setString(0, "snake3")
			.setString(1, "bigger")
			.setString(2, "140")
			.setString(3, "summer").executeUpdate();
	}
}

映射文件:

<?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 2018-5-16 14:18:51 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.cwh.hibernate.enties.hql.Goods" table="GOODS">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="weigh" type="java.lang.String">
            <column name="WEIGH" />
        </property>
    
     <joined-subclass name="com.cwh.hibernate.enties.hql.Apple" table="Apple">
        	<key>
        		<column name="GOODS_ID"></column>
        	</key>
	       <property name="season" type="java.lang.String">
	            <column name="SEASON" />
	        </property>
        </joined-subclass> 
        
          <!--  <union-subclass name="com.cwh.hibernate.enties.hql.Apple" table="APPLE2">
        	<property name="season" type="java.lang.String">
	            <column name="SEASON" />
	        </property>
        </union-subclass>-->   
    </class>
    
    <query name="page"><![CDATA[FROM Goods g where 1=1 order by id]]></query>
     <query name="page2"><![CDATA[FROM Apple g where 1=1]]></query>
    <query name="apples"><![CDATA[FROM Apple a where a.name like :name]]></query>
</hibernate-mapping>

配置文件:

<?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">chenwenhuan</property>
    	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="connection.url">jdbc:mysql://localhost:3306/testHQL?useUnicode=true&amp;characterEncoding=UTF-8</property>
    	
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    	
    	<property name="hibernate.c3p0.max_size">20</property>
    	<property name="hibernate.c3p0.min_size">5</property>
    	<property name="hibernate.c3p0.idle_test_period">5000</property>
    	<property name="hibernate.c3p0.acquire_increment">5</property>
    	<property name="hibernate.c3p0.timeout">5000</property>
    	<!-- 启用二级缓存 -->
    	<property name="cache.use_second_level_cache">true</property>
    	
    	<!-- 二级缓存使用的产品 -->
    	<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
   		
   		<mapping resource="com/cwh/hibernate/enties/hql/Goods.hbm.xml"/>
   		
   		<!-- 启用二级缓存的类 -->
   		<class-cache usage="read-write" class="com.cwh.hibernate.enties.hql.Goods"/>
   		
    </session-factory>
</hibernate-configuration>

转载于:https://my.oschina.net/u/3780366/blog/1814839

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值