6Hibernate进阶----青软S2SH(笔记)

关于关联关系的配置,用注解配置如下(这里引用的jar包是javax.persistence)

//    @ManyToOne(fetch=FetchType.LAZY)
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="supplier_id",nullable=true)
    private Supplier supplier;

用xml文件配置如下,这个跟注解配置有些不同,就不详解了,反正我也不会用xml配置

例子

/* 使用HQL对查询结果按照Customer的userName进行降序排序 */
    public static void orderByUserNameByDesc_HQL() {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.编写hql语句
        String hql = "from Customer c order by c.userName desc";
        // 3.以HQL作为参数,调用session的createQuery()方法创建Query对象
        Query query = session.createQuery(hql);
        // 4.调用query对象的list()等方法遍历结果
        List<Customer> list = query.list();
        // 打印结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

一个使用hql来进行动态查询的使用方法(用map存储参数)

@SuppressWarnings("unchecked")public long getXXXCount(Map<String,String> conditions) throws Exception {
        String hql = "select count(u.id)";
        Map<String,Object> valMap = createPartHql(hql,conditions);
        hql = (String)valMap.get("hql");
        valMap.remove("hql");

        Query query = getQueryFromMapAndHql(valMap,hql);
        return (long)query.list().get(0);
    }
private static Map<String,Object> createPartHql(String hql,Map<String,String> conditions){
        Map<String,Object> valMap = new HashMap<>();
        boolean conditionsIsNull = true;
        for(Map.Entry<String, String> entry:conditions.entrySet()){
            if(StringUtils.isNotEmpty(entry.getValue()))
                conditionsIsNull = false;
        }       hql = hql+" from xxxx u where u.deleteFlg = 0";

            if(StringUtils.isNotEmpty(conditions.get("roleType"))){
                hql = hql+" and u.roleType = :roleType";
                valMap.put("roleType", Integer.parseInt(conditions.get("roleType")));
            }
            if(StringUtils.isNotEmpty(conditions.get("loginId"))){
                hql = hql+" and u.loginId like :loginId";
                valMap.put("loginId", "%"+conditions.get("loginId")+"%");
            }
        valMap.put("hql", hql);
        return valMap;
    }

---------------------------
public Query getQueryFromMapAndHql(Map<String,Object> FieldsMap,String hql){
        Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
        for(Map.Entry<String, Object> entry : FieldsMap.entrySet()){
            query.setParameter(entry.getKey(), entry.getValue());
        }
        return query;
    }
    public Query getQueryFromMapAndHql(Map<String,String> FieldsMap,Query query){
        for(Map.Entry<String, String> entry : FieldsMap.entrySet()){
            query.setParameter(entry.getKey(), entry.getValue()+"");
        }
        return query;
    }

其他示例:

package com.qst.chapter06.demo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.qst.chapter06.pojos.Customer;
import com.qst.chapter06.pojos.Order;
import com.qst.chapter06.pojos.Product;
import com.qst.chapter06.util.HibernateUtils;

public class HqlCriteriaBusinessDemo {
    public static void main(String[] args) {
        // findCustomersByAddress_HQL("青岛市");
        // findCustomersByAddress_QBC("青岛市");
        // orderByUserNameByDesc_HQL();
        // orderByUserNameByDesc_QBC();
        // 第2页,每页3条记录
        // List<Customer> list=listPageCustomer_HQL(2,3);
        // List<Customer> list = listPageCustomer_QBC(2, 3);
        // 打印结果
        // for (Customer c : list) {
        // System.out.println(c.getId() + "\t" + c.getUserName());
        // }
        // Customer c = findOneCustomer_HQL();
        // Customer c = findOneCustomer_QBC();
        // System.out.println(c.getId() + "\t" + c.getUserName());
        // List<Customer> list=findCustomersByName1("zhangsan1");
        // List<Customer> list=findCustomersByName2("zhangsan1");
        // //打印结果
        // for (Customer c : list) {
        // System.out.println(c.getId() + "\t" + c.getUserName());
        // }
        // findCustomerByJoin();
        // findCustomerByFetchJoin();
        // findCustomerByLeftJoin();
        // findCustomerByLeftFetch();
        // groupByCustomer();
        // printOrders_HQL();
        // printOrders_QBC();
        // //////////////////////////////////////////////
        // List<Product> listProduct = findProductsByHQL("打印机", 560.0);
        // List<Product> listProduct = findProductsByCriteria("打印机", 560.0);
        // List<Product> listProduct= findProductsByQBE(product);
        // Product product=new Product();
        // product.setName("打印机");
        // product.setPrice(560.0);
        // //////////////////////////////////////////////
//        DetachedCriteria cri = DetachedCriteria.forClass(Product.class);
//        // 根据用户的动态查询条件,创建DetachedCriteria对象
//        cri.add(Restrictions.ilike("name", "打印机", MatchMode.ANYWHERE));
//        cri.add(Restrictions.eq("price", 560.0));
//        List<Product> listProduct = findProducts(cri);
//        for (Product p : listProduct) {
//            System.out.println(p.getId() + "\t" + p.getName() + "\t"
//                    + p.getPrice() + "\t" + p.getDescription());
//        }
        /////////////////////////////////////////////////////////////
        findProductsBySubQuerys();

    }

    /* 使用HQL检索根据地址查询Customer */
    public static void findCustomersByAddress_HQL(String address) {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.编写hql语句
        String hql = "from Customer c where c.address = :address";
        // // 3.以HQL作为参数,调用session的createQuery()方法创建Query对象
        // Query query = session.createQuery(hql);
        // // 4.调用Query对象的setXXX()方法为参数赋值
        // query.setString("address", address);
        // // 5.调用Query对象的list()等方法得到查询结果
        // List<Customer> list = query.list();
        // Query对象匿名方式
        List<Customer> list = session.createQuery(hql)
                .setString("address", address).list();
        // 遍历输出结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

    /* 使用QBC检索根据地址查询Customer */
    public static void findCustomersByAddress_QBC(String address) {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.以Customer的Class对象作为参数,创建Criteria对象
        Criteria critera = session.createCriteria(Customer.class);
        // // 3.调用Criteria对象的add()方法,增加Criterion查询条件
        // critera.add(Restrictions.eq("address", address));
        // // 4.执行Criteria的list()方法返回查询结果
        // List<Customer> list = critera.list();
        // Criteria对象匿名方式
        List<Customer> list = session.createCriteria(Customer.class)
                .add(Restrictions.eq("address", address)).list();
        // 遍历输出结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

    /* 使用HQL对查询结果按照Customer的userName进行降序排序 */
    public static void orderByUserNameByDesc_HQL() {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.编写hql语句
        String hql = "from Customer c order by c.userName desc";
        // 3.以HQL作为参数,调用session的createQuery()方法创建Query对象
        Query query = session.createQuery(hql);
        // 4.调用query对象的list()等方法遍历结果
        List<Customer> list = query.list();
        // 打印结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

    /* 使用QBC检索中的Order类对查询结果按照Customer的userName进行降序排序 */
    public static void orderByUserNameByDesc_QBC() {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.以Customer的Class对象作为参数,创建Criteria对象
        Criteria critera = session.createCriteria(Customer.class);
        // 3.调用criteria对象的addOrder()方法条件排序规则
        critera.addOrder(org.hibernate.criterion.Order.desc("userName"));
        List<Customer> list = critera.list();
        // 打印结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

    /* 使用HQL分页查询Customer信息 */
    public static List<Customer> listPageCustomer_HQL(int pageNo, int perPageNum) {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer c order by c.userName desc";
        Query query = session.createQuery(hql);
        query.setFirstResult((pageNo - 1) * perPageNum);
        query.setMaxResults(perPageNum);
        List<Customer> list = query.list();
        return list;
    }

    /* 使用QBC分页查询Customer信息 */
    public static List<Customer> listPageCustomer_QBC(int pageNo, int perPageNum) {
        Session session = HibernateUtils.getSession();
        Criteria criteria = session.createCriteria(Customer.class);
        criteria.setFirstResult((pageNo - 1) * perPageNum);
        criteria.setMaxResults(perPageNum);
        List<Customer> list = criteria.list();
        return list;
    }

    /* 利用HQL检索单个Customer对象 */
    public static Customer findOneCustomer_HQL() {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer c order by c.userName desc";
        Customer customer = (Customer) session.createQuery(hql)
                .setMaxResults(1).uniqueResult();
        return customer;
    }

    /* 利用QBC检索单个Customer对象 */
    public static Customer findOneCustomer_QBC() {
        Session session = HibernateUtils.getSession();
        Customer customer = (Customer) session.createCriteria(Customer.class)
                .addOrder(org.hibernate.criterion.Order.desc("userName"))
                .setMaxResults(1).uniqueResult();
        return customer;
    }

    /* HQL检索3月份的订单对象 */
    public static void printOrders_HQL() {
        Session session = HibernateUtils.getSession();
        // HQL检索日期在指定范围之内
        String hql = "from Order o where o.date between ? and ?";
        // 创建一个日期格式类,用于格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        try {

            List<Order> list = session.createQuery(hql)
                    .setParameter(0, dateFormat.parse("2015-03-01 00:00:00"))
                    .setParameter(1, dateFormat.parse("2015-03-31 23:59:59"))
                    .list();

            // 打印结果
            for (Order o : list) {
                System.out.println(o.getId() + "\t" + o.getDate());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /* QBC检索3月份的订单对象 */
    public static void printOrders_QBC() {
        Session session = HibernateUtils.getSession();
        // 创建一个日期格式类,用于格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        try {
            // QBC检索
            List<Order> list = session
                    .createCriteria(Order.class)
                    .add(Restrictions.between("date",
                            dateFormat.parse("2015-03-01 00:00:00"),
                            dateFormat.parse("2015-03-31 23:59:59"))).list();
            // 打印结果
            for (Order o : list) {
                System.out.println(o.getId() + "\t" + o.getDate());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static List<Customer> findCustomersByName1(String name) {
        // 获取Session对象
        Session session = HibernateUtils.getSession();
        // 创建HQL
        String hql = "from Customer as c where c.userName = :name";
        Query query = session.createQuery(hql);
        // 按照参数名字进行绑定
        query.setString("name", name);
        return query.list();
    }

    public static List<Customer> findCustomersByName2(String name) {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer as c where c.userName = ?";
        Query query = session.createQuery(hql);
        // 按照参数位置进行绑定
        query.setString(0, name);
        return query.list();
    }

    /* HQL内连接 */
    public static void findCustomerByJoin() {
        Session session = HibernateUtils.getSession();
        // 使用HQL进行内连接
        String hql = "from Customer c inner join c.orders o where c.userName like :name";
        Query query = session.createQuery(hql);
        query.setString("name", "z%");
        List<Object[]> list = query.list();
        for (Object[] objs : list) {
            Customer customer = (Customer) objs[0];
            System.out.print(customer.getId() + " * " + customer.getUserName()
                    + " * ");
            Order order = (Order) objs[1];
            System.out.print(order.getOrderNo() + " * ");
            System.out.print(order.getDate());
            System.out.println();
        }

    }

    /* HQL预先抓取内连接 */
    public static void findCustomerByFetchJoin() {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer c inner join fetch c.orders o where c.userName like :name";
        Query query = session.createQuery(hql);
        query.setString("name", "z%");
        List<Customer> list = query.list();
        // 使用HashSet过滤重复元素
        HashSet<Customer> set = new HashSet<Customer>(list);
        for (Customer customer : set) {
            System.out.print(customer.getId() + " " + customer.getUserName()
                    + " ");
            for (Order order : customer.getOrders()) {
                System.out.print(order.getOrderNo() + " ");
            }
            System.out.println();
        }
    }

    /* HQL左外连接 */
    public static void findCustomerByLeftJoin() {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer c left outer join  c.orders o where c.address = ?";
        Query query = session.createQuery(hql);
        query.setString(0, "青岛市");
        List<Object[]> list = query.list();
        for (Object[] objs : list) {
            Customer customer = (Customer) objs[0];
            System.out.print(customer.getId() + " " + customer.getUserName()
                    + " ");
            Order order = (Order) objs[1];
            if (objs[1] != null)
                System.out.print(order.getOrderNo());
            System.out.println();
        }

    }

    /* 预先抓取左外连接 */
    public static void findCustomerByLeftFetch() {
        Session session = HibernateUtils.getSession();
        String hql = "from Customer c left join fetch c.orders  where c.address = ?";
        Query query = session.createQuery(hql);
        query.setString(0, "青岛市");
        List<Customer> list = query.list();
        HashSet<Customer> set = new HashSet<Customer>(list);
        for (Customer customer : set) {
            System.out.print(customer.getId() + " " + customer.getUserName()
                    + " ");
            for (Order order : customer.getOrders()) {
                System.out.print(order.getOrderNo() + " ");
            }
            System.out.println();
        }

    }

    public static void groupByCustomer() {
        Session session = HibernateUtils.getSession();
        String hql = "select c.userName,count(o) from Customer c left join c.orders o group by c.id";
        Query query = session.createQuery(hql);
        List<Object[]> list = query.list();
        for (Object[] objs : list) {
            String username = (String) objs[0];
            Long count = (Long) objs[1];
            System.out.println("用户名: " + username + "  订单数:" + count);
        }

    }

    public static List<Product> findProductsByHQL(String name, Double price) {

        Session session = HibernateUtils.getSession();
        StringBuffer buffer = new StringBuffer();
        // 生成基础SQL
        buffer.append("from Product p where 1=1");
        // 如果name满足条件,则加入语句中
        if (name != null) {
            buffer.append(" and lower(p.name) like :name");
        }
        // 如果age满足条件,则加入语句中
        if (price != null && price != 0) {
            buffer.append(" and p.price = :price");
        }
        Query query = session.createQuery(buffer.toString());
        if (name != null) {
            query.setString("name", "%" + name.toLowerCase() + "%");
        }
        if (price != null && price != 0) {
            query.setDouble("price", price);
        }
        return query.list();

    }

    public static List<Product> findProductsByCriteria(String name, Double price) {

        Session session = HibernateUtils.getSession();
        Criteria criteria = session.createCriteria(Product.class);
        if (name != null) {
            criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
        }
        if (price != null && price != 0) {
            criteria.add(Restrictions.eq("price", price));
        }
        return criteria.list();
    }

    public static List<Product> findProductsByQBE(Product product) {

        Session session = HibernateUtils.getSession();
        /* customer为样本对象,根据查询条件创建的对象 */
        Example example = Example.create(product)// 根据样本对象创建Example对象
                .enableLike(MatchMode.ANYWHERE)// 对所有String类型的字段进行模糊匹配
                .excludeNone()// 不把为空的字段加入where子句中
                .excludeZeroes()// 不把值为0的字段加入where子句中
                .ignoreCase();// 忽略所有String类型字段的大小写
        Criteria criteria = session.createCriteria(Product.class);
        criteria.add(example);
        return criteria.list();
    }

    // 在业务逻辑层 把DetachedCriteria对象与Session对象绑定,并返回查询结果
    public static List<Product> findProducts(DetachedCriteria detachedCriteria) {
        Session session = HibernateUtils.getSession();
        Criteria criteria = detachedCriteria.getExecutableCriteria(session);
        return criteria.list();
    }

    public static void findProductsBySubQuerys() {

        Session session = HibernateUtils.getSession();
        String hql = "from Product p where p.price=(select p1.price from Product p1 where p1.name=:name) and p.name!=:name";
        Query query = session.createQuery(hql);
        query.setString("name", "打印机");
        List<Product> list = query.list();
        for (Product p : list) {
            System.out.println(p.getId() + "\t" + p.getName() + "\t"
                    + p.getPrice() + "\t" + p.getDescription());
        }
    }
}

增加查询条件的方法如下

.add(Restrictions.eq("address", address))

/* 使用QBC检索中的Order类对查询结果按照Customer的userName进行降序排序 */
    public static void orderByUserNameByDesc_QBC() {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.以Customer的Class对象作为参数,创建Criteria对象
        Criteria critera = session.createCriteria(Customer.class);
        // 3.调用criteria对象的addOrder()方法条件排序规则
        critera.addOrder(org.hibernate.criterion.Order.desc("userName"));
        List<Customer> list = critera.list();
        // 打印结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }
/* 使用QBC检索根据地址查询Customer */
    public static void findCustomersByAddress_QBC(String address) {
        // 1.获取session对象
        Session session = HibernateUtils.getSession();
        // 2.以Customer的Class对象作为参数,创建Criteria对象
        Criteria critera = session.createCriteria(Customer.class);
        // // 3.调用Criteria对象的add()方法,增加Criterion查询条件
        // critera.add(Restrictions.eq("address", address));
        // // 4.执行Criteria的list()方法返回查询结果
        // List<Customer> list = critera.list();
        // Criteria对象匿名方式
        List<Customer> list = session.createCriteria(Customer.class)
                .add(Restrictions.eq("address", address)).list();
        // 遍历输出结果
        for (Customer c : list) {
            System.out.println(c.getId() + "\t" + c.getUserName());
        }
    }

时间: 2024-12-31 12:19:06

6Hibernate进阶----青软S2SH(笔记)的相关文章

5Hibernate入门----青软S2SH(笔记)

这里有个问题,就是这本书第五章的示例代码中的hibernate的jar包有问题,各种找不到类,把lib下的包后换成第六章里的包就好了. 换成5.1的就好了,而且如果只是简单使用hibernate的话,那么,jar包用完整版的required目录里那几个就好,如下图 由于这个教程是以hibernate4.3为基础的,比较老,所以有些地方不太对,另外整理了一篇5Hibernate配置及使用方法----青软S2SH(笔记)

GIFT-EMS礼记----青软S2SH(笔记)

这个S2SH的项目,是这本书的一个贯穿项目,所以这里要记录一下, 看这个项目有两个目的: 1.借助这个项目,学习一下S2SH的综合配置及使用 2.借助这个项目练习一下如何做需求分析和项目架构设计. POJO设计,实际就是数据库设计,在确定了使用的框架之后,,数据库设计是最重要的设计.  这个项目的目录层次设计的并不很好,按说,用户使用的部分,和后台管理部分,这是要分开的

7Hibernate高级----青软S2SH(笔记)

5Hibernate配置及使用方法----青软S2SH(笔记)

关于hibernate的简单配置,先看结构图,我们需要 1.还要弄一下需要的 jar包. 2.配置两个文件(hibernate配置文件和映射文件),不过映射文件可以用注解替代. 3.写一个pojo类,写一个示例demo 1.关于jar包,下载网站http://hibernate.org/orm/downloads/ 下载的完整版的压缩包,解压后,lib里有一个required,这个基本就是需要的jar包,如果有别的需求再另加. 另外,这里边没有连接数据库的包(比如连接mysql的mysql-co

2Struts2配置----青软S2SH(笔记)

实例的文件目录如下:两个配置文件(web.xml和struts.xml),一个UserAction.java,三个jsp. 1.配置Struts2应用环境: 下载Struts2的jar包,官网是:http://struts.apache.org/download.cgi 下载完整版,里边的lib文件夹里有struts2的核心类库和依赖的第三方类库. 新建立一个web项目,把这些类库导入到项目的lib文件夹中. 一般来说,只要导入基本的几个jar包就好了,其他的需要了再导入,基础jar包如下几个:

2Struts2基础----青软S2SH(笔记)

4Struts2标签库----青软S2SH(笔记)

这里弄错了,这一堆属性是<datetimepicker>标签的,不是<doubleselect>标签的 输出错误信息这个不错,挺方便的. 这个树形标签,也用了好多网络,分析如下 <tree>在浏览器生成的代码如下 <tree>标签在浏览器生成的代码 这个树形菜单自己写js也是可以实现的,虽然麻烦点,如下面这个例子, http://www.2cto.com/kf/201210/159436.html 总体来说,对于上面这些表单标签中的特殊功能标签,比如<

“青软杯”安徽科技学院第六届程序设计大赛_专业组

Contest - "青软杯"安徽科技学院第六届程序设计大赛_专业组 Start time:  2015-04-18 08:00:00.0  End time:  2015-04-18 12:00:00.0 Current System Time:  2015-04-21 00:07:42.57  Contest Status:   Ended 关于举办"青软杯"安徽科技学院 第六届程序设计大赛通知 ACM 国际大学生程序设计竞赛 (International Co

软考笔记之存储管理

软考随堂笔记 考点1 实存管理 考点2 虚存管理 程序的装入(重定位)(将逻辑地址转换成物理地址) 静态重定位:静态重定位是在虚空间程序执行之前由装配程序完成地址影射工作. 动态重定位:动态重定位是在程序执行过程中,在CPU访问内存之前,将要访问的程序或数据地址转换为内存地址. 实存管理 存储管理的任务是存储空间的分配与回收.在现代操作系统中通常有单一连续分配(静态).固定分区分配(静态).可变分区分配(动态)三种分配方式: 单一连续分配(静态):不分区,所有用户空间给某个进程或作业.同一时间只