Home  >  Article  >  Java  >  java--entity rules, object status, cache, transactions, batch query and customer list display

java--entity rules, object status, cache, transactions, batch query and customer list display

巴扎黑
巴扎黑Original
2017-06-26 09:16:331546browse

1. Entity rules in hibernate

Notes on entity class creation

1. Persistence The class provides parameterless construction

 2. Member variables are private and provide shared get/set method access. Attributes are required

 3. For attributes in persistent classes, wrapper types should be used as much as possible

4. The persistence class needs to provide oid. Corresponds to the primary key column in the database

5. Do not use final to modify the class

Primary key type

Natural primary key (rare)

Among the business columns of the table, when there is a business column that meets, must have, and is non-repeating characteristics, the column can be used as the primary key.

Surrogate primary key (common)

When there is no business column in the table that meets, must have, and is not repeated, create a column with no business meaning as the primary key

Primary key generation strategy

Agent primary key:

identity: primary key auto-increment .The primary key value is maintained by the database. There is no need to specify the primary key when entering.
sequence: the primary key generation strategy in Oracle.
increment (understanding): the primary key is auto-incremented. Maintained by hibernate. Before each insertion First query the maximum id value in the table. +1 is used as the new primary key value. (If 10 people are concurrent at the same time, there will be problems with the query) Not used during development.
native:hilo+sequence+identity Automatically choose one of three strategies.
uuid: Generate a random string as the primary key. The primary key type must be string type.

Natural primary key:

assigned: natural primary key generation strategy. Hibernate will not manage the primary key value. It is entered by the developer himself.

2. Object status in hibernate

Objects are divided into three states

//测试对象的三种状态public class Demo {

    @Test//查看三种状态public void fun1(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作Customer c = new Customer(); // 没有id, 没有与session关联 => 瞬时状态        
        c.setCust_name("联想"); // 瞬时状态        
        session.save(c); // 持久化状态, 有id,有关联        //4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//三种状态特点//save方法: 其实不能理解成保存.理解成将瞬时状态转换成持久状态的方法//主键自增 : 执行save方法时,为了将对象转换为持久化状态.必须生成id值.所以需要执行insert语句生成.//increment: 执行save方法,为了生成id.会执行查询id最大值的sql语句.public void fun2(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作Customer c = new Customer(); // 没有id, 没有与session关联 => 瞬时状态        
        c.setCust_name("联想"); // 瞬时状态        
        session.save(c); // 持久化状态, 有id,有关联        //4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//三种状态特点// 持久化状态特点: 持久化状态对象的任何变化都会自动同步到数据库中.public void fun3(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作        
        Customer c = session.get(Customer.class, 1l);//持久化状态对象        
        c.setCust_name("微软公司");        //4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
}

Transition diagram of three states

3. hibernate advanced - first-level cache

Cache: Improve efficiency. The first-level cache in hibernate is also to improve the efficiency of operating the database.

Means to improve efficiency 1: Improve query efficiency

Mean to improve efficiency 2: Reduce sending unnecessary modification statements

4. Transactions in hibernate

# # Knowledge point: How to specify the isolation level of the database in hibernate

         <!-- 指定hibernate操作数据库时的隔离级别 
            #hibernate.connection.isolation 1|2|4|8        
            0001    1    读未提交
            0010    2    读已提交
            0100    4    可重复读
            1000    8    串行化         --> <property name="hibernate.connection.isolation">4</property>
Knowledge point 2: How to manage transactions in the project

Open the transaction before the business starts, and submit the transaction after the business is executed. An exception occurs during the execution. Roll back the transaction.

The session object is required to operate the database at the dao layer. The session object is also used to control transactions in the service. We need to ensure that the dao layer and the service layer use the same session object

In hibernate, hibernate has already solved the problem for us. Our developers only need to call sf.getCurrentSession( ) method to obtain the session object bound to the current thread

Note 1: Calling the getCurrentSession method must match a configuration section in the main configuration

         <!-- 指定session与当前线程绑定 --> <property name="hibernate.current_session_context_class">thread</property>
Note 2: Pass The session object obtained by the getCurrentSession method. When the transaction is submitted, the session will be automatically closed. Do not manually call close to close.

In the crm project:

Service layer

    public void save(Customer c) {
        Session session =  HibernateUtils.getCurrentSession();//打开事务Transaction tx = session.beginTransaction();//调用Dao保存客户try {
            customerDao .save(c);
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }//关闭事务        tx.commit();
    }
Dao layer

    public void save(Customer c) {//1 获得sessionSession session = HibernateUtils.getCurrentSession();//3 执行保存        session.save(c);
    }

## 5. Batch query in hibernate (Overview)

HQL query-hibernate Query Language (multi-table query, but not used when it is not complicated)

Hibernate exclusive query language, belongs to Object-oriented query language

//测试HQL语句public class Demo {

    @Test//基本查询public void fun1(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1> 书写HQL语句//        String hql = " from cn.itheima.domain.Customer ";String hql = " from Customer "; // 查询所有Customer对象//2> 根据HQL语句创建查询对象Query query = session.createQuery(hql);//3> 根据查询对象获得查询结果List<Customer> list = query.list();    // 返回list结果//query.uniqueResult();//接收唯一的查询结果        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//条件查询//HQL语句中,不可能出现任何数据库相关的信息的public void fun2(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1> 书写HQL语句String hql = " from Customer where cust_id = 1 "; // 查询所有Customer对象//2> 根据HQL语句创建查询对象Query query = session.createQuery(hql);//3> 根据查询对象获得查询结果Customer c = (Customer) query.uniqueResult();
        
        System.out.println(c);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//条件查询//问号占位符public void fun3(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1> 书写HQL语句String hql = " from Customer where cust_id = ? "; // 查询所有Customer对象//2> 根据HQL语句创建查询对象Query query = session.createQuery(hql);//设置参数//query.setLong(0, 1l);query.setParameter(0, 1l);//3> 根据查询对象获得查询结果Customer c = (Customer) query.uniqueResult();
        
        System.out.println(c);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//条件查询//命名占位符public void fun4(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1> 书写HQL语句String hql = " from Customer where cust_id = :cust_id "; // 查询所有Customer对象//2> 根据HQL语句创建查询对象Query query = session.createQuery(hql);//设置参数query.setParameter("cust_id", 1l);//3> 根据查询对象获得查询结果Customer c = (Customer) query.uniqueResult();
        
        System.out.println(c);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//分页查询public void fun5(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1> 书写HQL语句String hql = " from Customer  "; // 查询所有Customer对象//2> 根据HQL语句创建查询对象Query query = session.createQuery(hql);//设置分页信息 limit ?,?query.setFirstResult(1);
        query.setMaxResults(1);//3> 根据查询对象获得查询结果List<Customer> list =  query.list();
        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联    }
}

Criteria query (single table condition query)

Hibernate’s own statement-free Object-oriented query

//测试Criteria查询public class Demo {

    @Test//基本查询public void fun1(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------        //查询所有的Customer对象Criteria criteria = session.createCriteria(Customer.class);
        
        List<Customer> list = criteria.list();
        
        System.out.println(list);        
//        Customer c = (Customer) criteria.uniqueResult();        //-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//条件查询//HQL语句中,不可能出现任何数据库相关的信息的// >                 gt// >=                ge// <                lt// <=                le// ==                eq// !=                ne// in                in// between and        between// like             like// is not null         isNotNull// is null            isNull// or                or// and                andpublic void fun2(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//创建criteria查询对象Criteria criteria = session.createCriteria(Customer.class);//添加查询参数 => 查询cust_id为1的Customer对象criteria.add(Restrictions.eq("cust_id", 1l));//执行查询获得结果Customer c = (Customer) criteria.uniqueResult();
        System.out.println(c);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    
    
    @Test//分页查询public void fun3(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//创建criteria查询对象Criteria criteria = session.createCriteria(Customer.class);//设置分页信息 limit ?,?criteria.setFirstResult(1);
        criteria.setMaxResults(2);//执行查询List<Customer> list = criteria.list();
        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//查询总记录数public void fun4(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//创建criteria查询对象Criteria criteria = session.createCriteria(Customer.class);//设置查询的聚合函数 => 总行数        criteria.setProjection(Projections.rowCount());//执行查询Long count = (Long) criteria.uniqueResult();
        
        System.out.println(count);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
}

Native SQL query (complex business query)

//测试原生SQL查询public class Demo {

    @Test//基本查询public void fun1(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1 书写sql语句String sql = "select * from cst_customer";        //2 创建sql查询对象SQLQuery query = session.createSQLQuery(sql);        //3 调用方法查询结果List<Object[]> list = query.list();//query.uniqueResult();for(Object[] objs : list){
            System.out.println(Arrays.toString(objs));
        }        //-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//基本查询public void fun2(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1 书写sql语句String sql = "select * from cst_customer";        //2 创建sql查询对象SQLQuery query = session.createSQLQuery(sql);//指定将结果集封装到哪个对象中query.addEntity(Customer.class);        //3 调用方法查询结果List<Customer> list = query.list();
        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//条件查询public void fun3(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1 书写sql语句String sql = "select * from cst_customer where cust_id = ? ";        //2 创建sql查询对象SQLQuery query = session.createSQLQuery(sql);
        
        query.setParameter(0, 1l);//指定将结果集封装到哪个对象中query.addEntity(Customer.class);        //3 调用方法查询结果List<Customer> list = query.list();
        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
    
    @Test//分页查询public void fun4(){//1 获得sessionSession session = HibernateUtils.openSession();//2 控制事务Transaction tx = session.beginTransaction();//3执行操作//-------------------------------------------//1 书写sql语句String sql = "select * from cst_customer  limit ?,? ";        //2 创建sql查询对象SQLQuery query = session.createSQLQuery(sql);
        
        query.setParameter(0, 0);
        query.setParameter(1, 1);//指定将结果集封装到哪个对象中query.addEntity(Customer.class);        //3 调用方法查询结果List<Customer> list = query.list();
        
        System.out.println(list);//-------------------------------------------//4提交事务.关闭资源        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联        
        
    }
}

 

五、练习:客户列表

案例比较简单,可以按照上面笔记的知识点完成

servlet:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1 调用Service查询所有客户List<Customer> list = cs.getAll();//2 将客户列表放入request域request.setAttribute("list", list);//3 转发到list.jsp显示request.getRequestDispatcher("/jsp/customer/list.jsp").forward(request, response);
    
    }

service:

    public List<Customer> getAll() {
        Session session =  HibernateUtils.getCurrentSession();//打开事务Transaction tx = session.beginTransaction();
        
        List<Customer> list = customerDao.getAll();        
        //关闭事务                tx.commit();return list;
    }

dao:

    public List<Customer> getAll() {//1 获得sessionSession session = HibernateUtils.getCurrentSession();//2 创建Criteria对象Criteria c = session.createCriteria(Customer.class);return c.list();
    }

 

The above is the detailed content of java--entity rules, object status, cache, transactions, batch query and customer list display. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn