The first hibernate Program

Source: Internet
Author: User

Hibernate is an excellent open-source ORM framework. It is a relational database Persistence Solution that conforms to the Java language habits. Currently, all mainstream databases are relational databases, that is, the two-dimensional table structure. Java is an object-oriented language,ProgramIs the object manipulated in, so how to store a group of data describing the object to the database? This is what hibernate will do-object data persistence. Of course, persistence can be written to a file system or a database. during large-scale data access, the direct I/O efficiency and ease of use of the program are obviously inferior to the maintainability of the database, therefore, database usage is still a trend.
Hibernate official website is http://www.hibernate.org, to use hibernate of course to download the development kit, as learning, only download core package can be. The current version is 3.3.2-ga.
In the Development Kit documentation, there are help manuals and Chinese characters. This Chinese is only a simple translation, but it can save us time to find the directory. The help manual of Hibernate is well written.
Since we need to use the Java language for database operations, JDBC is essential, and Hibernate is also built on the jdbc api, its essence is JDBC, So we encounter the work that hibernate cannot do, JDBC should also be used directly, and everything is not omnipotent. Knowing the essence, the database driver must be used to interact with the database.
After preparing these things, we can start to build the hibernate development environment. Decompress the hibernate Development Kit and the hibernate3.jar in its root directory is required. Open the lib directory and use all the libraries that hibernate depends on in required. Cglib in bytecode is also required. Do not forget. The role of these class libraries is not explained here. After preparation, you can build a development environment in eclipse.
 
You can create a common Java project, and standalone learning test is enough. The Library and version can be different, which is the least requirement. Hibernate configuration file. cfg. it is recommended to place XML in the root directory of the class path. The package structure can be set to your preferences. Here, domain indicates the domain model/object, and user. java is a persistence class, user. HBM. XML is a ing file between objects and databases. It is meaningless to keep the file naming standard. Test. Java is a test class with the main method. hibernateutil is a simple abstract tool set.
With the project, we will first establish our first application step by step from the database.

XMLCode

 <?  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  = "Hibernate. Connection. username" > Hibernate </  Property  >          <  Property  Name  = "Hibernate. Connection. Password"  > Hibernate </  Property  >          <  Property  Name  = "Hibernate. dialect" > Org. hibernate. dialect. oracledialect </  Property  >          <  Property  Name  = "Current_session_context_class"  > Thread </  Property  >          <  Property  Name = "Show_ SQL"  > True </  Property  >          <  Property  Name  = "Format_ SQL"  > True </  Property  >          <  Mapping  Resource = "Domain/user. HBM. xml"   />      </  Session-factory  >  </  Hibernate-Configuration  > 

The XML root tag is
Property is configured with the driver name, URL, user name, password, and database dialect used by hibernate. These are required attributes. Specifically, the dialect indicates that hibernate can automatically generate the corresponding keywords in SQL when processing certain operations (such as paging) for different database products. The optional attribute is current_session_context_class, which is the way for hibernate to manage the session object context. There are three methods: thread, JTA, and manager. Whether show_ SQL displays restored SQL statements on the console. It is a Boolean value. We recommend that you use it during development. Format_ SQL: whether to format and display the restored SQL statement. It is a Boolean value. After it is used, you can see the easy-to-read SQL statement on the console. Otherwise, a line is displayed.
Hbm2ddl. auto: This attribute is used to configure whether to use hibernate to automatically create tables in the database. The values are as follows: Create/create-drop automatically deletes existing tables at the beginning of the program, the difference is that drop deletes the table after the VM exits, while create does not delete the table when it exits. Update updates the table based on the ing file and can be automatically added or deleted. Validate is a validation, an exception is reported when the table and ing are inconsistent. If you are used to manually creating a table, you don't need to use this attribute. So do I. It is more comfortable and practical to create a table manually. For more attributes, refer to the hibernate documentation.
Another tag is <mapping>. This is the object link ing file configured for hibernate. This tag can be configured with multiple tags, just write them one by one. Note that the package name should be fully written.
The following describes how to create a persistent object. The attributes of this object include the field names in the database, which correspond to each other to create a ing.

Java code

Package  Demo. domain;  Public   Class User Implements  Java. Io. serializable {  Private  Integer ID;  Private  String name;  Private  String phone;  Private  String department;  Private String city;  Private  Java. util. Date hiretime;  Public  User (){}  //  All get and set methods are omitted below }

The user. HBM. xml ing file is configured as follows:

 <?  XML version = "1.0" encoding = "UTF-8"  ?>  <!  Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 //" http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  <  Hibernate-Mapping  >      <  Class  Name  = "Demo. domain. User"  Table  = "Users"  >          <  ID  Name  = "ID"  Column  = "ID" Type  = "Java. Lang. Integer"  Length  = "10"  >              <  Generator  Class  = "Sequence"  >                  <  Param  Name  = "Sequence"  > Seq_hibernate_users </ Param  >              </  Generator  >          </  ID  >          <  Property  Name  = "Name"  Column  = "Name"  Type  = "Java. Lang. String"  Length = "20"  Not-Null  = "True"   />          <  Property  Name  = "Phone"  Column  = "Phone"  Type  = "Java. Lang. String"  Length  = "20"   />          <  Property Name  = "Department"  Column  = "Department"  Type  = "Java. Lang. String"  Length  = "20"   />          <  Property  Name  = "City"  Column  = "City"  Type = "Java. Lang. String"  Length  = "20"  Not-Null  = "True"   />          <  Property  Name  = "Hiretime"  Column  = "Hire_time"  Type  = "Java. util. Date"  Not-Null  = "True"  />      </  Class  >  </  Hibernate-Mapping  > 

the configuration file is flexible and the format can be different, but the basic configuration must be available.
the root tag is , where the label configures the persistence class. The name attribute contains the full name of the class. Table is the name of the table in the database. If no table is written, the table name is the class name by default.
indicates the configuration primary key. name indicates the attribute name of the persistence class, and column indicates the field name of the data table. If column is not written, it is the same as name by default. Type is the type of the attribute. The basic data type here is represented by its packaging class. The Length attribute is the length of the field in the data table. You do not need to view the database dictionary every time after it is specified here. is a primary key generation policy. The types include sequence, increment, and Native. For more information, see the hibernate manual. The sequence of Oracle is used to generate the primary key.
the tag configures the attributes of the object. The name is the attribute name in the persistence class, and the column is the field name of the data table. The rules are the same as above, type is the attribute type, lenth is the length, and not-null is a Boolean value, that is, whether it is not empty.
after the ing file is written, the hibernate configuration is completed. The following is a program for testing.

Import Java. util. date; import Org. hibernate. *; import Org. hibernate. cfg. configuration; import demo. domain. user; public class test {public static void main (string [] ARGs) {configuration Config = new configuration (); config. configure (); // the configuration file name is not hibernate. cfg. in XML, the file name is passed into sessionfactory = config. buildsessionfactory (); // equivalent to the JDBC registration driver session = sessionfactory. opensession (); // equivalent to JDBC's getconnectiontransaction Tx = session. begintransaction (); // The Hibernate operation must start the Transaction user = new user (); // create the Persistent Object User. setname ("Sarin"); User. setphone ("15912345678"); User. setdepartment ("R & D department"); User. setcity ("Dalian"); User. sethiretime (new date (); Session. save (User); // Save the object Tx. commit (); // persists to the database }}

Run

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.