您的位置:首页 > 其它

Hibernate之Criteria标准化对象查询小Demo

2017-10-19 15:17 399 查看
   代码:

#数据模型层

package com.sunline.entity;

/**
* Book entity. @author MyEclipse Persistence Tools
*/

public class Book  implements java.io.Serializable {

// Fields

private Integer id;
private String name;
private Double price;
private String info;

// Constructors

/** default constructor */
public Book() {
}

/** minimal constructor */
public Book(String name, Double price) {
this.name = name;
this.price = price;
}

/** full constructor */
public Book(String name, Double price, String info) {
this.name = name;
this.price = price;
this.info = info;
}

// Property accessors

public Integer getId() {
return this.id;
}

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

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Double getPrice() {
return this.price;
}

public void setPrice(Double price) {
this.price = price;
}

public String getInfo() {
return this.info;
}

public void setInfo(String info) {
this.info = info;
}
}

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.sunline.entity.Book" table="book" catalog="association">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="70" not-null="true" />
</property>
<property name="price" type="java.lang.Double">
<column name="price" precision="10" not-null="true" />
</property>
<property name="info" type="java.lang.String">
<column name="info" length="80" />
</property>
</class>
</hibernate-mapping>

#数据访问层

package com.sunline.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.sunline.entity.Book;
import com.sunline.sessionFactory.HibernateSessionFactory;
@Repository(value="bookDao")
public class BookDao extends HibernateDaoSupport{
private Session session;
private Transaction tx;
HibernateSessionFactory getSession;
/*
* 使用注解必须添加以下方式
*/
@Resource
public void setSessionFacotry(SessionFactory sessionFacotry) {
super.setSessionFactory(sessionFacotry);
}

/*
* 添加书籍操作(这里没有用到Criteria对象,该对象是用来做查询操作的)
*/
@SuppressWarnings("static-access")
public void AddBook(Book book){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
try {
tx = session.beginTransaction();
session.save(book);
tx.commit();
System.out.println("成功添加书籍信息!");
session.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("添加书籍信息失败!");
e.printStackTrace();
}
}

/*
* 查询所有书籍信息
*/
@SuppressWarnings({ "static-access", "unchecked" })
public List<Book> findAll(){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
list = cr.list();
System.out.println("查询所有书籍成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("查询所有书籍失败!");
e.printStackTrace();
}
return list;
}

/*
* 模糊查询
*/
public List<Book> findByMoHu(String name,String in){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
String na = "%"+name+"%";
String info = "%"+in+"%";
Criterion cl = Restrictions.like("name", na);
Criterion c2 = Restrictions.like("info", info);
cr.add(cl);                     //添加查询参数
cr.add(c2);                     //添加查询参数
list = cr.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

/*
* 数值匹配查询
*/
public List<Book> findByPrice(String name,double price){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
String na = "%"+name+"%";
Criterion cl = Restrictions.like("name", na);
Criterion c2 = Restrictions.eq("price", price);          //数值匹配
Criterion c3 = Restrictions.and(cl, c2);      //and的关系
cr.add(c3);                     //添加查询参数,可以多条件查询
list = cr.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

/*
* Order类对查询数据进行排序
*/
public List<Book> findByOrder(){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
//			cr.addOrder(Order.asc("id"));                 //根据id升序排序
cr.addOrder(Order.desc("id"));                //根据id降序排序
list = cr.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

/*
* 投影查询
*/
public List<Double> findByProject(){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Double> list = new ArrayList<Double>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
//           cr.setProjection(Projections.count("id"));           //统计书籍的总量
//            cr.setProjection(Projections.max("price"));            //统计书籍价格最大值
//            cr.setProjection(Projections.min("price"));           //统计书籍价格最小值
cr.setProjection(Projections.sum("price"));           //统计书籍价格的总数
list = (List<Double>)cr.list();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}

/*
* 离线查询
*/
public List<Book> findOffLine(){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
DetachedCriteria dc = DetachedCriteria.forClass(Book.class);   //查询对象
Criteria cr = dc.getExecutableCriteria(session);
list = cr.list();
System.out.println("查询所有书籍成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("查询所有书籍失败!");
e.printStackTrace();
}
return list;
}

/*
* 分页查询数据
*/
public List<Book> findPageList(int pageSize,int pageIndex){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
//            cr.setProjection(Projections.count("id"));           //统计书籍总记录数
//            Integer count= ((Integer)cr.uniqueResult()).intValue(); //看总记录数 转成Integer类型
//            System.out.println("总记录数:"+count);
cr.setFirstResult((pageIndex-1)*pageSize);
cr.setMaxResults(pageSize);
list = cr.list();
System.out.println("分页查询书籍成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("分页查询书籍失败!");
e.printStackTrace();
}
return list;
}

/*
* 条件查询
*/
public List<Book> findIsEmpty(){
getSession = new HibernateSessionFactory();
session = getSession.getSession();
List<Book> list = new ArrayList<Book>();
try {
Criteria cr = session.createCriteria(Book.class);    //查询对象
//			Criterion cl = Restrictions.isEmpty("price");        //查询没有价格的书籍
//			Criterion c2 = Restrictions.isNotEmpty("price");     //查询有价格的书籍
//			Criterion c3 = Restrictions.isNotNull("price");
Criterion c4 = Restrictions.gt("price", 70.0);       //查询价格大于70元的书籍
cr.add(c4);                                   //添加查询条件
list = cr.list();
System.out.println("查询所有书籍成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("查询所有书籍失败!");
e.printStackTrace();
}
return list;
}
}

#业务逻辑层

package com.sunline.biz;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.sunline.dao.BookDao;
import com.sunline.entity.Book;

@Service(value="bookBiz")
public class BookBiz {
@Autowired
@Qualifier("bookDao")            //使用@Qualifier注解来说明使用哪一个实现类
BookDao bookDao;

/*
* 添加书籍操作(这里没有用到Criteria对象,该对象是用来做查询操作的)
*/
public void AddBook(Book book){
bookDao.AddBook(book);
}

/*
* 查询所有书籍信息
*/
public List<Book> findAll(){
return bookDao.findAll();
}

/*
* 模糊查询
*/
public List<Book> findByMoHu(String name,String info){
return bookDao.findByMoHu(name,info);
}

/*
* 数值匹配查询
*/
public List<Book> findByPrice(String name,double price){
return bookDao.findByPrice(name, price);
}

/*
* Order类对查询数据进行排序
*/
public List<Book> findByOrder(){
return bookDao.findByOrder();
}

/*
* 投影查询
*/
public List<Double> findByProject(){
return bookDao.findByProject();
}

/*
* 离线查询
*/
public List<Book> findOffLine(){
return bookDao.findOffLine();
}

/*
* 分页查询数据
*/
public List<Book> findPageList(int pageSize,int pageIndex){
return bookDao.findPageList(pageSize, pageIndex);
}

/*
* 非空查询
*/
public List<Book> findIsEmpty(){
return bookDao.findIsEmpty();
}
}


#测试类


package com.sunline.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.junit.Test;
import com.sunline.biz.BookBiz;
import com.sunline.entity.Book;

@Transactional(propagation=Propagation.REQUIRED)
public class BookTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookBiz bookBiz = (BookBiz) ctx.getBean("bookBiz");
Book book = new Book();

/*
* 1.添加书籍测试
*/
book.setName("Hibernate深入浅出");
book.setPrice(56.0);
book.setInfo("一本介绍Hibernate框架的经典书籍");
bookBiz.AddBook(book);

/*
* 2.查询所有书籍信息
*/
List<Book> list = bookBiz.findAll();
for(Book bo : list){
System.out.println("所有书籍信息:" + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}

/*
* 3.模糊查询书籍
*/
String name ="Hibernate";
String info = "一本";
List<Book> list = bookBiz.findByMoHu(name,info);
if(list.size()<1){
System.out.println("没有你要查找的数据!");
}
else{
for(Book bo : list){
System.out.println("所有书籍信息: " + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}
}

/*
* 4.数值匹配查询
*/
String name ="Hibernate";
double price = 56;
List<Book> list = bookBiz.findByPrice(name, price);
if(list.size()<1){
System.out.println("没有你要查找的数据!");
}
else{
for(Book bo : list){
System.out.println("所有书籍信息: " + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}
}

/*
* 5.Order类对查询数据进行排序
*/
List<Book> list = bookBiz.findByOrder();
for(Book bo : list){
System.out.println("所有书籍信息:" +bo.getId()+" "+ bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}

/*
* 6.投影查询
*/
List<Double> list = bookBiz.findByProject();
for(Double a : list){
System.out.println("所有书籍总量为:" +a);
}

/*
* 7.离线查询
*/
List<Book> list = bookBiz.findOffLine();
for(Book bo : list){
System.out.println("所有书籍信息:" + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}

/*
* 8.分页查询
*/
List<Book> list = bookBiz.findPageList(3,2);
for(Book bo : list){
System.out.println("所有书籍信息:" + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}

/*
* 9.字段条件查询
*/
List<Book> list = bookBiz.findIsEmpty();
for(Book bo : list){
System.out.println("所有书籍信息:" + bo.getName()+" "+bo.getPrice()+" "+bo.getInfo());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: