first, the basic introduction
1, it has a very lightweight JDBC object encapsulation, it will pojo and database table mapping relationship, is a fully automatic ORM (object relationship Mapping) framework, hibernate can automatically generate SQL statements, automatic execution; Hibernate can be applied to any use of jdbc.
2. Persistence layer: Code method (ORM) for mapping relationships between relational databases (data storage Tiers) and Model objects (object, business logic Model)
3. Hibernate is a mainstream persistence framework based on jdbc, which encapsulates the code of JDBC Access database, simplifies the tedious repetitive code of the data access layer, and is an excellent ORM implementation, which simplifies the DAO layer coding Greatly.
4,: http://www.hibernate.org/downloads
5. New Hibernate.cfg.xml or hibernate.properties, put in the project root directory, used to configure the database information, XLM header file information can be found in the DTD file in hibernate-core-5.3.0.final.jar, while a Class object mapping XML file header can also be in the jar package Found in the DTD file;
second, Hibernate's API
A total of 6, respectively: Session, sessionfactory, Transaction, Query, criteria and Configuration. Through these interfaces, persistent objects can be accessed, transaction Control.
1. Examples of use:
//use Hibernate's API to complete the operation of saving customer information to a MySQL databaseConfiguration config =NewConfiguration (). Configure ();//Hibernate Framework Load Hibernate.cfg.xml fileSessionfactory sessionfactory = config.buildsessionfactory ();//Repository Storage Source. Create a corresponding database storage source based on the hibernate configuration File. After the Sessionfactory object is created, it is no longer associated with the configuration Object. Session session = Sessionfactory.opensession ();//equivalent to getting a connection//Open Transactionsession.begintransaction (); //the User's own operation, often also has the update (), delete (), load (), Get () The two are queries, get () is sent directly SQL statement query, load is the use of proxy technology, when you want to query, proxy call hiberate query database, and initializes other properties; CreateQuery () executes a custom SQL statement, but the variable name used is object-specific, unknown origin, or you can use the SQLQuery object to execute the native SQL statement;Session.save (obj); //Transaction Commitsession.gettransaction (). Commit (); Session.close (); Sessionfactory.close ();
2. Session Object Method:
Transaction BeginTransaction () starts the work unit and returns the associated transaction Object. voidCancelquery () cancels the current query Execution. voidclear () clears the session completely. Connection Close () ends the session by releasing and cleaning the JDBC Connection. The criteria Createcriteria (class Persistentclass) creates a new criteria instance for the superclass of a given entity class or entity class. Criteria Createcriteria (String Entityname) creates a new Criteria instance for the given entity Name. Serializable Getidentifier (object Object) Returns the identifier value of the session associated with the given Entity. Query Createfilter (Object collection, String QueryString) Creates a new instance of the query for the given collection and filter Characters. Query CreateQuery (String QueryString) Creates a new instance of the query for the given HQL query character. SQLQuery createsqlquery (string QueryString) Creates a new instance of SQLQuery for the given SQL query string. voidDelete (object Object) Removes the persisted instance from the data store. voiddelete (String entityname, Object Object) Removes the persisted instance from the data store. Session get (String entityname, Serializable Id) returns the given name with the given identifier orNULLpersisted instance (if there is no such persisted instance). Sessionfactory Getsessionfactory () Gets the session factory that created the Conversation. voidRefresh (object Object) re-reads The state of the given instance from the base Database. Transaction gettransaction () Gets the transaction instance associated with the Session. Booleanisconnected () Checks if the current session is Connected. BooleanIsDirty () Does the session contain changes that must be synchronized with the database? BooleanIsOpen () Checks if the session is still Open. Serializable Save (object Object) allocates a generated identity to maintain the given transient state instance. voidsaveorupdate (object) saves (objects) or updates (objects) the given instance. voidUpdate (object Object) updates the persisted instance with an identifier and is a given instance of the Off-state. voidUpdate (String entityname, Object Object) updates the persisted instance with an identifier and is a given instance of the De-state.
3, the use of transaction objects:
An operation that encapsulates a Transaction. When we do additions and deletions and other operations, we must turn on the Transaction. because the session is thread insecure, this is primarily for thread Safety. Ensure the correctness of the Data.
Open transaction: Transaction ts=session.begintransaction ();
Commit Transaction: Ts.commit ();
Rollback transaction: Ts.rollback ();
When the current Thread-bound session is obtained through getcurrentsession, the session is automatically closed and deleted when the transaction is Closed.
4, the XXX class mapping file Xxx.hbm.xml Configuration example (these can be implemented through annotations):
<!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://www.hibernate.org/dtd/hiber Nate-mapping-3.0.dtd "> <hibernate-mapping> <!--define a specific mapping from a Java class to a database table - <classname= "Employee"Table= "EMPLOYEE"> <!--options available - <Metaattribute= "class-description">this class contains the employee Detail. </Meta> <!--primary key, where the generator tag automatically generates a primary key value - <IDname= "id"type= "int"column= "id"> <Generatorclass= "native"/> </ID> <!--Other common values, name is the attribute name in the object, and column is the corresponding name of the Database. - < propertyname= "firstName"column= "first_name"type= "string"/> < propertyname= "lastName"column= "last_name"type= "string"/> < propertyname= "salary"column= "salary"type= "int"/> </class> </hibernate-mapping>
5. Hibernate Annotations
Usage environment: need to install Hibernate 3.x Note pack, copy hibernate-annotations.jar, Lib/hibernate-comons-annotations.jar and lib/from hibernate comment release Ejb3-persistence.jar to your CLASSPATH.
@Entity is interested in a class as an entity Bean.
@table Note provides four properties that allow you to override the name of the table, the directory, and its schema, and you can create unique constraints on the column in the table
@Id Primary key;
@Column Specify the details of a column and a field or attribute mapping, the common Properties are: name,length,nullable,unique;
6, hibernate in the persistence class writing specification;
1), you must provide a default constructor method without Parameters. As the program runs, hibernate uses the reflection mechanism of Java to create an instance of the entity class.
2), All properties must provide a set get method for the public access control
3), attribute should try to use the wrapper type of the base data type (such as Integer)
The base data type cannot express a null value, and the default value for all base data types is not null, which can be a major drawback.
For example, there is a score attribute that indicates that the student score, if 0, indicates that the student did not take the exam or that the student scored 0.
At this point, if you use a wrapper type, you can use NULL to denote null values, students not taking exams, and so On.
4), do not use final modifier entities (will not be able to generate proxy objects for Optimization)
third, the query statement:
1, HQL
object-oriented Sql-like statements;
1), the basic example;
String hql = "from Employee"; // Query the employee class for all database data, The class name can also be used before the completion of the package path; Query query = session.createquery (hql); = Query.list ();
Other syntax:
From Employee as E creates an alias for the class
SELECT E.firstname from Employee E only queries the data for a specific item;
From Employee E WHERE e.id = 10-piece query, Similar to the use of order by, GROUP By,update,delete,insert,sum,max,min,count,avg,disti nct, etc.
2), Pass the parameter example:
String hql = "from Employee E WHERE e.id =: employee_id"; = Session.createquery (hql); Query.setparameter ("employee_id", ten); = Query.list ();
3), Paging
Query.setfirstresult (int Startposition) represents the first line in the result, starting at 0 lines.
Query.setmaxresults (int Maxresult) The maximum number of search results;
2, Standard Query (criteria)
Returns an instance of a persisted object class when using a standard query
1) Basic Example:
Criteria cr = Session.createcriteria (Employee. Class); Cr.add (restrictions.eq ("salary"); // Query the results of all salary=2000, or do not go this line, query all data in the database; similar conditions are gt,lt,like,ilike,between,isnull,isempty,isnotempty ( All of the above are replaced by EQ to make the same Use) List results = cr.list ();
2) Examples of logical conditions:
Criteria cr = Session.createcriteria (Employee. Class); = restrictions.gt ("salary", +); = Restrictions.ilike ("firstnname", "zara%"); // or (or), with (and) LogicalExpression orexp = restrictions.or (salary, name); Cr.add (orexp); = Cr.list ();
3) Paging
Public Criteria Setfirstresult (int firstresult);
Public Criteria setmaxresults (int maxResults);
3, the original SQL statement query
Basic Example:
String sql = "select * from EMPLOYEE WHERE ID =: employee_id"; = Session.createsqlquery (sql); Query.addentity (Employee. class); // returns the entity object, if Setresulttransformer (criteria.alias_to_entity_map) returns the original data; Query.setparameter ("employee_id", Ten); = Query.list ();
Iv. Other Extensions
1, Hiberate can achieve a pair of one or one-to-many, many-to-one, many-to-many mappings;
2, hiberate Cache mechanism, Batch processing methods and the use of interceptors;
3, Attached: hiberate from the entity to the database type automatic mapping;
Hibernate (open Source Object Relational mapping Framework)