Part 1: getting started with hibernate what is hibernate? What is a lightweight ORMapping framework ORMapping principle (object relational mapping) Basic ORMapping rule: 1: Class corresponds to table 2: class attributes correspond to table fields 3: class instances correspond to a specific record in the Table 4: A class can correspond to multiple tables, A table can also correspond to tables in Class 5: DB without a primary key, but the primary key field 6 must be set in the object: Relationship between tables in dB (for example, foreign keys) ing to the relationship between objects 7: The number and name of attributes in the object can be different from the number and name of fields defined in the table. Basic Implementation Method of ORMapping: Use JDBC and use SQL to operate the database, it only depends on dynamic generation or manual code writing. Have we implemented ORMapping? What does hibernate Do: Hibernate is mainly used to implement ing between Java objects and tables. In addition, it also provides data query and data retrieval methods, this greatly reduces the time required to manually process data using SQL and JDBC during development. Hibernate aims to release 95% of data persistence-related programming tasks for developers. For data-centric programs, they often only use stored procedures in the database to implement business logic. hibernate may not be the best solution; hibernate is the most useful for Java-based middle-tier applications that implement object-oriented business models and business logic. Hibernate can help you eliminate or wrap the SQL code for specific vendors, and help you convert the result set from table-based representation to a series of objects. A very brief high-level summary of the hibernate architecture diagram the "minimal" Architecture Scheme of the hibernate runtime architecture, requiring applications to provide their own JDBC connections and manage their own transactions. This solution uses the minimum subset of the hibernate API. The "Comprehensive Solution" architecture solution abstracts the application layer from the underlying JDBC/jta api, and enables hibernate to process these details. Sessionfactory (Org. hibernate. sessionfactory) is thread-safe (immutable) for memory images compiled for a single database ing relationship ). It is the factory that generates the session and uses connectionprovider. Session (Org. hibernate. Session) indicates a single-threaded object for interaction between applications and the persistent storage layer. This object has a short lifetime and hides JDBC connections. It is also the transaction factory. The transaction (Org. hibernate. Transaction) application is used to specify the objects in the range of atomic operation units. It is single-threaded and has a short life cycle. It isolates applications from specific underlying JDBC, JTA, and CORBA transactions through abstraction. Connectionprovider (Org. hibernate. Connection. connectionprovider) is used to generate a JDBC connection factory ). It isolates applications from the underlying datasource or drivermanager through abstraction. It is only for developers to expand/implement and is not exposed to applications. Transactionfactory (Org. hibernate. transactionfactory) generates the factory of the transaction object instance. It is only for developers to expand/implement and is not exposed to applications.
To learn how to do helloworld, you must first understand what needs to be done. Based on the previous study, you must complete the following work for basic hibernate applications: object, database table, two configuration files, client program to call the hibernate interface for operations. The simplest way to build the environment: add all the jar packages under lib/required in the hibernate-release-4.0.0.beta4.zip package to the project library, also need to add slf4j implementation package slf4j-log4j12-1.5.8.jar and log4j implementation package log4j-1.2.16.jar, also don't forget to add the JDBC driver jar package to the library object how to do 1: that is, the VO method (the rule is also the four points) learned earlier. 2. A public parameter must be a constructor. Currently, Vo is generally not a constructor, there is one by default, but when writing the constructor, you must note that the previous constructor with the public parameter is null. 3: A identifier attribute is required. 4: use a non-final class (because you need to use a proxy to delay object loading) 5: Set to construct an object: CN. javass. h4.hello. usermodel, which has four attributes: UUID, userid, name, and age. If you create a table in the database and set it to tbl_user, field: UUID, userid, name, and age, configure XXX. cfg. XML 1: The default name is hibernate. cfg. XML 2: It is stored in the root directory of the current classes. during development, it can be stored in the SRC root. 3. It mainly includes the following four configurations: (1) connection to dB (2) optional configuration (3) resource file registration (4) Level 2 Cache 4: Find a hibernate in the hibernate release package during configuration. cfg. for example, you can use hibernate under "\ project \ hibernate-documentation \ Quickstart \ tutorials \ basic \ SRC \ test \ resources. cfg. XML Example 5: Java code:
View copies to clipboard and print
- <? XML version = '1. 0' encoding = 'utf-8'?>
- <! Doctype hibernate-configuration public
- "-// Hibernate/hibernate configuration DTD 3.0 // en"
- Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>
- <Hibernate-configuration>
- <Session-factory>
- <Property name = "connection. driver_class"> oracle. JDBC. Driver. oracledriver </property>
- <Property name = "connection. url"> JDBC: oracle: thin: @ localhost: 1521: orcl </property>
- <Property name = "connection. username"> test </property>
- <Property name = "connection. Password"> test </property>
- <Property name = "connection. pool_size"> 2 </property>
- <Property name = "dialect"> org. hibernate. dialect. oracledialect </property>
- <Property name = "show_ SQL"> true </property>
- <Mapping Resource = "cN/javass/H4/Hello/usermodel. HBM. xml"/>
- </Session-factory>
- </Hibernate-configuration>
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">Configure XXX. HBM. XML 1: the same name as the described class, for example, usermodel. HBM. XML 2: The storage location and the description class are stored in the same folder. 3. The configuration mainly includes the following four parts: (1) ing of classes and tables (2) ing of primary keys (3) mappings between class attributes and DB fields (4) 4: you can find an example in the hibernate release package during configuration, for example, you can use the customer under "\ project \ hibernate-core \ SRC \ test \ Java \ org \ hibernate \ test \ Cid. HBM. XML Example 5: Java code:
View copies to clipboard and print
- <? XML version = "1.0" encoding = "UTF-8"?>
- <! Doctype hibernate-mapping public
- '-// Hibernate/hibernate mapping DTD 3.0 // en'
- 'Http: // hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
- <Hibernate-mapping>
- <Class name = "cn. S. h4.hello. usermodel" table = "tbl_user">
- <ID name = "UUID">
- <Generator class = "assigned"/>
- </ID>
- <Property name = "userid"> </property>
- <Property name = "name"> </property>
- <Property name = "Age"> </property>
- </Class>
- </Hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD 3.0//EN' 'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>Client File: Java code:
View copies to clipboard and print
- Package CN. ipvs. h4.hello;
- Import org. hibernate. Session;
- Import org. hibernate. sessionfactory;
- Import org. hibernate. transaction;
- Import org. hibernate. cfg. configuration;
- Public class client {
- Public static void main (string [] ARGs ){
- Sessionfactory Sf = new configuration (). Configure (). buildsessionfactory ();
- Session S = NULL;
- Transaction T = NULL;
- Try {
- // Prepare data
- Usermodel um = new usermodel ();
- Um. setuuid ("1 ");
- Um. setuserid ("id1 ");
- Um. setname ("name1 ");
- Um. setage (1 );
- S = SF. opensession ();
- T = S. begintransaction ();
- S. Save (UM );
- T. Commit ();
- } Catch (exception ERR ){
- T. rollback ();
- Err. printstacktrace ();
- } Finally {
- S. Close ();
- }
- }
- }
Package CN. javass. h4.hello; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. transaction; import Org. hibernate. cfg. configuration; public class client {public static void main (string [] ARGs) {sessionfactory Sf = new configuration (). configure (). buildsessionfactory (); Session S = NULL; transaction T = NULL; try {// prepare the data usermodel um = new usermodel (); um. setuuid ("1"); um. setuserid ("id1"); um. setname ("name1"); um. setage (1); s = SF. opensession (); t = S. begintransaction (); S. save (UM); T. commit ();} catch (exception ERR) {T. rollback (); err. printstacktrace ();} finally {S. close ();}}}
Test:Run the client file directly in Elipse. After the operation is complete, you will see the output in the console: "hibernate: insert into tbl_user (userid, name, age, UUID) values (?, ?, ?, ?)", Open the data table of the database and you will see that a value has been added.
Note:
1:Sessionfactory Sf = new configuration (). Configure (). buildsessionfactory (); this statement reads hibernate. cfg. xml and creates a session factory, which is thread-safe. The default value is "hibernate. cfg. xml". If the file name is not "hibernate. cfg. xml", it must be specified as follows: sessionfactory Sf = new configuration ().
Configure ("S. cfg. xml ").Buildsessionfactory ();
2:Session is the main hibernate interface used by applications. It is equivalent to the JDBC connection + statement/preparedstatement function and is thread unsafe. 3: In hibernate4, we do not recommend using the configuration class anymore, but use serviceregistrybuilder and metadatasources instead. The new syntax is roughly as follows: serviceregistrybuilder builder = new serviceregistrybuilder (). configure (); builder. applysetting ("connection. driver_class "," oracle. JDBC. driver. oracledriver "); builder. applysetting ("connection. URL "," JDBC: oracle: thin: @ l Ocalhost: 1521: orcl "); builder. applysetting ("connection. username "," ztb "); builder. applysetting ("connection. password "," ztb "); builder. applysetting ("connection. pool_size "," 2 "); builder. applysetting ("hibernate. dialect "," org. hibernate. dialect. oracledialect "); builder. applysetting ("show_ SQL", "true"); metadatasources sources = new metadatasources (builder. buildserviceregistry (); sources. addresource (" CN/javass/H4/Hello/usermodel. HBM. XML "); metadataimpl metadata = (metadataimpl) sources. buildmetadata (); sessionfactory Sf = metadata. getsessionfactorybuilder (). buildsessionfactory. 4: The transaction used here is the transaction of hibernate. It must exist and cannot be removed. Why must we have this hibernate transaction? Take helloworld For example: Video matching PPT, video address 【
Hibernate4 practice-exclusive video course: original content is transferred from, please note 【
Http://sishuok.com/forum/blogpost/list/2461.html]