Hibernate learning-Building a simple Hibernate project

Source: Internet
Author: User

Recently, the teacher made a small web application, the junior year to learn a little bit of the Java EE things, also done some web-related XXX management system, are used servlet,jsp these completed, although reluctantly able to complete the task, but the various codes are doped together, not good-looking and maintenance is also very troublesome, A little problem to be debugged for a long time to solve. This time to let oneself learn a little more things, in the framework of the project I used the STRUTS2 implementation of multi-layer code separation, in the database, because the past experience all need to connect to the database for a package, which contains the database connection, record add, query, modify and delete operations, Each use of the process needs to implement a connection object before the operation of the database, and object-oriented programming for different objects, the traditional database operations can only complete a generalization of the task, different objects need different processing methods, So we need a framework to use object-oriented thinking to describe the database to accomplish this task, through the degree Niang found hibernate.

So here I will record the process of learning hibernate framework, so as not to forget after the use of ...

Today I will complete the configuration of the environment and build a simple hibernate project, using the development tools for MYECLIPSE10, the database for MySQL.

Before we do the necessary preparation: Java JDK and MySQL problem I will not say, this is only involved in the project configuration and the necessary code to write, we will first download hibernate jar package, extracted after extracting the several files: Hibernate-annotations.jar,hibernate-commons-annotations.jar,hibernate-entitymanager.jar,hibernate-validator.jar,hibernate 3.jar.

Open MyEclipse After creating a Web project to import the above jar package into the project, here I build a database LAN, there is a table called user, including U_id,u_name,u_password three, Our task is to implement a user class in the program, complete the mapping of the user class to the user table in the database, and add a record to the table.

A hibernate project has an essential two files, one is Hibernate.cfg.xml, which is used to complete the mapping of the project to the database. The other is xxx.hbm.xml, a file that is mapped to a table and class object, implementing a mapping of the class properties to the properties in the table.

First of all to complete the project and database mapping relationship, here need to write a configuration file to complete, named Hibernate.cfg.xml, the path is placed in the SRC root directory.

1 <?XML version= ' 1.0 ' encoding= ' UTF-8 '?>2 <!DOCTYPE hibernate-configuration Public3 "-//hibernate/hibernate Configuration DTD 3.0//en"4 "Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">5 6 <!--Generated by MyEclipse Hibernate Tools.  -7 <hibernate-configuration>8 9     <session-factory>Ten         < Propertyname= "dialect"> One Org.hibernate.dialect.MySQLDialect A         </ Property> -         < Propertyname= "Hibernate.connection.url"><!--fill in the database path - - Jdbc:mysql://127.0.0.1:3306/lan the         </ Property> -         < Propertyname= "Connection.username">Root</ Property><!--fill in the database user name - -         < Propertyname= "Connection.password">Root</ Property><!--fill in the database password - -         < Propertyname= "Connection.driver_class"><!--fill out the database driver - + Com.mysql.jdbc.Driver -         </ Property> +         < Propertyname= "Myeclipse.connection.profile">Lan</ Property> A         <MappingResource= "./user.hbm.xml" /><!--Table Mapping File - at      -     </session-factory> -  - </hibernate-configuration>

Where the table mapping file we say below.

Then write a user class (note that our model class and table content must correspond to one by one, that is, the property is a one by one corresponding relationship):

1 classuser{2     Private intID;3     PrivateString name;4     PrivateString password;5 6      Public voidSetId (intID) {7          This. ID =ID;8     }9      Public voidsetName (String name) {Ten          This. Name =name; One     } A      Public voidSetPassword (String password) { -          This. Password =password; -     } the  -      Public intgetId () { -         returnID; -     } +      PublicString GetName () { -         returnname; +     } A      PublicString GetPassword () { at         returnpassword; -     } -}

The data members correspond to the three elements in the database user table, respectively: U_id,u_name,u_password.

With the user class, our next step is to implement the mapping between the database table user and the model class user in the program, where we need a table mapping file: XXX.hbm.xml (we'll name it as User.hbm.xml in this article)

1 <?XML version= "1.0" encoding= "Utf-8"?>2 <!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en"3 "Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">4 <!-- 5 Mapping file autogenerated by myeclipse persistence Tools6  -7 <hibernate-mapping>8     <classname= "model. User "Table= "User"Catalog= "LAN">9         <IDname= "id"type= "int">Ten             <columnname= "u_id"length= "One" /> One             <Generatorclass= "Assigned"></Generator> A         </ID> -         < Propertyname= "Name"type= "string"> -             <columnname= "U_name"length= " the"Not-null= "true" /> the         </ Property> -         < Propertyname= "Password"type= "string"> -             <columnname= "U_password"length= " the"Not-null= "true" /> -         </ Property> +     </class> - </hibernate-mapping>

Where the class name option is the classpath for the database tables in the project, the table option is the name, and catalog is the database name.

Complete the preparation process described above, we will try to test the project, we add a record to the database code as follows:

1User user;//Define a model2User.setid (1);//set the user's property value3User.setname ("name");4User.setpassword ("Password");5 Session session;6 //Find Hibernate configuration7Configuration config=NewConfiguration (). Configure ();8 //Remove the sessionfactory from the configuration9Sessionfactory factory=config.buildsessionfactory ();Ten //Take a session out of a sessionfactory Onesession=factory.opensession (); ATransaction tran=session.begintransaction (); - //EXECUTE Statement -  This. Session.save (user); the //Commit a transaction -Tran.commit ();//

The above statement implements the effect of adding a record to the database, and the first write thinking is a bit confusing ...

Hibernate learning-Building a simple Hibernate project

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.