Java Hibernate framework for database operations

Source: Internet
Author: User

Before we used a Java class to connect to the MySQL database to implement the database additions and deletions to change the operation---------MySQL chapter;

But there are many kinds of databases, except MySQL, Access, Oracle, DB2 and so on, and each database language is different;

At this point, we need a framework to achieve compatibility with mainstream database operations, and to streamline the operation process, Hibernate is one of

Mainstream framework. Here we use MyEclipse as the development software to sample.

1. Establishing a database connection

Open the MySQL database service, and in MyEclipse, Window-->show view-->db Browser, opens the Database window;

Right click New, you are asked to enter the database information you opened and connect it, because I use MySQL here, so choose

The information is as follows:

Driver Template:mysql connecter/j;

Driver Name: Custom, but it is recommended to use the name associated with the project;

Conection Url:jdbc:mysql://localhost:8090/eco (write the address of your own database here);

Driver Jars: Here need to add a database driver, here is the JDBC driver of MySQL, download well in advance;

Then the user name, password, if the information is correct, then the connection is successful.

2. Create a new Java project and add hibernate features to it

The process is as follows:

Right-click Project-->myeclipse-->add Hibernate capabilities--> Select version, I choose the 4.1 version here, and then choose Hibernate

Core package, the next step;

Select the previously connected database--Here you will generate a Hibernate.cfg.xml file that currently stores the connection information for the database--Select a

Directory to place Hibernatesessionfactory.java this class-->finish.

The methods in this class will be used in subsequent database operations, where Hibernate has been written for us, and the subsequent call is OK.

3. Reverse generation of persistence classes

Create a table in the database and Add attribute fields to it, such as id,name,age and so on, where we use a table to

To reverse-build the persisted class (and the class file corresponding to the attribute in the table), after the table information is set, the right-click Table-->hibernate Reverse Engineer;

This generates a persisted class and an XML file about the class-to-table mapping relationship, and the system lets you choose a placement path, pojo<>db field

Hook, which represents the project-to-database mapping-->type type: Java,id field (primary key) type, which I chose here is assigned (manual input),

If the ID information is filled with the study number, so it is more reliable, if there is no real meaning, then choose Native, he will be more database category from

MySQL will be the self-increment-->finish.

4. mapping files and database information files

Student.hbm.xml

1 <hibernate-mapping>2     <classname= "Student." Student "Table= "Student"Catalog= "Eco">3         <IDname= "id"type= "Java.lang.Integer">4             <columnname= "id" />5             <Generatorclass= "Assigned" />6         </ID>7         < Propertyname= "User"type= "Java.lang.String">8             <columnname= "User"length= "+"Not-null= "true" />9         </ Property>Ten         < Propertyname= "Password"type= "Java.lang.String"> One             <columnname= "Password"length= "+"Not-null= "true" /> A         </ Property> -         < Propertyname= "Age"type= "Java.lang.Integer"> -             <columnname= "Age"Not-null= "true" /> the         </ Property> -     </class> - </hibernate-mapping>

This represents the mapping of the student persistence class under the student package to the database table student, which is a member variable in the persisted class.

column is the attribute field of the database table, which corresponds to one by one, and the ID tag indicates that the field is the primary key.

Hibernate.cfg.xml

1 <session-factory>2         < Propertyname= "dialect">3 Org.hibernate.dialect.MySQLDialect4         </ Property>5         < Propertyname= "Connection.url">6 Jdbc:mysql://localhost:8090/eco7         </ Property>8         < Propertyname= "Connection.username">Root</ Property>9         < Propertyname= "Connection.password">Root</ Property>Ten         < Propertyname= "Connection.driver_class"> One Com.mysql.jdbc.Driver A         </ Property> -         < Propertyname= "Myeclipse.connection.profile"> - Mysqljdbc the         </ Property> -          -         <MappingResource= "Student/student.hbm.xml" /> -     </session-factory>

This is the database information file and mapping file registration, in fact, the property tag can also add several:

<property name= "Show_sql" >true</property> indicates that SQL statements are printed in the background while database operations are in progress

<property name= "Fomat_sql" >true</property> means to format the printed SQL statement

<property name= "Hbm2ddl.auto" >create</property> adding records to the table operation processing, create delete new, update updates

5. Unit Testing

Here's an episode, the unit test, with unit testing, we don't have to create a new program entry to run the Main method as before

Code function, you can choose to run the function block (method).

Start by importing the jar package for the JUnit Unit Test tool for the project, and then create a new test class;

1  Public classStudenttest {2     PrivateSession session =hibernatesessionfactory.getsession ();3     PrivateTransaction Transaction;4 5 @Before6      Public voidinit () {7         //Open Transaction8Transaction =session.begintransaction ();9     }Ten  One @After A      Public voiddistory () { -         //Commit a transaction - transaction.commit (); the         //Close Session - session.close (); -         //Close Session Factory - hibernatesessionfactory.getsessionfactory (). Close (); +     } -  + @Test A      Public voidTestadd () { at         //Transaction Specific Content -Student s =NewStudent (334, "Orange Mulberry", "12646574", 26); - Session.save (s); -     } -  -}

Let's take a look at these three annotations:

@Before the equivalent of initialization, we implemented the open transaction in this method;

@Test here to arrange the functions that you want to achieve, to decorate what is really to be done;

@After is equivalent to destruction, where we first submit the task to the database, and then close the session/session factory, if not shut down, as the connection to the database

, it is possible to overflow the connection pool, so we close the session after the task has ended.

6. Adding and deleting changes

1     @Test2      Public voidTestadd () {3         //Transaction Specific Content4Student s =NewStudent (334, "Orange Mulberry", "12646574", 26);5 Session.save (s);6     }7 @Test8      Public voidtestupdate () {9         //Transaction Specific ContentTenStudent s = (Student) session.get (Student.class, 1); OneS.setage (25); A Session.update (s); -     } - @Test the      Public voidTestdelete () { -         //Transaction Specific Content -Student s = (Student) session.get (Student.class, 1); - Session.delete (s); +     } - @Test +      Public voidTestget () { A         //Transaction Specific Content atStudent s = (Student) session.get (Student.class, 1); - System.out.println (s); -}

The above is the database of additions and deletions to check the function, is not very convenient, no longer have to think about splicing SQL statements,

Student.class represents the class type of the Student class and is the knowledge of Java reflection.

Java Hibernate framework for database operations

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.