Hibernate Core API and configuration files

First, the core configuration file

1, Hibernate mapping file * .hbm.xml

basic structure:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 映射文件的dtd信息 -->
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    
<hibernate-mapping>
	<!--name 代表的是实体类名 table代表的是表名  -->
	<class name="XXX" table="xxx">
		<!-- name=id 代表i的是XXX类中的属性 column=id代表的是xxx表中的字段 -->
		<id name="id" column="id">
			<generator class="native"/> <!-- 主键生成策略 -->
		</id>
		<!-- 其他属性使用property标签来映射 -->
		<property name="password" column="password" type="string"/>
	</class>
	
</hibernate-mapping>
  hibernate-mapping: This element defines the basic properties of the XML configuration file, which he defined attributes available in all node mapping files

class: This element is used to declare a persistent class, he is the main contents of the XML configuration file

id: This element is used to persistent class of the OID (object identifier), and the primary key mapping table

property: This element is used in common persistent class attribute mapping table corresponding to the database field

2, hibernate configuration file hibernate.cfg.xml

 basic structure:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 配置文件的dtd信息 -->
<!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://localhost:3306/hibernate
		</property>
		<!--  用户名-->
		<property name="hibernate.connection.username">
			root
		</property>
		<!-- 密码 -->
		<property name="hibernate.connection.password">
			itcast
		</property>
		<!-- 其他配置 -->
		<!-- 显示sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 格式化sql语句 -->
		<property name="hibernate.format_sql">true</property>
		<!-- 关联hbm配置文件 -->
		<mapping resource="com/itcast/domain/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>
 Hibernate configuration file and use common attributes:

Name  Uses            
hibernate.dialect Operation of the database dialect
hibernate.connection.driver_class Connect to the database driver
hibernate.connection.url URL road connection data
hibernate.connection.username database username
hibernate.connection.password Database Password
hibernate.show_sql SQL statement on the console output
hibernate.format_sql Console output formatting SQL statements
hibernate.hbm2ddl.auto

When SessionFactory is created automatically verify whether the table structure according to the mapping file or automatically create,

Automatically update the database table structure. The value of this parameter is validate, update, create and create-drop

hibernate.connection.autocommit Are things automatically submitted


Two, Hibernate Core API

 Six common core interface in Hibernate, respectively Configuration, SessionFactory, Session, Transaction, Query, Criteria


1,Configuration

 When using Hibernate, we must first load the Configuration instance, Configuration examples mainly used to start,
Load management hibernate configuration file. In the process of starting the Hibernate, Configuration example first determines
Location Hibernate configuration file, and then read the relevant configuration, and finally create a unique SessionFactory instance.
Configuration object exists only in the system initialization phase, after it SessionFactory is created, the mission is complete
 Hibernate usually Configuration config = new Configuration () configure ();. Manner
Create an instance, the default read this way hibernate.cfg.xml configuration file will go src. If you do not want to use the default configuration
File, but the use of customized configuration files in the specified directory, you need () method passing a file path to configure
Parameters, as follows:
Configuration config = new Configuration().configure("xml文件位置");

2,SessionFactory

 Hibernate SessionFactory interface initialization responsible for the establishment and Session objects. It has played a buffer in Hibernate
Action, Hibernate can automatically generate SQL statements, the map data and the data of certain reusable placed in this buffer. Simultaneously
It also holds all of the mappings of database configuration and maintenance of the current level two cache.
 Acquisition method as follows:
SessionFactory sessionFactory = config.buildSessionFactory();
  SessionFactory has the following characteristics:
  • It is thread-safe, it's the same instance can be shared by multiple threads
  • It is a heavyweight, not at liberty to create and destroy an instance of it
Because of these characteristics, in general, a project in the SessionFactory only one, only when a plurality of data source applications exist only for each
Data source to create a SessionFactory instance. Thus in the actual project, typically a HibernateUtils extraction tools, used to provide
Session object:
public class HibernateUtils {
	//声明一个私有静态final类型的Configuration对象
	private static final Configuration config;
	//声明一个私有静态final类型的SessionFactory对象
	private static final SessionFactory factory;
	//通过静态代码块构建SessionFactory
	static{
		config = new Configuration().configure();
		factory = config.buildSessionFactory();
	}
	//提供一个共有静态方法供外部获取,并返回一个Session对象
	public static Session getSession(){
		return factory.openSession();
	}
}

 With this tool category, the program can directly obtain the Session object by HIbernateUtils.getSession () mode




3,Session

  Session is a single-threaded operation of object interactions between applications and the database, Hibernate is the center of the operation, its main role is to
Persistent objects to create, read and delete functions, all persistent objects must persist before they can be operated under Session Management
 After creating SessionFactory instance, you can get a Session object through it. There are two ways to obtain the Session, as follows:
 Session session = sessionFactory.openSession();
  Session session = sessionFactory.getCurrentSession();
  The first method directly create a new Session instance when creating SessionFactory instance, and need to call in after use
 manually close method Close
 The second way to create instances will be bound to the current thread, it will automatically shut down when the commit or rollback operation


Session thread is incomplete, when simultaneously operating a plurality of concurrent threads Session, data access may cause confusion (internal method
Problem does not occur when the thread defining and using Session). Therefore, due to avoid multiple threads simultaneously using a Session
It provides a number of methods commonly used in the Session:
  • save (), update () and saveOrUpdate () method: for increasing and modifying objects
  • delete () method: to remove objects
  • get () and load () methods: The primary key query
  • the createQuery () and createSQLQuery () and: a database operation target
  • createCriteria () method: query conditions

4,Transaction

  Transaction interface is primarily used for the management of things, it is an object Hibernate database interface and the interface to the underlying object is encapsulated. Transaction
Things object interface is turned on by the Session object, which open the way:
Transaction t = session.beginTransaction();

  In the Transaction interface provides a common approach to transaction management:
  •  commit () method: Session instance associated Submit
  •  rollback () method: undo things operate
  •  wasCommitted (): Check whether things submission

After Session Ends perform database operations, commit to using the method Transaction Interface are being filed in order to truly synchronize data
To the database. When an exception occurs, things need to be rolled back using the rollback to avoid data errors.

5,Query

 Query on behalf of a Hibernate object-oriented query operation. In Hibernate usually used session.createQuery () method
Accept a HQL statement. Query and then call the list () or uniqueResult () method to execute the query.
 To use the Query object in Hibernate:
(1) obtain hibernate session objects
(2) write HQL statement
(3) create a query object to call session.createQuery
(4) If HQL statement contains parameters, set the parameters Query call setXxx
(5) call the Query object list () or uniqueResult () method to execute a query
Here too a case to illustrate the same
 Create a new class QueryTest.java in com.itcast.test package under the previous entry-case project entry-case link

 
package com.itcast.test;

import java.util.List;

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

import com.itcast.domain.User;

public class QueryTest {
	@Test
	public void findAll_hqlTest(){
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction t = session.beginTransaction();
		String hql = "from User";
		Query query = session.createQuery(hql);
		List<User>list= query.list();
		for(User user:list){
			System.out.println(user);
		}
		t.commit();
		session.close();
		sessionFactory.close();
	}
	
}
Junit test method using the
data in the database:

Console output data:


Query in addition to using the list method to query all the data, there are some common methods:
  • setter methods: Query interface provides a set of query parameters setter method is used to set, for
    Different types of data, need to use a different setter methods
  • iterator method: This method is used to query statement, the method returns an Iterator object, the method can only be read in the order read, it
   Only used to convert data into the entity object java
  • uniqueResult method: This method is used to return a unique result, ensure that the query is only one record of when you can use this method
  • executeUpdate method: This method is a new feature Hibernate3, it supports update and delete HQL statement of operations
  • setFirstResult method: This method can be set to get the first record of the location, that is, it represents the beginning of a query from the first few records, default 0
  • setMaxResult Method: The method used to set the maximum number of records of the result set, the method usually used in conjunction with setFirstResult, limiting the result set, implement paging function      

6,Criteria

 Criteria is a fully object-oriented, extensible criteria query API how to implement it completely without considering the underlying database, and SQL
How to write the statement, he is the core of Hibernate query object framework.
 Use Criteria query data objects main steps:
(1) obtain Hibernate Session object
(2) Criteria object obtained by Session
Static method (3) Restrictions of the use of objects to create Criterion
(4) Add Criterion query to Criteria object. Criteria of add () method is used join query
(5), or a list of Criteria results obtained uniqueResult
The following is illustrated by a case:
Create a class CriteriaTest.java in com.itcast.test package under the src directory entry case
package com.itcast.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import com.itcast.domain.User;

public class CriteriaTest {
	@Test
	public void qbcTest(){
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory= config.buildSessionFactory();
		Session session= sessionFactory.openSession();
		Transaction t = session.beginTransaction();
		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Restrictions.eq("name", "tom"));
		List<User>list =criteria.list();
		for(User user:list){
			System.out.println(user);
		}
		t.commit();
		session.close();
		sessionFactory.close();
	}
}


Run as Junit test:
Console output:


Name = tom is outputted to the information



Published 110 original articles · won praise 76 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_34731703/article/details/79173443