Java框架之Hibernate实战篇

2020-06-09 16:02:02来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java框架之Hibernate实战篇

从零开始Hibernate实战篇:(四篇实战代码,循序渐进,注意事项和学习内容在代码注释里面,面向有一定基础的同学使用)

第一篇:基础篇(搭建)

Hibernate开发基本步骤:

1.导入jar包(hibernate-release-5.0.7.Final\lib的文件里面去找所需要的jar包)

2.写实体类+实体类的映射文件

User.java

/**
 * Project Name:hibernate_demo
 * File Name:User.java
 * Package Name:cn.itcast.entity
 *
*/

package cn.itcast.entity;

/**
 * @author zhouP
 * @version
 * @see
 */
public class User {

    // hibernate要求实体类有一个属性唯一的
    private int uid;

    private String username;

    private String password;

    private String address;

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getUid() {
        return uid;
    }

}

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- 1.配置类和表对应 class属性:实体类全路径(类路径) table属性:数据库表名称 -->
    <class name="cn.itcast.entity.User" table="t_user">
        <!-- 2.配置实体类id与表id对应 hibernate要求实体类有一个属性唯一值 hibernate要求表有字段作为唯一值 -->
        <!-- id标签 name属性:实体类里面id属性名称 column属性:生成的表字段名称 -->
        <id name="uid" column="uid">
            <!-- 配置数据库表id的增长策略 native:主键自动增长 -->
            <generator class="native"></generator>
        </id>

        <!-- 配置其他属性和表字段对应 name属性:实体类属性名称 column属性:生成表字段名称 -->
        <property name="username" column="username"></property>
        <property name="password" column="password"></property>
        <property name="address" column="address"></property>
        
    </class>

</hibernate-mapping>

3.Hibernate核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- 第一部分:配置数据库信息(必须的) -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<!-- 第二部分:配置hibernate信息(可选的) -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 两个重要配置ddl、dialect(分页时用) -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- 第三部分:把映射文件放到核心配置文件中(必须的)(文件路径) -->
<mapping resource="cn/itcast/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

4.编写Hibernate工具类

package cn.itcast.utils;

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

public class HibernateUtils {

    // 创建sessionFactory的过程,特别浪费资源,建议一个项目一般创建一个sessionFactory对象
    // static Configuration cfg = null;

    static SessionFactory sessionFactory = null;
    // 静态代码块实现
    static {
        // cfg = new Configuration();
        // cfg.configure();
        // sessionFactory = cfg.buildSessionFactory();
        sessionFactory = new Configuration().configure().buildSessionFactory();

    }

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

}

5.测试代码

package cn.itcast.hibernatetest;

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

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateDemo {

    @Test
    public void testAdd() {
        // 第一步:加载hibernate核心配置文件
        // Configuration cfg = new Configuration();
        // cfg.configure();
        // 第二步:创建SessionFactory对象
        // SessionFactory sessionFactory = cfg.buildSessionFactory();

        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 第三步:使用SessionFactory创建session对象
        Session session = sessionFactory.openSession();
        // 第四步:开启事务
        Transaction tx = session.beginTransaction();

        // 第五步:写具体的逻辑 curd操作
        // 添加功能
        User user = new User();
        user.setUsername("Mr Li");
        user.setPassword("1234");
        user.setAddress("武汉");

        // 调用session的方法实现添加
        session.save(user);

        // 第六步:提交事务
        tx.commit();
        // 第七步:关闭资源
        session.close();
        sessionFactory.close();

    }

}

第二篇:Hibernate API 练习篇

1.创建项目(略)2.导入jar包(略)3.实体类+其映射文件(略)

4.Hibernate核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test2</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    
    <!-- 在hibernate核心配置文件中配置 -->
    <property name="hibernate.current_session_context_class">thread</property>
    <!-- 把映射文件放到hibernate核心配置文件当中 -->
    <mapping resource="cn/itcast/entity/User.cfg.xml"/>
    </session-factory>    
    </hibernate-configuration>

5.Hibernate相关测试代码:

(1)HibernateDemo.java

package cn.itcast.hibernatetest;

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

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;


public class HibernateDemo {

    @Test
    public void testSaveOrUpdate() {
        // 1.调用工具类得到sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.获取session
        Session session = sessionFactory.openSession();
        // 3.开启事务
        Transaction tx = session.beginTransaction();
        // 4.添加操作
        // User user = new User();
        // user.setUid(1);
        // user.setUsername("王第一");
        // user.setPassword("12345");
        // user.setAddress("杏林二小");
        // session.save(user);

        // 把uid=1的记录username修改
        // User user = new User();
        // user.setUid(1);
        // user.setUsername("韩梅梅梅");
        // session.save(user);要用update
        // session.update(user);

        // User user = session.get(User.class, 2);
        // user.setAddress("兴隆林业局");
        // // 实体类对象是持久态,做修改
        // session.saveOrUpdate(user);

        // User user = new User();
        // user.setUsername("rose");
        // user.setPassword("1314");
        // user.setAddress("阿尔巴尼亚");
        // session.save(user);

        // User user = new User();
        // user.setUsername("jack");
        // user.setPassword("520");
        // user.setAddress("朝鲜");
        // session.save(user);

        User user = new User();
        user.setUsername("jack");
        user.setPassword("124");
        user.setAddress("china");
        session.save(user);

        // 5.提交事务
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.关闭资源
            session.close();
            sessionFactory.close();
        }

    }

    @Test
    public void testDelete() {
        // 1.利用工具类创建sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.得到session
        Session session = sessionFactory.openSession();
        // 3.开启事务
        Transaction tx = session.beginTransaction();
        // 4.删除操作
        // 第一种删除方法
        // User user = session.get(User.class, 1);
        // session.delete(user);

        // 第二种删除方法
        User user = new User();
        user.setUid(3);
        session.delete(user);

        // 5.提交事务
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.关闭资源
            session.close();
            sessionFactory.close();
        }

    }

    @Test
    public void testUpdate() {
        // 1.工具类中得到sessionFactory
        SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
        // 2.得到session
        Session session = sessionFactory.openSession();
        // 3.开启事务
        Transaction tx = session.beginTransaction();
        // 4.更新操作(修改uid=2记录的username值)
        // 4.1根据id查询(如果数据库中没有此id,执行的是查询)
        User user = session.get(User.class, 2);
        // 4.2向返回的username对象里面设置修改之后的值
        user.setUsername("修改之后的值");
        // 4.3调用session的update方法
        // 执行过程:到user对象里面找到uid值,根据uid进行修改
        session.update(user);
        // 5.提交事务
        try {
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            // 6.关闭资源
            session.close();
            sessionFactory.close();
        }

    }

}

(2)HibernateQueryData.java

package cn.itcast.hibernatetest;

import java.util.List;

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

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateQueryData {

    // 使用SQLQuery对象
    @Test
    public void testQuery() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 创建SQLQuery对象
            SQLQuery sqlQuery = session.createSQLQuery("select * from t_user");
            // 返回的list中的每部分是对象的形式
            sqlQuery.addEntity(User.class);
            // 调用SQLQuery里面的方法...导包是:import java.util.List;
            @SuppressWarnings("unchecked")
            List<User> list = sqlQuery.list();

            // 验证:当调用SQLQuery方法:返回的list集合,默认里面每一部分是数组结构
            for (User user : list) {
                System.out.println(user);
            }
            // List<Object[]> list = sqlQuery.list();
            //
            // for (Object[] objects : list) {
            // System.out.println(Arrays.toString(objects));
            // }
            // 提交事务
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();

        }
    }

    // 使用Criteria对象
    @Test
    public void testCriteria() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            // 创建criteria对象
            Criteria criteria = session.createCriteria(User.class);
            @SuppressWarnings("unchecked")
            List<User> list = criteria.list();
            for (User user : list) {
                System.out.println(user);
            }
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }

    // 使用query对象
    @Test
    public void demoQuery() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = HibernateUtils.getSessionobject();
            // 开启事务
            tx = session.beginTransaction();

            // 1 创建Query对象
            Query query = session.createQuery("from User");

            // 2 调用query对象里面的方法得到结果
            @SuppressWarnings("unchecked")
            List<User> list = query.list();

            // 遍历list集合四种: 普通for、增强for、迭代器、list迭代器
            // 遍历set集合两种:增强for、迭代器
            // 遍历map集合两种:得到所有key,根据key得到value; 得到key-value关系
            for (User user : list) {
                System.out.println(user);
            }

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

(3)HibernateSelect.java

package cn.itcast.hibernatetest;

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

import cn.itcast.entity.User;
import cn.itcast.utils.HibernateUtils;

public class HibernateSelect {

    // 事务规范代码
    @Test
    public void testTx() {
        Session session = null;
        Transaction tx = null;
        try {
            // 于本地线程绑定的session
            session = HibernateUtils.getSessionobject();
            // 开启事务
            tx = session.beginTransaction();

            // 添加
            User user = new User();
            user.setAddress("华丰");
            user.setPassword("789");
            user.setUsername("化华");

            session.save(user);

            // 模拟出事情了:java.lang.ArithmeticException: / by zero
            // 10/0 此时,不能插入数据

            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            // 下面session不能关闭,JUnit关闭会报错。可以插入数据。
            // org.hibernate.SessionException: Session was already closed
            // org.hibernate.SessionException: Session was already closed
            // session.close();
        }

    }

    // 一级缓存特性
    @Test
    public void testDemo() {

        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;

        try {
            // 1.调用工具类得到sessionFactory
            sessionFactory = HibernateUtils.getSessionFactory();
            // 2.获取session
            session = sessionFactory.openSession();

            // 3.开启事务
            tx = session.beginTransaction();
            // 4.操作:查询
            User user = session.get(User.class, 5);

            user.setAddress("之前室china,现在是哈尔滨");
            session.update(user);

            // 5.提交事务
            tx.commit();

        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        } finally {
            // 6.关闭资源
            session.close();
            sessionFactory.close();
        }

    }

    // 验证一级缓存存在
    @Test
    public void testCasch() {
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try {
            sessionFactory = HibernateUtils.getSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            // 1.根据id=2查询
            // 执行第一个get方法是否查询数据库,是否发送语句
            User user1 = session.get(User.class, 2);
            System.out.println(user1);

            // 2.在 根据id查询
            // 执行第二个get方法是否查询数据库,是否发送语句
            // 结果是!只有一条查询语句,两条查询结果
            User user2 = session.get(User.class, 2);
            System.out.println(user2);

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

}

第三篇:Hibernate 一对多、多对多实战篇

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<LinkMan> setLinkMan = new HashSet<LinkMan>();

    public Set<LinkMan> getSetLinkMan() {
        return setLinkMan;
    }

    public void setSetLinkMan(Set<LinkMan> 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

<?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" >
<hibernate-mapping>
<!-- 1.配置类和表对应
       class标签
       name属性:实体类的全路径
       table属性:数据库表名称 -->
<class name="cn.itcast.entity.Customer" table="t_customer">
<id name="cid" column="cid">
<generator class="native"></generator>
</id>
<property name="custName" column="custName"></property>
<property name="custLevel" column="custLevel"></property>
<property name="custSource" column="custSource"></property>
<property name="custPhone" column="custPhone"></property>
<property name="custMobile" column="custMobile"></property>

<!-- 在客户映射文件中,表示所有联系人
     使用set标签:表示所有联系人
     set标签里面有name属性:属性值写在客户实体类里面,表示联系人的set集合名称 
     reverse属性默认值:false表示不放弃维护
                    true表示放弃维护-->
<set name="setLinkMan" inverse="true">
<!-- 一对多建表,有外键
     hibernate机制:双向维护外键,在一和多那一方都配置外键
     column属性值:外键名称
      -->
<key column="clid"></key>
<!-- 客户所有的联系人,class里面写联系人实体类全路径 -->
<one-to-many class="cn.itcast.entity.LinkMan"/>
</set>
</class>
</hibernate-mapping>

(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

<?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" >
<hibernate-mapping>
<class name="cn.itcast.entity.LinkMan" table="t_linkman">
<id name="lkm_id" column="lkm_id">
<generator class="native"></generator>
</id>
<property name="lkm_name" column="lkm_name"></property>
<property name="lmk_gender" column="lmk_gender"></property>
<property name="lkm_phone" column="lkm_phone"></property>

<!-- 表示联系人所属客户
    name属性:因为在联系人实体类使用customer对象表示,写customer名称
    class属性:customer全路径
    column属性:外键名称 -->
    <many-to-one name="customer" class="cn.itcast.entity.Customer" column="clid"></many-to-one>
</class>
</hibernate-mapping>

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核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 第一部分:配置数据库信息,必须的 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 第二部分:配置hibernate信息,可选 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置数据库方言
    在mysql里面实现分页,关键字limit,只能用在mysql里面
    在oracle数据库,实现分页rownum
    让hibernate框架识别不同数据库的自己特有的语句 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- 第三部分:把映射文件放到核心配置文件中,必须的-->
<mapping resource="cn/itcast/entity/Customer.hbm.xml"/>
<mapping resource="cn/itcast/entity/LinkMan.hbm.xml"/>

<mapping resource="cn/itcast/manytomany/User.hbm.xml"/>
<mapping resource="cn/itcast/manytomany/Role.hbm.xml"/>


</session-factory>
</hibernate-configuration>

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<User> setUser = new HashSet<User>();

    public Set<User> getSetUser() {
        return setUser;
    }

    public void setSetUser(Set<User> 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

<?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" >
<hibernate-mapping>
<!-- 1.配置类和表对应
    class标签
    name属性:实体类的全路径
    table属性:数据库表名称 -->
<class name="cn.itcast.manytomany.Role" table="t_role">
<id name="role_id" column="role_id">
<generator class="native"></generator>
</id>
<property name="role_name" column="role_name"></property>
<property name="role_memo" column="role_memo"></property>
<!-- 在角色里面表示所有用户,使用set标签 -->
<set name="setUser" table="user_role">
<!-- 角色在第三张表外键 -->
<key column="roleid"></key>
<many-to-many class="cn.itcast.manytomany.User" column="userid"></many-to-many>
</set>
</class>
</hibernate-mapping>

(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<Role> setRole = new HashSet<Role>();

    public Set<Role> getSetRole() {
        return setRole;
    }

    public void setSetRole(Set<Role> 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

<?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" >
<hibernate-mapping>
<class name="cn.itcast.manytomany.User" table="t_user">
<id name="user_id" column="user_id">
<generator class="native"></generator>
</id>
<property name="user_name" column="user_name"></property>
<property name="user_password" column="user_password"></property>
<!-- 在用户里面表示所有角色,使用set标签
    name属性:角色set集合名称
    table属性:第三张表名称 -->
<set name="setRole" table="user_role" cascade="save-update,delete">
<!-- key标签里面的配置
    配置当前映射文件在第三张表外键的名称
     -->
<key column="userid"></key>
<!-- class标签:角色实体类的全路径
    column标签:角色在第三张表外键名称 -->
<many-to-many class="cn.itcast.manytomany.Role" column="roleid"></many-to-many>
</set>
</class>
</hibernate-mapping>

第四篇: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<LinkMan> setLinkMan = new HashSet<LinkMan>();

    public Set<LinkMan> getSetLinkMan() {
        return setLinkMan;
    }

    public void setSetLinkMan(Set<LinkMan> 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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="cn.itcast.entity.Customer" table="t_customer">
    <id name="cid" column="cid">
    <generator class="native"></generator>
    </id>
    <property name="custName" column="custName"></property>
    <property name="custLevel" column="custLevel"></property>
    <property name="custSource" column="custSource"></property>
    <property name="custPhone" column="custPhone"></property>
    <property name="custMobile" column="custMobile"></property>
    <!-- 在客户映射文件中,表示所有联系人 
            使用set标签表示所有联系人
            set标签里面有name属性:
                 属性值写在客户实体类里面表示联系人的set集合名称
                 
             inverse属性默认值:false不放弃关系维护
                            true表示放弃关系维护
        -->
    <set name="setLinkMan" batch-size="10">
    <!-- 一对多建表,有外键
                hibernate机制:双向维护外键,在一和多那一方都配置外键    
                column属性值:外键名称
             -->
    <key column="clid"></key>
    <one-to-many class="cn.itcast.entity.LinkMan"/>
    </set>
    </class>
    </hibernate-mapping>

(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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="cn.itcast.entity.LinkMan" table="t_linkman">
    <id name="lkm_id" column="lkm_id">
    <generator class="native"></generator>
    </id>
    <property name="lkm_name" column="lkm_name"></property>
    <property name="lkm_gender" column="lkm_gender"></property>
    <property name="lkm_phone" column="lkm_phone"></property>
   
    <!-- 表示联系人所属客户 
            name属性:因为在联系人实体类使用customer对象表示,写customer名称
            class属性:customer全路径
            column属性:外键名称
        -->
    <many-to-one name="customer" class="cn.itcast.entity.Customer" column="clid"></many-to-one>
    </class>
    </hibernate-mapping>

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核心配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql:///hibernate_test4</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">thread</property>
    
    <mapping resource="cn/itcast/entity/Customer.hbm.xml"/>
    <mapping resource="cn/itcast/entity/LinkMan.hbm.xml"/>
    </session-factory>
    </hibernate-configuration>

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> 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<Customer> list = criteria.list();

            for (Customer customer : list) {
                System.out.println(customer.getCid() + "::" + customer.getCustName());
                // 每个客户里面的所有联系人
                Set<LinkMan> 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<Customer> 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<Customer> 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<Customer> 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<Customer> 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<Customer> 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<Object> 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<Customer> 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<Customer> 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<Customer> 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<Customer> 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<Customer> 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();
        }
    }
}

Hibernate定义陈述:

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的JaveEE架构中取代CMP,完成数据持久化的重任。-------来自百度百科


原文链接:https://www.cnblogs.com/1693977889zz/p/13069802.html
如有疑问请与原作者联系

标签:sysIEnameAVServlet维护

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java实现金字塔:1 212 32123 4321234 543212345

下一篇:黑菜菌的JAVA学习笔记