Java框架之Hibernate实战篇2

1.cn.itcast.entity包里面:

(1)Customer.java

复制代码
package cn.itcast.entity;

import java.util.HashSet;
import java.util.Set;

public class Customer {
// 用户id
private Integer cid;

// 用户名称
private String custName;

// 用户级别
private String custLevel;

// 用户来源
private String custSource;

// 联系电话
private String custPhone;

// 手机
private String custMobile;

// 在客户实体类里面表示多个联系人,一个客户有多个联系人
// hibernate要求使用集合表示多的数据,使用set集合:
// import java.util.HashSet;import java.util.Set;
private Set setLinkMan = new HashSet();

public Set getSetLinkMan() {
    return setLinkMan;
}

public void setSetLinkMan(Set setLinkMan) {
    this.setLinkMan = setLinkMan;
}

public Integer getCid() {
    return cid;
}

public void setCid(Integer cid) {
    this.cid = cid;
}

public String getCustName() {
    return custName;
}

public void setCustName(String custName) {
    this.custName = custName;
}

public String getCustLevel() {
    return custLevel;
}

public void setCustLevel(String custLevel) {
    this.custLevel = custLevel;
}

public String getCustSource() {
    return custSource;
}

public void setCustSource(String custSource) {
    this.custSource = custSource;
}

public String getCustPhone() {
    return custPhone;
}

public void setCustPhone(String custPhone) {
    this.custPhone = custPhone;
}

public String getCustMobile() {
    return custMobile;
}

public void setCustMobile(String custMobile) {
    this.custMobile = custMobile;
}

}
复制代码
Customer.hbm.xml

复制代码

复制代码 (2)LinkMan.java

复制代码
package cn.itcast.entity;

public class LinkMan {
// 联系人编号(主键)
private Integer lkm_id;

// 联系人姓名
private String lkm_name;

// 联系人性别
private String lmk_gender;

// 联系人办公电话
private String lkm_phone;

// 在联系人实体类里面表示所有客户,一个联系人只能属于一个客户
// Customer customer=new Customer();
private Customer customer;

public Customer getCustomer() {
    return customer;
}

public void setCustomer(Customer customer) {
    this.customer = customer;
}

public Integer getLkm_id() {
    return lkm_id;
}

public void setLkm_id(Integer lkm_id) {
    this.lkm_id = lkm_id;
}

public String getLkm_name() {
    return lkm_name;
}

public void setLkm_name(String lkm_name) {
    this.lkm_name = lkm_name;
}

public String getLmk_gender() {
    return lmk_gender;
}

public void setLmk_gender(String lmk_gender) {
    this.lmk_gender = lmk_gender;
}

public String getLkm_phone() {
    return lkm_phone;
}

public void setLkm_phone(String lkm_phone) {
    this.lkm_phone = lkm_phone;
}

}
复制代码
LinkMan.hbm.xml

复制代码


复制代码 2.HibernateUtils包里面的HibernateUtils.java工具类,添加本地线程绑定的session的方法

复制代码
package cn.itcast.utils;

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

public class HibernateUtils {

// 加载核心配置文件,静态代码块实现
static Configuration cfg = null;

static SessionFactory sessionFactory = null;
static {
    cfg = new Configuration();
    cfg.configure();
    sessionFactory = cfg.buildSessionFactory();
}

// 提供返回与本地线程绑定的session的方法
public static Session getSessionObject() {
    return sessionFactory.getCurrentSession();
}

// 提供方法返回sessionFactory
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void main(String[] args) {

}

}
复制代码
3.Hibernate核心配置文件

复制代码

com.mysql.jdbc.Driver jdbc:mysql:///hibernate_test3 root root true true update org.hibernate.dialect.MySQLDialect thread 复制代码 4.Hibernatetest包

(1)HibernateOnetoMany.java

复制代码
package hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import cn.itcast.entity.LinkMan;
import cn.itcast.utils.HibernateUtils;

public class HibernateOnetoMany {

// 演示:一对多级联保存
@Test
public void testUpdate() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 添加一个客户,为这个客户添加一个联系人
        // 1 创建客户和联系人对象
        Customer customer = new Customer();
        customer.setCustLevel("vip");
        customer.setCustMobile("8888");
        customer.setCustName("橡果国际");
        customer.setCustPhone("18345782345");
        customer.setCustSource("上海");

        LinkMan linkman = new LinkMan();
        linkman.setLkm_name("王小卓");
        linkman.setLkm_phone("173456379876");
        linkman.setLmk_gender("女");

        // 2 在客户表示所有联系人,在联系人表示客户
        // 建立客户对象和联系人对象关系
        // 2.1 把联系人对象 放到客户对象的set集合里面
        customer.getSetLinkMan().add(linkman);
        // 2.2 把客户对象放到联系人里面
        linkman.setCustomer(customer);

        // 3 保存到数据库
        session.save(customer);
        session.save(linkman);

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

// 演示:一对多级联保存
@Test
public void testAddDemo2() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        Customer customer = new Customer();
        customer.setCustLevel("普通");
        customer.setCustName("奥克斯");
        customer.setCustPhone("18932222237");
        customer.setCustSource("北京");

        LinkMan linkman = new LinkMan();
        linkman.setLkm_name("陈小桥");
        linkman.setLkm_phone("15024324567");
        linkman.setLmk_gender("女");

        customer.getSetLinkMan().add(linkman);
        // 少了这句,linkman.setCustomer(customer);只执行t_customer表的insert语句
        // 添加它和session.save(linkman);,则t_linkman表中添加的新数据(陈小桥)才会加进去
        linkman.setCustomer(customer);

        // save() 保存要有哦!
        session.save(customer);
        session.save(linkman);

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        // sessionFactory.close();
        // session.close();
    }
}

// 演示:一对多级联删除
@Test
public void testDeleteDemo() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.根据id查询客户对象
        Customer customer = session.get(Customer.class, 12);
        // 2.调用删除方法
        session.delete(customer);
        // 3.提交事务
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }
}

// 演示:一对多修改
@Test
public void testUpdateDemo() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        // 1.根据id查询联系人,根据id查询客户
        Customer customer1 = session.get(Customer.class, 3);
        LinkMan linkman1 = session.get(LinkMan.class, 1);
        // 2.设置持久态对象值
        // i.把联系人放到客户里面
        customer1.getSetLinkMan().add(linkman1);
        // ii.把客户放到联系人里面
        linkman1.setCustomer(customer1);
        // 3.提交事务
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }

}

}
复制代码
(2)HibernateManytoMany.java

复制代码
package hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.manytomany.Role;
import cn.itcast.manytomany.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateManytoMany {
// 演示维护第三张表
@Test
public void testTable1() {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
sessionFactory = HibernateUtils.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

        // 让某个用户拥有某个角色
        // 1.查询
        User user1 = session.get(User.class, 2);
        Role role1 = session.get(Role.class, 2);
        // 2.放
        user1.getSetRole().add(role1);

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }
}

// 演示:维护第三张表
@Test
public void testTable2() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 让某个用户没有某个角色
        User user2 = session.get(User.class, 2);
        Role role2 = session.get(Role.class, 3);

        // 从用户里面把角色去掉
        user2.getSetRole().remove(role2);
        // 提交事务
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }

}

// 演示:多对多级联删除
@Test
public void testSave() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 添加两个用户,为每个用户相加两个角色
        // 1.创建对象
        User user3 = new User();
        user3.setUser_name("春花");
        user3.setUser_password("8766899");

        User user4 = new User();
        user4.setUser_name("mary");
        user4.setUser_password("456");

        Role role3 = new Role();
        role3.setRole_name("pig");
        role3.setRole_memo("粉色的");

        Role role4 = new Role();
        role4.setRole_name("秘书");
        role4.setRole_memo("秘书");

        Role role5 = new Role();
        role5.setRole_name("保安");
        role5.setRole_memo("保安");

        // 2.建立关系,把角色放到用户里面
        user3.getSetRole().add(role3);
        user3.getSetRole().add(role4);

        user4.getSetRole().add(role4);
        user4.getSetRole().add(role5);

        // 3.保存
        session.save(user3);
        session.save(user4);

        // 4.提交事务
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }
}

// 演示:多对多级联保存
@Test
public void testDelete() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        User user5 = session.get(User.class, 1);
        session.delete(user5);
        // 提交事务
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        // sessionFactory.close();
    }
}

}
复制代码
5.cn.itcast.manytomany包

(1)Role.java

复制代码
package cn.itcast.manytomany;

import java.util.HashSet;
import java.util.Set;

public class Role {

private Integer role_id;

private String role_name;

private String role_memo;

// 一个角色有多个客户
private Set setUser = new HashSet();

public Set getSetUser() {
    return setUser;
}

public void setSetUser(Set setUser) {
    this.setUser = setUser;
}

public Integer getRole_id() {
    return role_id;
}

public void setRole_id(Integer role_id) {
    this.role_id = role_id;
}

public String getRole_name() {
    return role_name;
}

public void setRole_name(String role_name) {
    this.role_name = role_name;
}

public String getRole_memo() {
    return role_memo;
}

public void setRole_memo(String role_memo) {
    this.role_memo = role_memo;
}

}
复制代码
Role.hbm.xml

复制代码

复制代码 (2)User.java

复制代码
package cn.itcast.manytomany;

import java.util.HashSet;
import java.util.Set;

public class User {

private Integer user_id;

private String user_name;

private String user_password;

// 一个用户可以有多个角色
private Set setRole = new HashSet();

public Set getSetRole() {
    return setRole;
}

public void setSetRole(Set setRole) {
    this.setRole = setRole;
}

public Integer getUser_id() {
    return user_id;
}

public void setUser_id(Integer user_id) {
    this.user_id = user_id;
}

public String getUser_name() {
    return user_name;
}

public void setUser_name(String user_name) {
    this.user_name = user_name;
}

public String getUser_password() {
    return user_password;
}

public void setUser_password(String user_password) {
    this.user_password = user_password;
}

}
复制代码
User.hbm.xml

复制代码

复制代码 第四篇:HQL、QBC 、查询、检索策略、批量抓取等 相关练习篇

1.cn.itcast.entity包

(1)Cutomer.java

复制代码
package cn.itcast.entity;

import java.util.HashSet;
import java.util.Set;

public class Customer {
private Integer cid;

private String custName;

private String custLevel;

private String custSource;

private String custPhone;

private String custMobile;

// 在客户实体类里面表示多个联系人,一个客户有多个联系人
private Set setLinkMan = new HashSet();

public Set getSetLinkMan() {
    return setLinkMan;
}

public void setSetLinkMan(Set setLinkMan) {
    this.setLinkMan = setLinkMan;
}

public Integer getCid() {
    return cid;
}

public void setCid(Integer cid) {
    this.cid = cid;
}

public String getCustName() {
    return custName;
}

public void setCustName(String custName) {
    this.custName = custName;
}

public String getCustLevel() {
    return custLevel;
}

public void setCustLevel(String custLevel) {
    this.custLevel = custLevel;
}

public String getCustSource() {
    return custSource;
}

public void setCustSource(String custSource) {
    this.custSource = custSource;
}

public String getCustPhone() {
    return custPhone;
}

public void setCustPhone(String custPhone) {
    this.custPhone = custPhone;
}

public String getCustMobile() {
    return custMobile;
}

public void setCustMobile(String custMobile) {
    this.custMobile = custMobile;
}

}
复制代码
Customer.hbm.xml

复制代码



















复制代码
(2).LinkMan.java

复制代码
package cn.itcast.entity;

public class LinkMan {
private Integer lkm_id; // 联系人编号(主键)

private String lkm_name;// 联系人姓名

private String lkm_gender;// 联系人性别

private String lkm_phone;// 联系人办公电话

// 在联系人实体类中表示所属客户,一个联系人只能有一个客户
private Customer customer;

public Customer getCustomer() {
    return customer;
}

public void setCustomer(Customer customer) {
    this.customer = customer;
}

public Integer getLkm_id() {
    return lkm_id;
}

public void setLkm_id(Integer lkm_id) {
    this.lkm_id = lkm_id;
}

public String getLkm_name() {
    return lkm_name;
}

public void setLkm_name(String lkm_name) {
    this.lkm_name = lkm_name;
}

public String getLkm_gender() {
    return lkm_gender;
}

public void setLkm_gender(String lkm_gender) {
    this.lkm_gender = lkm_gender;
}

public String getLkm_phone() {
    return lkm_phone;
}

public void setLkm_phone(String lkm_phone) {
    this.lkm_phone = lkm_phone;
}

}
复制代码
LinkMan.hbm.xml

复制代码














复制代码
2.utils包(同上)

HibernateUtils.java

复制代码
package ustils;

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

public class HibernateUtils {

static Configuration cfg = null;

static SessionFactory sessionFactory = null;
static {
    cfg = new Configuration();
    cfg.configure();
    sessionFactory = cfg.buildSessionFactory();
}

public static Session getSessionobject() {
    return sessionFactory.getCurrentSession();
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

public static void main(String[] args) {

}

}
复制代码
3.Hibernate核心配置文件

复制代码



org.hibernate.dialect.MySQLDialect
com.mysql.jdbc.Driver
jdbc:mysql:///hibernate_test4
root
root

true
true
update
thread





复制代码
4.cn.itcast.hibernantetest包

(1)HibernateDemo.java

复制代码
package cn.itcast.hibernantetest;

import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import cn.itcast.entity.LinkMan;
import ustils.HibernateUtils;

public class HibernateDemo {

// 演示对象导航查询
@Test
public void testSelect1() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;

    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.查询cid=1客户
        Customer customer = session.get(Customer.class, 1);
        // 2.再查询这个客户里面的所有联系人(此时,得到set集合,没有发送语句)
        Set linkman = customer.getSetLinkMan();

        // 发送了语句
        System.out.println(linkman.size());

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

// 演示检索策略
@Test
public void testSelect2() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;

    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 根据cid=1客户
        // 执行get方法之后是否发送sql语句
        // 调用get方法马上发送sql语句查询数据库
        // Customer customer = session.get(Customer.class, 1);
        // System.out.println(customer.getCid());
        /*
         * 1 调用load方法之后,不会马上发送sql语句 (1)返回对象里面只有 id值
         * 
         * 2 得到对象里面不是id的其他值时候才会发送语句
         */
        Customer customer = session.load(Customer.class, 1);
        System.out.println(customer.getCid());
        System.out.println(customer.getCustName());

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

// 演示批量抓取
@Test
public void testSelect3() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;

    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 查询所有客户
        Criteria criteria = session.createCriteria(Customer.class);
        // 得到每个客户里面所有的联系人
        List list = criteria.list();

        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
            // 每个客户里面的所有联系人
            Set setlinkman = customer.getSetLinkMan();
            for (LinkMan linkMan : setlinkman) {
                System.out.println((linkMan.getLkm_id() + "::" + linkMan.getLkm_name()));
            }
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

}
复制代码
(2)HibernateHQL.java

复制代码
package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.entity.Customer;
import ustils.HibernateUtils;

public class HibernateHQL {

// 演示查询所有
@Test
public void testSelect1() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        Query query = session.createQuery("from Customer");
        // 2.调用方法得到结果
        List list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示条件查询
@Test
public void testSelect2() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        // SELECT *FROM t_customer WHERE cid=? AND custName=?
        Query query = session.createQuery("from Customer c where c.cid=? and c.custName=?");
        // 2.设置条件
        // 向?里面设置值
        // setParameter方法两个参数
        // 第一个参数:int类型是?位置,?位置从0开始
        // 第二个参数:具体参数值
        // 设置第一个?值
        query.setParameter(0, 1);
        // 设置第二个?值
        query.setParameter(1, "百度");
        // 3.调用方法得到结果
        List list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示条件查询-模糊查询
@Test
public void testSelect3() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        Query query = session.createQuery("from Customer c where c.custName like ?");
        // 2.设置?的值
        query.setParameter(0, "%蒂%");
        // 3.调用方法得到结果
        List list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:排序查询
@Test
public void testSelect4() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        Query query = session.createQuery("from Customer order by cid desc");
        // 2.调用方法得到结果
        List list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:分页查询
@Test
public void testSelect5() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        // 写查询所有的语句
        Query query = session.createQuery("from Customer");
        // 2.设置分页数据
        // 2.1.设置开始位置
        query.setFirstResult(3);
        // 2.2.设置每页记录数
        query.setMaxResults(3);
        // 3.调用方法得到结果
        List list = query.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:投影查询
@Test
public void testSelect6() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        Query query = session.createQuery("select custLevel from Customer");
        // 2.调用方法得到结果
        List list = query.list();
        for (Object object : list) {
            System.out.println(object);
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:聚集函数的使用
@Test
public void testSelect7() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建query对象
        Query query = session.createQuery("select count(*) from Customer");
        // 2.调用方法得到结果
        // query对象里面有方法,直接返回对象形式
        Object obj = query.uniqueResult();
        // 返回int类型
        // int count=(int)obj;

        // 首先把object变成long类型,再变成int类型
        Long lobj = (Long) obj;
        int count = lobj.intValue();
        System.out.println(count);

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}
 
  

}
复制代码
(3)HibernateQBC.java

复制代码
package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import cn.itcast.entity.Customer;
import ustils.HibernateUtils;

public class HibernateQBC {

// 演示:查询所有
@Test
public void testSelect1() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建对象
        Criteria criteria = session.createCriteria(Customer.class);
        // 2.调用方法得到结果
        List list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:条件查询
@Test
public void testSelect2() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建criteria对象
        Criteria criteria = session.createCriteria(Customer.class);
        // 2.使用criteria对象里面的方法设置条件值
        // 首先使用add方法,表示设置条件值
        // 在add方法里面使用类的方法实现条件设置
        // 类似于cid=?
        // criteria.add(Restrictions.eq("cid", 1));
        // criteria.add(Restrictions.eq("custName", "玛莎拉蒂"));
        // 上面是eq,下面是like
        criteria.add(Restrictions.like("custName", "%百%"));
        // 3.调用方法得到结果
        List list = criteria.list();

        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:排序查询
@Test
public void testSelect3() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建对象
        Criteria criteria = session.createCriteria(Customer.class);
        // 2.设置对哪个属性进行排序,设置排序规则
        criteria.addOrder(Order.desc("cid"));
        // 3.调用方法,得到结果
        List list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:分页查询
@Test
public void testSelect4() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建对象
        Criteria criteria = session.createCriteria(Customer.class);
        // 2.设置分页,起始和记录数
        criteria.setFirstResult(3);
        criteria.setMaxResults(3);
        // 3.调用方法得到结果
        List list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:统计查询
@Test
public void testSelect5() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建对象
        Criteria criteria = session.createCriteria(Customer.class);
        // 2.设置操作
        criteria.setProjection(Projections.rowCount());
        // 3.调用方法得到结果
        Object obj = criteria.uniqueResult();
        Long lobj = (Long) obj;
        int count = lobj.intValue();
        System.out.println(count);

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

// 演示:离线查询
@Test
public void testSelect6() {

    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 1.创建对象
        // Criteria criteria = session.createCriteria(Customer.class);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
        // 2.最终执行时候才需要得到session
        Criteria criteria = detachedCriteria.getExecutableCriteria(session);
        List list = criteria.list();
        for (Customer customer : list) {
            System.out.println(customer.getCid() + "::" + customer.getCustName());
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }

}

}
复制代码
(4)HibernateManyTable.java

复制代码
package cn.itcast.hibernantetest;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import ustils.HibernateUtils;

public class HibernateManyTable {

// 演示hql内连接查询(2种)
@Test
public void testSelect1() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 内连接的list返回的是数组的形式;迫切内外连接的list放回的是对象的形式
        // Query query = session.createQuery("from Customer c inner join
        // c.setLinkMan");
        // List list = query.list();

        Query query = session.createQuery("from Customer c inner join fetch c.setLinkMan");
        List list = query.list();

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

// 演示hql外连接查询(3种)
@Test
public void testSelect2() {
    SessionFactory sessionFactory = null;
    Session session = null;
    Transaction tx = null;
    try {
        sessionFactory = HibernateUtils.getSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        // 左外连接的list返回的是数组的形式;迫切左外连接的list放回的是对象的形式
        // Query query = session.createQuery("from Customer c left outer
        // join c.setLinkMan");
        // List list = query.list();

        // Query query = session.createQuery("from Customer c left outer
        // join fetch c.setLinkMan");
        // List list = query.list();

        // 右外连接,没有迫切右外连接
        Query query = session.createQuery("from Customer c right outer join fetch c.setLinkMan");
        List list = query.list();

        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    } finally {
        session.close();
        sessionFactory.close();
    }
}

}
深圳网站建设www.sz886.com

你可能感兴趣的:(Java框架之Hibernate实战篇2)