Hibernation5

Hibernation5:

demo:

pom.xml声明依赖,利用该网站查找配置写法(http://mvnrepository.com/)

Hibernate5.2使用手册:

http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html

pom.xml:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.16.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>5.2.16.Final</version>
    </dependency>
    <!--c3p0-->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

hibernate.cfg.xml:

<!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://localhost:3306/hibernate_day01</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!--方言 mysql version5.1~5.5  MySQL5Dialect-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!--显示sql-->
        <property name="hibernate.show_sql">true</property>
        <!--格式化sql-->
        <property name="hibernate.format_sql">true</property>
        <!-- 配置C3P0连接池 -->
        <property name="connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
        <!--在连接池中可用的数据库连接的最少数目 -->
        <property name="hibernate.c3p0.min_size">5</property>
        <!--在连接池中所有数据库连接的最大数目  -->
        <property name="hibernate.c3p0.max_size">20</property>
        <!--设定数据库连接的过期时间,以秒为单位,
        如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
        <property name="hibernate.c3p0.timeout">120</property>
        <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
        <property name="hibernate.c3p0.idle_test_period">3000</property>

        <!--none 不会自动生成表-->
        <!--update 更新表-->
        <!--validate 只校验-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--事物隔离级别-->
        <property name="hibernate.connection.isolation">4</property>
        <!--配置session绑定本地线程-->
        <property name="hibernate.current_session_context_class"> thread</property>
        <!--加载映射-->
        <mapping resource="com/fly/pojo/Customer.hbm.xml"/>
        <mapping resource="com/fly/pojo/Linkman.hbm.xml"/>
        <mapping resource="com/fly/pojo/User.hbm.xml"/>
        <mapping resource="com/fly/pojo/Role.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Customer:

@Entity
@Table(name = "cst_customer")
public class Customer {
    private long custId;
    private String custName;
    private String custPhone;
    private String custMobile;
    private String custImage;
    //一个客户有多个联系人
    private Set<Linkman>linkmen = new HashSet<Linkman>();

    public Set<Linkman> getLinkmen() {
        return linkmen;
    }
    @Id
    @Column(name = "cust_id")
    public long getCustId() {
        return custId;
    }

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="com.fly.pojo.Customer" table="cst_customer">
        <id name="custId" column="cust_id">
            <generator class="native"/>
        </id>
        <property name="custName" column="cust_name"/>
        <property name="custPhone" column="cust_phone"/>
        <property name="custMobile" column="cust_mobile"/>
        <property name="custImage" column="cust_image"/>
        <!--主控方 设置级联-->
        <!--删除Customer的同时删除linkmen-->
        <!--inverse 放弃外键维护权-->
        <set name="linkmen" cascade="save-update,delete" inverse="true">
            <key column="lkm_cust_id"/>
            <one-to-many class="com.fly.pojo.Linkman"/>
        </set>
    </class>
</hibernate-mapping>

Linkman:

@Entity
@Table(name = "cst_linkman")
public class Linkman {
    private long lkmId;
    private String lkmName;
    private String lkmGender;
    private String lkmPhone;
    private String lkmMobile;
    private String lkmEmail;
    private String lkmQq;
    private String lkmPosition;
    private String lkmMemo;

    private Customer customer;

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="com.fly.pojo.Linkman" table="cst_linkman" schema="hibernate_day01">
        <id name="lkmId" column="lkm_id">
            <generator class="native"/>
        </id>
        <property name="lkmName" column="lkm_name"/>
        <property name="lkmGender" column="lkm_gender"/>
        <property name="lkmPhone" column="lkm_phone"/>
        <property name="lkmMobile" column="lkm_mobile"/>
        <property name="lkmEmail" column="lkm_email"/>
        <property name="lkmQq" column="lkm_qq"/>
        <property name="lkmPosition" column="lkm_position"/>
        <property name="lkmMemo" column="lkm_memo"/>
        <many-to-one name="customer" class="com.fly.pojo.Customer" column="lkm_cust_id"/>
    </class>
</hibernate-mapping>

Role.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="com.fly.pojo.Role" table="tb_role" schema="hibernate_day01">
        <id name="roleId" column="role_id">
            <generator class="increment"/>
        </id>
        <property name="roleName" column="role_name"/>
        <property name="roleMemo" column="role_memo"/>
        <!--//主控方是role-->
        <set name="users" table="sys_user_role" cascade="save-update,delete">
            <key column="role_id"/>
            <many-to-many class="com.fly.pojo.User" column="user_id"/>
        </set>
    </class>
</hibernate-mapping>

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>

    <class name="com.fly.pojo.User" table="tb_user" schema="hibernate_day01">
        <id name="userId" column="user_id">
            <generator class="increment"/>
        </id>
        <property name="userCode" column="user_code"/>
        <property name="userName" column="user_name"/>
        <property name="userPassword" column="user_password"/>
        <property name="userState" column="user_state"/>
        <set name="roles">
            <key column="user_id"/>
            <many-to-many class="com.fly.pojo.Role" column="role_id"/>
        </set>
    </class>
</hibernate-mapping>

Test:

public class test {
    private SessionFactory sessionFactory;
    @Before
    public void before(){

        //默认读src下的 hibernate.cfg.xml
        Configuration cfg = new Configuration().configure();
//        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        //properties方式的config无法配置映射,需编写
//        cfg.addResource("com/fly/pojo/Customer.hbm.xml");
        sessionFactory = cfg.buildSessionFactory();
    }
    @Test
    public void demo1(){

//        Session session = sessionFactory.openSession();//需要手动关闭
        //获取当前线程绑定的会话
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();

        Customer customerEntity = new Customer();
        customerEntity.setCustName("小王子");
        customerEntity.setCustMobile("12312345672");
        session.save(customerEntity);

        tx.commit();
//        session.close();
    }
    @Test
    public void updateDemo(){
        Session session = sessionFactory.openSession();//需要手动关闭
        Transaction tx = session.beginTransaction();

        Customer customerEntity = session.get(Customer.class, 22L);
        customerEntity.setCustName("小王子");
        customerEntity.setCustMobile("12312345671");
        session.update(customerEntity);

        tx.commit();
        session.close();
    }
    @Test
    public void deleteDemo(){
        Session session = sessionFactory.openSession();//需要手动关闭
        Transaction tx = session.beginTransaction();

        Customer customerEntity = session.get(Customer.class, 22L);
        session.delete(customerEntity);

        tx.commit();
        session.close();
    }
    @Test
    public void SaveOrUpdateDemo(){
        Session session = sessionFactory.openSession();//需要手动关闭
        Transaction tx = session.beginTransaction();

        Customer customerEntity = new Customer();
       // customerEntity.setCustId(23L);  //设置id会执行update,否则insert
        customerEntity.setCustName("小王子");
        customerEntity.setCustMobile("12312345671");
        session.saveOrUpdate(customerEntity);

        tx.commit();
        session.close();
    }

    @Test
    public void findAllDemo(){
        Session session = sessionFactory.openSession();//需要手动关闭
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery("from Customer ");
        List<Customer> list = query.list();
        for (Customer customerEntity : list) {
            System.out.println(customerEntity);
        }
        tx.commit();
        session.close();
    }
    /**
     * hql语句
     */
    @Test
    public void QueryHQLTest(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
//        Query query = session.createQuery("from Customer where custName=?");
        Query query = session.createQuery("from Customer where custName=:name");
//        query.setParameter(0,"李凳子A");
        query.setParameter("name","李凳子A");
        List<Customer> list = query.list();
        System.out.println(list);
        tx.commit();
    }
    @Test
    public void QueryHQLTest2(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery("from Customer");
        query.setFirstResult(3);//默认从0开始
        query.setMaxResults(3);//最大记录数
        List<Customer> list = query.list();
        System.out.println(list);
        tx.commit();
    }
    /**
     * NativeQuery
     * SQLQuery过时
     */
    @Test
    public void NativeQueryTest(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        NativeQuery query = session.createNativeQuery("select * from cst_customer");
        List<Object[] > list = query.list();
        for (Object[] objects : list) {
            System.out.println(Arrays.toString(objects));
        }
        tx.commit();
    }

    /**
     * 基于JPA规范的CriteriaQuery查询
     * Criteria过时
     * 实体查询
     */
    @Test
    public void CriteriaQueryTest0(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();

        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
        Root<Customer> root = query.from(Customer.class);
        query.select(root);
//        query.where(cb.equal(root.get("custName"),"李凳子A"));
        query.where(builder.like(root.<String>get("custName"),"李%"));
        List<Customer> list = session.createQuery(query).getResultList();
        for (Customer customer : list) {
            System.out.println(customer);
        }
        tx.commit();
    }
    // 选择一个属性或多个
    @Test
    public void CriteriaQueryTest1(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Object[]> criteria = builder.createQuery(Object[].class);
        Root<Customer> root = criteria.from(Customer.class);
//        query.select(root.<Customer>get("custName"));
        Path<String> custName = root.get("custName");
        Path<String> custPhone = root.get("custPhone");

//        criteria.select(builder.array(custName,custPhone));//方式一
        criteria.multiselect(custName,custPhone);
        criteria.where(builder.equal(root.get("custId"),9L));
        List<Object[]> list = session.createQuery(criteria).getResultList();
        for (Object[] objects : list) {
            System.out.println(objects[0]);
            System.out.println(objects[1]);
        }
        tx.commit();
    }
    // 多个值更好的方法: 选择一个 tuple
    @Test
    public void CriteriaQueryTest2(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
        Root<Customer> root = criteria.from(Customer.class);

        Path<String> custName = root.get("custName");
        Path<String> custPhone = root.get("custPhone");

        criteria.multiselect(custName,custPhone);
        criteria.where(builder.equal(root.get("custId"),9L));
        List<Tuple> tuples = session.createQuery(criteria).getResultList();
        for (Tuple tuple : tuples) {
            System.out.println(tuple.get(custName));
            System.out.println(tuple.get(custPhone));
        }
        tx.commit();
    }

    /**
     * 保存一个客户和两个联系人
     */
    @Test
    public void oneToManyTest(){
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Customer customer = new Customer();
        customer.setCustName("客户b");
        Linkman linkman = new Linkman();
        linkman.setLkmName("联系人2");

        customer.getLinkmen().add(linkman);
        linkman.setCustomer(customer);

        session.save(customer);
//        session.save(linkman);//customer方设置了级联

        tx.commit();
    }
    //级联删除
    @Test
    public void delCusAndLinkman(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Customer customer = session.get(Customer.class, 30L);
        session.delete(customer);
        transaction.commit();
    }
    //将2号联系人关联的客户10
    @Test
    public void inverseDemo(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        Customer customer = session.get(Customer.class, 10L);
        Linkman linkman = session.get(Linkman.class, 2L);
        linkman.setCustomer(customer);
        customer.getLinkmen().add(linkman);
        transaction.commit();
    }
    /*
     * 多对多
     */
    @Test
    public void many2manydemo(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        User user = new User();
        user.setUserName("用户");
        User user2 = new User();
        user2.setUserName("用户2");

        Role role = new Role();
        role.setRoleName("角色");

        user.getRoles().add(role);
        user2.getRoles().add(role);
        role.getUsers().add(user);
        role.getUsers().add(user2);
        session.save(role);//主控方是role

        transaction.commit();
    }
    //级联删除
    @Test
    public void delm2mDemo(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Role role = session.get(Role.class, 0L);
        session.delete(role);
        transaction.commit();
    }
    //将1号user的1号role去掉
    @Test
    public void demo(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();

        User user = session.get(User.class, 1L);
        Role role = session.get(Role.class, 1L);
        role.getUsers().remove(user);//role是主控
        transaction.commit();
    }
    //将1号role的2号user改为1号
    @Test
    public void demo2(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        User user = session.get(User.class, 1L);
        User user2 = session.get(User.class, 2L);
        Role role = session.get(Role.class, 1L);

        role.getUsers().remove(user2);
        role.getUsers().add(user);
        transaction.commit();
    }
    //给1号role添加2号user
    @Test
    public void demo3(){
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        User user = session.get(User.class, 2L);
        Role role = session.get(Role.class, 1L);
        role.getUsers().add(user);
        transaction.commit();
    }
}

补充:

对象的 3 种状态:


a) 临时状态/瞬时状态

该对象是新创建的;一个持久化状态的对象被删除;一个游离状态的数据被删除

b) 持久化状态

对象从数据库中查询出来时,临时状态的数据被保存时,游离状态的数据被更新/锁定

c) 游离状态

持久化状态的数据被(session)清理


临时状态:内存有,数据库没有

持久状态:内存有,session 有,数据库有

游离状态:内存有,数据库有


 

posted @ 2018-12-18 10:10  fly_bk  阅读(118)  评论(0)    收藏  举报