Hibernate entry

xiaoxiao2021-03-06  62

Author: Umbrellas (geezer)

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

This article configuration environment:

JBuilder X

JDK 1.4.2

Mysql 4.0.11 Driver: mm.mysql-2.0.4-bin.jar (org.gjt.mm.mysql.driver)

Hibernate 2.1

Unzip Hibernate

Open JB, New Engineering, named: Hibernate

Join Hibernate needs to drive with MySQL

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 imports serializable {

Private string name; // Here Name and Address and ID name can be set, there will be no effect. But the GET and SET methods cannot be. 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 after reading 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, will be detailed below

Return 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-have

Return ID;

}

Public void setid (int ID) // must

{

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.dialev Net.sf.hibernate.dialect.hsqldiaLect

Hibernate.Connection.driver_class org.hsqldb.jdbcdriver

Hibernate.connection.username sahibernate.connection.password

Hibernate.Connection.url JDBC: HSQLDB: HSQL: // localhost

Hibernate.Connection.URL JDBC: HSQLDB: TEST

Hibernate.Connection.url JDBC: HSQLDB :..

Change to

## Hypersonicsql

# hibernate.dialect net.sf.hibernate.dialect.hsqldiaforct

# 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.dialev Net.sf.hibernate.dialect.mysqldiact

# 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.Dialev Net.sf.hibernate.dialect.mysqldiaLect

Hibernate.Connection.driver_class org.gjt.mm.mysql.driver

Hibernate.Connection.URL JDBC: MySQL: // localhost: 3306 / test

Hibernate.Connection.username root

Hibernate.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 / classes / hibernate / directory), the file name is: hello_bean.hbm.xml

The content is as follows:

"- // Hibernate / Hibernate mapping DTD 2.0 // en"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

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.hibiBernate.cfg.configuration;

Import Net.sf.hibActory;

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.hibelresUlts;

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); // initialized with hello_bean.class class

SessionFactory 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 GetName in the Hello_Bean class, the setName method is corresponding of. 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), take the annotation.

HSQL is relatively simple, let's take a look at the example, you should understand, here is not talking.

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 it back 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 hello_bean");

// query q = session.createQuery ("from hello_bean where name =?"); // Here? The difference between the JDBC's PreparedStatement method, but here is starting with 0, JDBC is 1 start. // q.setstring (0, "my_name");

// q.setfirstResult (0); // This sentence means that the results of the query start from the first few rows.

// q.setMaxResults (3); // This sentence means how many data is taken, just like SQL Server's TOP method and 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 (); // Please comment this line if you use scrollableresults

Session.Close (); // If you use scrollableresults, please comment this line.

List l = q.list (); // Returns a list interface to traverse the result set

For (int i = 0; i

MY_HIBERNATE = (Hello_Bean) L.GET (i); // Get a My_Hibernate object from list

System.out.println (my_hibernate.getname ()); // Call the GetName method of the My_Hibernate object to get the value of the database Name field

}

* /

/ / Find method query data

/ *

Hello_bean my_hibernate = NULL;

List Q = session.find ("from hello_bean");

Session.flush ();

session.close ();

For (int i = 0; i

{

My_Hibernate = (Hello_Bean) Q.GET (i);

System.out.println (My_Hibernate.getName ());

}

* /

// Iterate method query data

/ *

Hello_bean my_hibernate = NULL;

Iterator Q = Session.Iterage ("from hello_bean");

While (q.hasnext ())

{

MY_HIBERNATE = (Hello_Bean) q.next ();

System.out.println (My_Hibernate.getName ());

}

* /

//change the data

/ *

Query QQ = session.createQuery ("from hello_bean");

Hello_Bean my_hibernate = (hello_bean) session.load (Hello_Bean.class, New Integer (2));

// The new integer (2) means that the line data of the ID 2 in the table is modified, and must be an object of a packaging class. If Int is used, if Int is used, it will be wrong.

My_Hibernate.setName ("Geezer"); // Change the Name field value of the line data 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.

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 is wrong, your XML configuration file has 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 you have this line error, your MySQL driver does not add JB Current or not in ClassPath.

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

New Post(0)