Hibernate4 practices Part 1: getting started with hibernate

Source: Internet
Author: User
Tags xml example
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
  1. <? XML version = '1. 0' encoding = 'utf-8'?>
  2. <! Doctype hibernate-configuration public
  3. "-// Hibernate/hibernate configuration DTD 3.0 // en"
  4. Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>
  5. <Hibernate-configuration>
  6. <Session-factory>
  7. <Property name = "connection. driver_class"> oracle. JDBC. Driver. oracledriver </property>
  8. <Property name = "connection. url"> JDBC: oracle: thin: @ localhost: 1521: orcl </property>
  9. <Property name = "connection. username"> test </property>
  10. <Property name = "connection. Password"> test </property>
  11. <Property name = "connection. pool_size"> 2 </property>
  12. <Property name = "dialect"> org. hibernate. dialect. oracledialect </property>
  13. <Property name = "show_ SQL"> true </property>
  14. <Mapping Resource = "cN/javass/H4/Hello/usermodel. HBM. xml"/>
  15. </Session-factory>
  16. </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
  1. <? XML version = "1.0" encoding = "UTF-8"?>
  2. <! Doctype hibernate-mapping public
  3. '-// Hibernate/hibernate mapping DTD 3.0 // en'
  4. 'Http: // hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
  5. <Hibernate-mapping>
  6. <Class name = "cn. S. h4.hello. usermodel" table = "tbl_user">
  7. <ID name = "UUID">
  8. <Generator class = "assigned"/>
  9. </ID>
  10. <Property name = "userid"> </property>
  11. <Property name = "name"> </property>
  12. <Property name = "Age"> </property>
  13. </Class>
  14. </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
  1. Package CN. ipvs. h4.hello;
  2. Import org. hibernate. Session;
  3. Import org. hibernate. sessionfactory;
  4. Import org. hibernate. transaction;
  5. Import org. hibernate. cfg. configuration;
  6. Public class client {
  7. Public static void main (string [] ARGs ){
  8. Sessionfactory Sf = new configuration (). Configure (). buildsessionfactory ();
  9. Session S = NULL;
  10. Transaction T = NULL;
  11. Try {
  12. // Prepare data
  13. Usermodel um = new usermodel ();
  14. Um. setuuid ("1 ");
  15. Um. setuserid ("id1 ");
  16. Um. setname ("name1 ");
  17. Um. setage (1 );
  18. S = SF. opensession ();
  19. T = S. begintransaction ();
  20. S. Save (UM );
  21. T. Commit ();
  22. } Catch (exception ERR ){
  23. T. rollback ();
  24. Err. printstacktrace ();
  25. } Finally {
  26. S. Close ();
  27. }
  28. }
  29. }
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.