Configuration test for Hibernate--hibernate

Source: Internet
Author: User
Tags naming convention

Hibernate

Hibernate is an open source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that maps Pojo to database tables, is a fully automated ORM framework, and Hibernate automatically generates SQL statements, automatically executes, So that Java programmers can use object programming thinking to manipulate the database at will.

Language Features
    • Simplifies development by translating operations on the database into operations on Java objects. Modifies the corresponding record data in a database table by modifying the properties of a persisted object.
    • Provides thread and process two levels of caching to boost application performance.
    • There is a rich mapping approach to translating the relationships between Java objects into relationships between database tables.
    • Block differences between implementations of different databases. In hibernate you only need to specify the currently used database in the form of "dialect", and you can generate appropriate SQL statements based on the actual situation of the underlying database.
    • Non-intrusive: Hibernate does not require the persistence class to implement any interface or inherit any class, Pojo.
Core API

There are 6 APIs for hibernate: Session, Sessionfactory, Transaction, Query, criteria, and configuration. Through these interfaces, persistent objects can be accessed, transaction control.
Session
The session interface is responsible for performing crud operations on persisted objects (the task of crud is to complete the communication with the database, including many common SQL statements). However, it is important to note that the session object is non-thread-safe. At the same time, Hibernate's session differs from the HttpSession in JSP applications. When the term "session" is used, it is actually referring to the session in Hibernate, and later the HttpSession object is called the user session.
sessionfactory
The Sessionfactory interface is responsible for initializing hibernate. It acts as a proxy for the data storage source and is responsible for creating session objects. The factory model is used here. It is important to note that Sessionfactory is not lightweight, because in general, a project typically requires only one sessionfactory, and when you need to manipulate multiple databases, you can specify a sessionfactory for each database.
Transaction
The Transaction interface is an optional API that allows you to opt out of using this interface instead of the underlying transaction code written by Hibernate's designers themselves. The Transaction interface is an abstraction of the actual transaction implementation, which includes JDBC transactions, usertransaction in JTA, and even CORBA transactions. This design is designed to enable developers to use a single transactional interface, allowing their projects to be easily ported between different environments and containers.
Query
The query interface makes it easy to make queries against databases and persistent objects, which can be expressed in two ways: the HQL language or the SQL statement for the local database. Queries are often used to bind query parameters, limit the number of query records, and ultimately perform query operations.
Criteria
The criteria interface is very similar to the query interface, allowing you to create and execute object-oriented, standardized queries. It is important to note that the criteria interface is also lightweight and cannot be used outside the session.
Configuration
The purpose of the configuration class is to configure Hibernate and start it. During Hibernate startup, an instance of the configuration class first locates the location of the mapped document, reads the configuration, and then creates a Sessionfactory object. Although the configuration class plays only a small role throughout the Hibernate project, it is the first object encountered when starting hibernate.

The role of some of Hibernate's packages

Net.sf.hibernate.*
The class of the package is basically the interface class and the exception class
Net.sf.hibernate.cache.*
Implementation class of JCS
net.sf.hibernate.cfg.*
Configuration file Read class
net.sf.hibernate.collection.*
Hibernate collection interface implementation classes, such as List,set,bag, and so on, hibernate to write its own collection interface implementation class is to support the lazy loading
net.sf.hibernate.connection.*
Provider of several database connection pools
net.sf.hibernate.dialect.*
supports a variety of database features, each dialect implementation class represents a database that describes the data types and other features that the database supports, such as whether there are autoincrement, whether there are sequence, whether there are paging SQL, etc.
Net.sf.hibernate. eg.*
Examples used in Hibernate documentation
Net.sf.hibernate.engine.*
The class function of this package is relatively scattered
net.sf.hibernate.expression.*
HQL Supported expressions
net.sf.hibernate.hq.*
HQL implementation
Net.sf.hibernate. id.*
ID Generator
Net.sf.hibernate.impl.*
The core of the package, some important interfaces of the implementation class, such as Session,sessionfactory,query, etc.
Net.sf.hibernate.jca.*
JCA support, wrapping the session as a JCA-enabled interface implementation class
net.sf.hibernate.jmx.*
JMX is used to write the hypervisor of the app server, presumably the implementation of the JMX part of the interface, allowing app server to manage hibernate through the JMX interface
Net.sf.hibernate.loader.*
is also the core of the package, mainly the generation of SQL statements
net.sf.hibernate.lob.*
Blob and CLOB support
net.sf.hibernate.mapping.*
The properties of HBM files are implemented
Net.sf.hibernate.metadata.*
The meta implementation of PO
net.sf.hibernate.odmg.*
ODMG is an ORM standard, this package is the ODMG standard implementation class
Net.sf.hibernate.persister.*
Core packages for mapping between persistent objects and tables
Net.sf.hibernate.proxy.*
Proxy and lazy loading support
Net.sf.hibernate. ps.*
The package is preparedstatment Cache
Net.sf.hibernate.sql.*
The package that generated the JDBC SQL statement
net.sf.hibernate.test.*
Test class, you can use JUnit to test hibernate
Net.sf.hibernate.tool.hbm2ddl.*
Generating DDL with HBM configuration files
net.sf.hibernate.transaction.*
Hibernate Transaction Implementation Class
Net.sf.hibernate.type.*
Data type for properties of persisted objects defined in hibernate
Net.sf.hibernate.util.*
Some tool classes, the role of a more scattered
Net.sf.hibernate.xml.*
XML Data Binding

Hibernate configuration

The structure of the final project is as follows

First step: start configuration Hibernate need to import many packages, this need to download the last Officer network, download the latest version can be,: http://hibernate.org/orm/

After the download is unpacked, find this path in the following directory, import all the jar packages in the Lib created in your eclipse and introduce

Step Two: Create a persistence class and configure its. hbm.xml file

Let's explain what the persistence class is.

Persistence is the mechanism by which program data is transformed between a persistent state and a transient state. Persistence classes (Persistent Class): Classes that can be saved to the database by hibernate and read from the database. 1. Persistent class: Refers to the class whose instance needs to be persisted by hibernate into the database. The persistence class conforms to the JavaBean specification, contains properties, and corresponds to the getxxx () and Setxxx () methods. Note: (1) The Get/set method must conform to a specific naming convention, and the get and set are immediately followed by the name of the property, and the first letter of the property name is capitalized. (2) The Get method of the Name property is GetName (), if written as GetName () or getname () Causes Hibernate to throw the following exception at run time: Net.sf.hibernate.PropertyNotFoundException:Could not find a getters for Porperty name in class Mypack XXX2, if the property of the persisted class is a Boolean type, then his get method name can be prefixed with get, or it can be prefixed with IS. 3. The persistence class has an id attribute that uniquely identifies each object of the account class. This id attribute is called an object identifier (Oid,object Identifier), which is usually represented by an integer. 4. Hibernate requires the persistence class to provide a default constructor with no parameters, and hibernate uses the Java reflection mechanism to invoke Java while the program is running. Lang.raflect.Constructor.newInstance () method to construct an instance of a persisted class.

The popular point is that the table field in the database is how to persist the properties of how to do, the table name is the class name, then the system can generate the set and get method

I first create the User's persistence class: User.java

 Public classUser {Private intID; PrivateString username; PrivateString passowrd;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString getpassowrd () {returnPASSOWRD; }     Public voidsetpassowrd (String passowrd) { This. PASSOWRD =PASSOWRD; }}

When creating its. hbm.xml file, this file location is the same as the persistence class's location, and the same sibling

<?XML version= "1.0" encoding= "UTF-8" standalone= "no"?><!--Generated 2017-8-25 9:27:23 by Hibernate Tools 5.2.3.Final -<!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd "><hibernate-mapping>    <classname= "Com.bean.User"Table= "User">        <IDname= "id"type= "Java.lang.Integer">            <Generatorclass= "Native"/>        </ID>            < Propertyname= "username"type= "Java.lang.String"/>            < Propertyname= "PASSOWRD"type= "Java.lang.String"/>    </class></hibernate-mapping>

Step Three: Configure the Hibernate.cfg.xml file

The location of this file is under SRC, with the package sibling

<?XML version= ' 1.0 ' encoding= ' utf-8 '?><!--The starting line of the standard XML file, version= ' 1.0 ' indicates the version of the XML, encoding= ' Utf-8 ' indicates how the XML file is encoded, and cannot take the first line to account -   <!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hi Bernate.org/dtd/hibernate-configuration-3.0.dtd ">  <!--declaring the start of a hibernate configuration file - <hibernate-configuration>     <!--indicates that the following configuration is configured for Session-factory, Sessionfactory is a class in Hibernate, which is responsible for saving hibernate configuration information and the operation of the session -       <session-factory>        <!--Configure the database driver, hibernate needs to use the database driver when connecting to the database -           < Propertyname= "Connection.driver_class">Com.mysql.jdbc.Driver</ Property>        <!--set the database connection Jdbc:mysql:///zhou, where localhost represents the MySQL server name, this is native, Zhou is the database name -          < Propertyname= "Connection.url">Jdbc:mysql:///zhou</ Property>         <!--user name of the connection database -           < Propertyname= "Connection.username">Root</ Property>         <!--password to connect to the database -           < Propertyname= "Connection.password">123456</ Property>       <!--whether the SQL statement that Hibernate uses is displayed in the background, set to true at development time, makes it easy to make mistakes, and the program can display hibernate's execution SQL statements in the console of eclipse at runtime. The project can be set to false after deployment to improve operational efficiency -           < Propertyname= "Show_sql">True</ Property>          <!--Hibernate.dialect is only the database dialect used by hibernate, which is to use Hibernate to connect to that type of database server. The default is to use this dialect -             < Propertyname= "Hibernate.dialect">Org.hibernate.dialect.MySQLDialect</ Property>        <!--Update updates the database when the project starts, create is the database table that was created by the persistence class at startup -        < Propertyname= "Hbm2ddl.auto">Update</ Property>        <!--XML Injection Method -        <MappingResource= "Com/bean/user.hbm.xml"/>         <!--annotation (annotation) Injection method -        <!--<mapping class= "Com.bean.User"/> -    </session-factory></hibernate-configuration>

Fourth step: Write tests to see if the flow is smooth

 Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//read information about a configuration fileConfiguration config=NewConfiguration (). Configure (); //Create Factory mode for sessionSessionfactory factory=config.buildsessionfactory (); //Open SessionSession session=factory.opensession (); //Open TransactionTransaction transaction=session.begintransaction (); User User= Session.find (User.class, 1); System.out.println (User.getusername ()+"---"+user.getpassowrd ()); //Commit a transactionTransaction.commit (); //close these twoSession.close ();            Factory.close (); }

These are the most basic configuration of hibernate and the smooth flow of the process.

"version Statement" This article is the original blogger articles, reproduced please indicate the source.

Configuration test for Hibernate--hibernate

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.