SSH [SSH] Hibernate framework of: Hibernate Core API

Hibernate API for a total of six, are: Session, SessionFactory, Transaction, Query, Criteria and Configuration. You can access, transaction control of the persistent object through these interfaces.

A, Configuration:

Configuration class action Hibernate is configured, and its start. Hibernate during startup, the first instance of the class Configuration position location mapping document, reads the configuration, and then create a SessionFactory.

  • If the configuration file is written in the hibernate.properties file, create a configuration object with the following form:
Configuration cfg = new Configuration();
//这种方式需要手动加载映射文件
cfg.addResource("cn/jingpengchong/pojo/Customer.hbm.xml");
  • If it is written in the configuration file hibernate.cfg.xml file, create a configuration object directly using the following form and load map file:
Configuration cfg = new Configuration().configure();
  • Get SessionFactory object based Configuration object:
SessionFactory factory = cfg.buildSessionFactory();

二、SessionFactory:

SessionFactory interface is responsible for initializing Hibernate. It serves as a source of proxy data storage, internal maintenance of the database connection pool, and is responsible for creating Session objects. Factory mode used here, in general, a project typically requires only a SessionFactory enough, multiple databases when needed, can specify a SessionFactory for each database.

  • SessionFactory to obtain the Session object according to the object:
Session session = factory.openSession();

Since a project usually requires only a SessionFactory, so you can create the Session extraction tools:

package cn.jingpengchong.utils;

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

public class SessionFactoryUtil {
	
	private static final Configuration CFG;
	private static final SessionFactory SF;
	
	static {
		CFG = new Configuration().configure();
		SF = CFG.buildSessionFactory();
	}
	
	public static Session getSessionFactory() {
		return SF.openSession();
	}
	
	public static void closeSessionFactory() {
		SF.close();
	}
}

Three, Session:

Session interface is responsible for the implementation of persistent objects CRUD operations (CRUD task is to complete the exchange with the database, contains a lot of common SQL statements). But note that the Session is not thread-safe. Meanwhile, the session Hibernate is different from the HttpSession JSP applications, when used herein the term session, in fact, refers to a session in Hibernate.
You can open a transaction, the transaction object obtained based on the Session object:

Transaction transaction = session.beginTransaction();

Session of the persistent object CRUD operations: to the blog post the code as an example

1, increasing operation: save () and saveOrUpdate ()

Save () : add operation;
saveOrUpdate () : If there is no data (id to determine whether it is on the same or Objects) add operation is performed, if there is, then the edit operation.
To save (), for example, from Step 5 Test class main method modified as follows:

Customer customer = new Customer();
customer.setName("猪八戒");
session.save(customer);

Results are as follows:
Here Insert Picture Description
At this time, data in the database as follows:
Here Insert Picture Description

2, query operations: get (), load (), createQuery () and createSQLQuery ()

get () and Load () : a query object Example: Step 5 Test class main method modified as follows

//方法一:get()
//Customer customer = session.get(Customer.class, 1l);
//方法二:load()
Customer customer = session.load(Customer.class, 1l);
System.out.println(customer);

Results are as follows:
Here Insert Picture Description
the difference between get () and load () is :

  • Send the implementation of the get () SQL statement immediately, but do not send SQL statements to the load (), found only in the first use of data (in addition to id to access the object) when sending SQL statements;
  • get () to get a true persistent class object, load () to get a proxy class inherits the class of object persistence;
  • get () does not return a query to null, load () can not find any exception will be thrown.

the createQuery () : a plurality of query objects, Example: Step 5 Test class main method modified as follows

Query<Customer> query = session.createQuery("from Customer",Customer.class);
List<Customer> list = query.list();
for (Customer customer : list) {
	System.out.println(customer);
}

Results are as follows:
Here Insert Picture Description
createSQLQuery () : a plurality of query objects, Example: Step 5 Test class main method modified as follows

NativeQuery<Object[]> query = session.createSQLQuery("select * from cst_customer");
List<Object[]> list = query.list();
for (Object[] customer : list) {
	System.out.println(Arrays.toString(customer));
}

Results are as follows:
Here Insert Picture Description
the difference between the createQuery () and createSQLQuery () is :

  • the createQuery () returns a generic class for persistent objects Query, list call () method to convert it to a generic set of List persistent class; while createSQLQuery () returns to the generic Object [] the NativeQuery objects, list call () method can be converted to a generic Object [] List of collection;
  • the createQuery () takes two parameters, a HQL statement, one instance of class Class; createSQLQuery () requires a SQL expression parameter;
3, modify operation: update () and saveOrUpdate ()

update () : modify operation, if there is no error will;
saveOrUpdate () : modify operation, as if there is no new data is added;
to update () as an example, the Test class in step 5 with the following modifications:

//方法一:创建一个对象,将id设置为要修改的数据,根据cust_id修改cust_name
//Customer customer = new Customer();
//customer.setId(3l);
//customer.setName("齐天大圣");
//session.update(customer);

//方法二:根据要修改的记录的cust_id查询一个对象,然后对其进行修改(推荐)
Customer customer = session.get(Customer.class, 1l);
customer.setName("齐天大圣");
session.update(customer);

Results are as follows:
Here Insert Picture Description
look at the database, it has been modified:
Here Insert Picture Description

4, delete operations: delete ()

Delete () : Delete records, for example: the main class Step 5 Test method modified as follows:

//方法一:创建一个对象,将id设置为要删除的数据,根据cust_id删除记录
//Customer customer = new Customer();
//customer.setId(1l);
//session.delete(customer);

//方法二:根据要修改的记录的cust_id查询一个对象,然后对其进行删除(推荐)
Customer customer = session.get(Customer.class, 1l);
session.delete(customer);

Results are as follows:
Here Insert Picture Description
look at the database, it has been deleted:
Here Insert Picture Description

四、Transaction:

Transaction Interface is an optional API, you can choose not to use this interface, replaced by Hibernate designers to write their own underlying transaction code.

  • Transaction submitted:
transaction.commit();
  • Transaction rollback:
transaction.rollback();

Five, Query:

Query interface allows you to easily query the database and persistent objects, which can be expressed in two ways: HQL language or local database SQL statements. Query query parameters are often used to bind, limit the number of query record, and ultimately perform a query operation, for example, the following:
Condition Query :

  • After from the persistent class name should be written, not the database table name
  • The condition may be defined persistent class attribute names, it may be the corresponding field name
  • Parameter placeholder format is "? 0", "? 1" and the like, the first parameter setParameter corresponding method should be below
  • setParameter (int arg0, Object arg1) for indicating to the first parameter set arg0 arg1
  • Object list () is used to query into the Query object List collection
String hql = "from Customer where name like ?0";
Query<Customer> query = session.createQuery(hql,Customer.class);
query.setParameter(0, "%天%");
List<Customer> list = query.list();
for (Customer user : list) {
	System.out.println(user);
}

Results are as follows:
Here Insert Picture Description
paging query :

  • After from the persistent class name should be written, not the database table name
  • setFirstResult (int arg0) method for setting the first few queries data from the beginning, starting from 0
  • setMaxResults (int arg0) is provided a method for displaying data several
String hql = "from Customer";
Query<Customer> query = session.createQuery(hql,Customer.class);
query.setFirstResult(1);
query.setMaxResults(2);
List<Customer> list = query.list();
for (Customer user : list) {
	System.out.println(user);
}

Results are as follows:
Here Insert Picture Description

Six, Criteria:

Criteria Query interface very similar interface, allows the creation and implementation of a standardized object-oriented queries. It is noteworthy that Criteria interface is also lightweight, it can not be used outside Session.

Published 128 original articles · won praise 17 · views 2729

Guess you like

Origin blog.csdn.net/qq_43705275/article/details/104214875