Getting started in Hibernate (original)

xiaoxiao2021-03-06  103

Hibernate entry (original) 2004/08/22 Author: Umbrellas (geezer)

----------------------------------------------

This article configuration environment: jbuilder xjdk 1.4.2mysql 4.0.11 driver: mm.mysql-2.0.4-bin.jar (org.gjt.mm.mysql.driver) Hibernate 2.1

Unzip Hibernate

Open JB, New Enginee, named: Hibernate Join Hibernate Need Package with MySQL Drive Steps: File-> New Project-> Name Enter Hibernate, Directory Select the path you want to store this project -> Next

-> Required libraries-> add-> new-> name Enter the Hibernate package you want to set

-> Add-> Select your Hibernate to decompress the directory, select all JAR packages in this directory with all JAR packages in the lib directory, and add your mysql driver package.

Then press OK, NEXT.

Create a new class, named hello_bean.java, the code is as follows:

Package hibernate;

Import java.io.serializable;

/ *** @Author Geezer * QQ: 9986986 MSN: Geezer_hot@hotmail.com

Public class hello_bean implements serializable {private string name; // The name of Name and Address and ID can be fixed, there will be no effect. But the GET and SET methods are not. Because it is to correspond to the database and the configuration file. Private string address; private int id;

Public Hello_Bean () {

}

Public Hello_Bean (String Name, String Address) {// Constructor, I believe you will understand this chapter, this .Name = name; this.address = address;}

Public String getName () {// This method name must be the same as the corresponding name in the Hello_Bean.hbm.xml file, the following will be returned name;

Public void setname (String name) {this.name = name;}

Public string getaddress () {return address;}

Public void setaddress (String address) {this.address = address;} public int getId () {// must-only Return ID;

Public void setid (int ID) // must be required {this.id = id;}

}

Complete this step after compiling

Copy the hibernate.properties in the SRC folder in the directory after Hibernate to copy the Classes directory of the log4j.properties file to your project directory.

(For example, in the hibernate / classs / directory),

Open hibernate.properties file, find

## Hypersonicsql

hibernate.dialect net.sf.hibernate.dialect.HSQLDialecthibernate.connection.driver_class org.hsqldb.jdbcDriverhibernate.connection.username sahibernate.connection.passwordhibernate.connection.url jdbc: hsqldb: hsql: //localhosthibernate.connection.url jdbc: hsqldb : TestHibernate.Connection.URL JDBC: HSQLDB :. Change to

## Hypersonicsql

# Hibernate.dialect net.sf.hibernate.dialect.HSQLDialect # hibernate.connection.driver_class org.hsqldb.jdbcDriver # hibernate.connection.username sa # hibernate.connection.password # hibernate.connection.url jdbc: hsqldb: hsql: / /localhost#hibernate.connection.url jdbc: hsqldb: test # hibernate.connection.URL JDBC: HSQLDB :.

Found again

## mysql

# Hibernate.dialect net.sf.hibernate.dialect.MySQLDialect # hibernate.connection.driver_class org.gjt.mm.mysql.Driver # hibernate.connection.driver_class com.mysql.jdbc.Driver # hibernate.connection.url jdbc: mysql : ///test#hibernate.connection.username root # hibernate.connection.password

Change to

## mysql

hibernate.dialect net.sf.hibernate.dialect.MySQLDialecthibernate.connection.driver_class org.gjt.mm.mysql.Driverhibernate.connection.url jdbc: mysql: // localhost: 3306 / testhibernate.connection.username roothibernate.connection.password

Please change to your own URL

Create an empty file after completion, save in the same folder in your project class file (such as hibernate / class / hibernate / directory), the file name is: Hello_Bean.hbm.xml content is as follows:

Slightly explanation, Name refers to the class of your generated table,

TABLE specifies the name of the database table you want to create, free to modify, no impact.

Set the primary key ID, here the value ID of Name is associated with the method of Hello_Bean.java corresponds to the setID, don't take this, hibernate will be called automatically, the configuration is good, column The value is the field name to be generated, which can be freely modified, no impact.

property allows the ID of the primary key to increase the ID (automatically plus 1)

Here "Name" corresponds to the getName method in Hello_Bean.java, Column is to generate Field Name

Add a field name and address, note that the type attribute type here is string, if the type here is different from the type set in Hello_Bean.java is not the same.

Save after modification.

Finally, in JB, create a class, name is Hello.java, I will explain step by step, the code is as follows:

Package hibernate;

import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.tool.hbm2ddl.SchemaExport; import net.sf.hibernate.Session; import net.sf.hibernate.Query Import net.sf.hibernate.hibernate; import net.sf.hibernate.type.longtype; import net.sf.hibernate.Transaction; import net.sf.hibernate.scrollableresults; import java.util. *; / *** @Author Geezer * QQ: 9986986 MSN: Geezer_hot@hotmail.com*/

Public class hello {

Public hello () {

}

Public static void main (string [] args) throws exception {

Configuration cfg = new configuration (). Addclass (hello_bean.class); // Initialization Factory sessions = cfg.buildsessionFactory (); // Get a sessionFactory object with the buildsessionFactory method

Session session = sessions.opensession (); // Review a session with the sessionFactory's OpenSession method

New SchemaExport (CFG) .create (True, True); // This sentence means a creation table, after the first run, it is created after the table will add this line. If you don't comment out later, you will delete the previously created table and re-build one.

Hello_bean my_hibernate = new hello_bean (); // Get a Hello_Bean object my_hibernate.setName ("my_name"); // Set the Name value of the Hello_Bean object is my_name, which is actually the value of the string my_name as the database field name. The database field name is corresponding to the getName in the Hello_Bean class, the setName method is corresponding. Form a mapping relationship. my_hibernate.setaddress ("my_address"); //

Session.save (my_hibernate); // This sentence is important, write my_hibernate objects into the database (Name in my_hibernate object, we have just set a value, will write the Name, Address value into the database)

Session.flush (); session.close ();

/ / The above is a simple insertion data and the first running metrics. Here I introduce the method of deleting and modifying. The following code I added a comment, what method you need (delete, modify, loop) Value) If you go to the comment, you can have HSQL. It should be relatively simple. Let's take a look at the example, you should understand, you will not talk. There are three ways to traverse the database, named Query, Find, Iterate, Query, and Find return a list interface, Iterate returns an Iterator, and the specific method can view these classes.

// Delete data / * int a = session.delete ("from hello_bean where id = 1); // If you do not find the ID of 1, return 0, if you find a return 1, here's Hello_Bean is our Hello_Bean class He corresponds to the database table, so we are here to code database tables directly with Hello_Bean. System.out.println (a); session.flush (); session.close (); * /

// Query method query data / * hello_bean my_hibernate = null; query q = session.createQuery ("from helry q = session.createQuery (" from hello_bean where name =? "); // Here? It's almost the same as the JDBC's PreparedStatement method, but here is the beginning of 0, and JDBC is 1 start. // q.setstring (0, "my_name"); // q.setfirstResult (0); // This sentence means that the query results are listed from the first few rows to the data // q.setMaxResults (3); // This sentence means how many data is taken, just like the SQL Server's TOP method and the mysql's Limit method. // scrollableresults sc = q.scroll (); // Get a scrollableresults, can be scrolled, if your database supports the free movement of the cursor, that is, if you can determine whether the query results are values, or move to the next line. Record, etc.. // if (! sc.next ()) // {// system.out.println ("Did not find the data you need"); //} session.flush (); // If you use scrollableresults, please This line comes out of session.close (); // If you use scrollableresults, comment this line out of List L = Q.List (); // Return to a list interface, used to traverse the result set for (INT i = 0 i

* /// Find method query data / * hello_bean my_hibernate = null; list = session.find ("from hello_bean"); session.flush (); session.close ();

For (int i = 0; i

// Iterate method query data / * hello_bean my_hibernate = null; item q = session.iterate ("from hello_bean"); while (q.hasnext ()) {my_hibernate = (hello_bean) q.next (); system.out. Println (My_Hibernate.getName ());

* /

// Modify data / * query qq = session.createQuery ("from hello_bean"); hello_bean my_hibernate = (Hello_Bean) session.load (Hello_Bean.class, New Integer (2)); // Here New Integer (2) Meaning It is the line of data that modifies the ID 2 in the table, which must be an object of a packaging class. If Int is used, it will be wrong. MY_HIBERNATE.SETNAME ("Geezer"); // change the Name field value of the line of the ID 2 to "Geezer" session.flush (); session.close (); * /

}

}

Finally, you can run.

If you are unclear, you can download the example of this article to see it, run.

Download address: http://www.phpx.com/happy/attachment.php? S = & postid = 599353

After downloading, you can use JB to open hibernate.jpx. Add Hibernate and MySQL driver before using it, and if you don't know, look at the beginning of this chapter.

Common error: caused by: org.dom4j.documentexception: invalid byte 2 of 2-byte UTF-8 SEQUENCE. NESTED Exception: Invalid Byte 2 of 2-byte UTF-8 SEQUENCE. If this line error shows your XML configuration file There is an irregular character, check it.

Net.sf.hibernate.mappingexception: Error Reading Resource: Hibernate / Hello_Bean.hbm.xml

If you have this line error, your Hibernate's XML configuration file is wrong.

Net.sf.hibernate.mappingexception: resource: hibernate / hello_bean.hbm.xml not found

If you appear this line error Description Hibernate's XML configuration file is not found, you should put the XML file in the same directory with your class file, this article is placed in the hibernate / class / hibernate / directory, which is hello_bean. Class class files together.

Net.sf.hibernate.propertyNOTFOUNDEXCEPTION: COULD NOT FIND A SETER for Property Name In Class Hibernate.Hello_Bean

If this line error occurs, the value of the field name Name set in your XML file is inconsistent with the getxxx or setxxx method in the Hello_Bean.java class.

Net.sf.hibernate.HibernateException: JDBC Driver Class Not Found: Org.gjt.mm.mysql.driver If this line error shows that your MySQL driver does not add JB Current or not in ClassPath.

转载请注明原文地址:https://www.9cbs.com/read-124373.html

New Post(0)