An introduction to Eclipse's quick-start hibernate

Source: Internet
Author: User
Tags date sql mysql net string version variable jboss

This article is mainly about the introduction of hibernate, the example is very simple, is to add a username and password to the datasheet. I used three different methods, one is to write code directly, write HBM mapping file, and so on, one is to generate code by HBM mapping file, one is to generate HBM mapping file by code. Using some automation tools, Xmlbuddy is used to edit XML files, and the JBoss Eclipse IDE is used to write Doclet tags. This article also discusses some of the techniques used in eclipse, such as creating "User libraries", "generating Getter and Setter", and so on.

About the use of some software skills, my previous articles are mentioned, here is not much to say, if necessary, will be prompted.

First, download, install and configure 1. Required Software

Ant 1.6.2http://ant.apache.org

Download Http://mirror.apache.or.kr/ant/binaries/apache-ant-1.6.2-bin.zip

Eclipse 3.0.1 and Language packs

Reference: Http://blog.csdn.net/javamxj/archive/2004/10/11/131952.aspx

XDoclet 1.2.2 http://xdoclet.sourceforge.net/xdoclet/

Download Http://prdownloads.sourceforge.net/xdoclet/xdoclet-bin-1.2.2.zip?download

Xmlbuddy http://www.xmlbuddy.com/

Download Xmlbuddy 2.0.38 JBoss Eclipse idehttp://www.jboss.org/products/jbosside

To see the description, you need to pick the version that corresponds to the eclipse you are using, select Jbosside-1.4.1-e30.zip, which is its mirrored download address:

Http://prdownloads.sourceforge.net/jboss/jbosside-1.4.1-e30.zip?download Hibernate http://www.hibernate.org/

Download Hibernate 2.1.8

Http://prdownloads.sourceforge.net/hibernate/hibernate-2.1.8.zip?download also has to takeHibernate Extensions 2.1.3Downloaded, it contains a few tool classes.

Download Http://prdownloads.sourceforge.net/hibernate/hibernate-extensions-2.1.3.zip?download

MySQL4.1.8

Reference: Http://blog.csdn.net/javamxj/archive/2005/01/13/251861.aspx

Note the need for Mysql-connector-java-3.0.16-ga-bin.jar files

   2. Installation and Configuration

This highlights the need to set the ant_home in the environment variable and point it to the ANT installation directory and add "%ant_home%\bin" to the path variable value to reference the Java environment variable settings. · Xmlbuddy and Jboss-ide I have to use links to install, reference http://blog.csdn.net/javamxj/archive/2004/10/11/132311.aspx

To Create a library folder:Under D disk, create a new Java directory, create a new hibernate subdirectory under this directory, and create a new Lib subdirectory under this subdirectory.

D:\

-java

-hibernate

-lib

· The download of the Hibernate-2.1.8.zip decompression, such as the extracted directory named hibernate-2.1, the directory under the Hibernate2.jar copy to the previously established Lib directory, that is, the D:\java\Hibernate\lib directory;

· The following files in the Lib subdirectory under the hibernate-2.1 directory are then copied to this Lib directory as well:

Jta.jar Cglib-full-2.0.2.jar Commons-collections-2.1.1.jar Commons-logging-1.0.4.jar Commons-lang-1.0.1.jar Dom4j-1.4.jar Ehcache-0.9.jar Log4j-1.2.8.jar Odmg-3.0.jarodmg-3.0.jar

• Unzip the hibernate-extensions-2.1.3.zip and copy the Velocity-1.3.1.jar and Jdom.jar from the Hibernate-tools.jar and subdirectory Lib in its subdirectory tools to D:\ In the Java\hibernate\lib directory

• Unpack the Xdoclet-bin-1.2.2.zip, Xdoclet-1.2.2.jar, Xdoclet-hibernate-module-1.2.2.jar, Xjavadoc-1.1.jar, in its subdirectory lib, Xdoclet-xdoclet-module-1.2.2.jar also copied to the D:\java\Hibernate\lib directory

· Finally, copy the Mysql-connector-java-3.0.16-ga-bin.jar file to this Lib directory.

In this way, the library files that need to be used are ready, and if this is a hassle, you can copy the jar files to the Lib directory. The following describes how to set up the user library in eclipse.

   set up the user library• Window-> Preferences->java-> Build Path-> User Library,





· And then click Add Jar






In this way, a user library file is done, and if you want to update eclipse, you can pilot it out and then import it.

This makes it easy to manage the library files and is convenient if you need to replace them or upgrade them.

  Setting the Build Path

· Click the Menu window-> Preferences, and the following are configured in preferences:

java-> Build Path






  Second, the project practice

  
Here a simple program to demonstrate hibernate configuration and functionality, in this example, some of the operations, in fact, will use some automation tools to complete, and not necessarily manual operation of the set, this side of the full manual reason, is that you can know the basic hibernate process.

This is the structure of the entire project:






OK, let's start creating the project below.

1. Create a project

· Create a new Java project: Hibernatebegin_1, and note that "Creating a separate source folder and output folder" is selected. Click "Next", Switch to "library", click "Add Library", the following figure:






· Select the user library






· Tick the previously set Hibernate user library.






2. Establishment of a sustainable class

· The following starts by creating a new class:User ; Package name:javamxj.hibernate ;

Then add three variables (italic) with the following code:



/*
* Develop a simple hibernate example using the conventional method
* Date Created 2005-3-31
* @author JAVAMXJ (share Java Fun)
* @link blog:htpp://javamxj.mblogger.cn
* htpp://blog.csdn.net/javamxj/
*/



Package javamxj.hibernate;



public class User {
private int id;
Private String username;
private String password;



}



· Click "Source (S)" On the toolbar to select "Generate Getter and Setter" (right-click, also available in pop-up menu), as shown in figure:






When you click OK, generate the following code:



/*
* Develop a simple hibernate example using the conventional method
* Date Created 2005-3-31
* @author JAVAMXJ (share Java Fun)
* @link blog:htpp://javamxj.mblogger.cn
* htpp://blog.csdn.net/javamxj/
*/



Package javamxj.hibernate;



public class User {
private int id;
Private String username;
private String password;



public int getId () {
return ID;
}
public void setId (int id) {
This.id = ID;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
This.password = password;
}
Public String GetUserName () {
return username;
}
public void Setusername (String username) {
This.username = Username;
}
}



OK, this class is done. It is an ordinary Java object (Plain old Java Objects, which is pojos, sometimes called Plain ordinary Java Objects), which represents a collection of data. The following creates a HBM file that maps this class to a table on the database.



3. mapping File

Under the javamxj.hibernate package, create a new file called "User.hbm.xml" and use Xmlbuddy to edit it (reference: Use Xmlbuddy to develop XML in Eclipse), which is easier. The contents of the document are as follows:


<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
 
<hibernate-mapping>

    <class name="javamxj.hibernate.User" table="UserTable">
        <id name="id">
            <generator class="assigned" />
        </id>
        <property name="username"  />
        <property name="password" />  
    </class>

</hibernate-mapping>


This XML file defines the relationship of object attributes to database tables. Here, the primary key is generated using the assigned method. Of course, other methods can be used to generate the primary key, and the following articles use other methods to generate the primary key. The <property> tag is used to define the properties of a Java object. The simplest way is defined here. Hibernate automatically determines the correspondence between Java object properties and database table names. Additional settings on the <property/> tag (like not null, sql-type, etc.) can be used on tools that automatically generate Java objects and database tables.

4. Configuration file
Hibernate can be configured using XML or a properties file. The default configuration file name is "hibernate.cfg.xml" (or hibernate.properties).

In the src directory, create a new hibernate.cfg.xml file with the following contents:
<?xml version='1.0' encoding='GBK'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Whether to output the SQL generated by the runtime to the log for debugging -->
        <property name="show_sql">true</property>
   
        <!-- SQL dialect, here is MySQL -->
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
   
        <!-- JDBC driver -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
   
        <!-- JDBC URL, "?useUnicode=true&characterEncoding=GBK" means encoding with GBK -->
        <property name="connection.url">
   Jdbc:mysql://localhost:3306/HibernateTest?useUnicode=true&characterEncoding=GBK
        </property>
   
        <!-- Database Username -->
        <property name="connection.username">root</property>
   
        <!-- Database password -->
        <property name="connection.password">javamxj</property>
        <!-- Specify User's mapping file -->
        <mapping resource="javamxj/hibernate/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
Note: The HibernateTest database in "jdbc:mysql://localhost:3306/HibernateTest?useUnicod..." is used here. You need to create this database in MySql.
5. Test procedure
Under the javamxj.hibernate package, create a new Test class with the following contents:
/*
 * Simply test the User class
 * Date of creation 2005-3-31
 * @author javamxj (share java happy)
 */
Package javamxj.hibernate;
Import net.sf.hibernate.*;
Import net.sf.hibernate.cfg.*;
Public class Test {
 Public static void main(String[] args) {
  Try {
   SessionFactory sf = new Configuration().configure()
     .buildSessionFactory();
   Session session = sf.openSession();
   Transaction tx = session.beginTransaction();
   User user = new User();
   user.setUsername("Blog");
   user.setPassword("Share java happy");
   Session.save(user);
   Tx.commit();
   Session.close();
  } catch (HibernateException e) {
   e.printStackTrace();
  }
 }
}
Here is a brief talk about the process, first initialize Configuration, load Hibernate configuration information, then Configuration gets the SessionFactory object, and it starts a Session, which represents a session operation of the object and the table, and Transaction represents a set of session operations, We only need to directly manipulate the User object, and perform related operations on Session and Transaction. Hibernate will automatically complete the operation of the database.
6. Configuration database
You must also set up the database before running the test program.
Create a HibernateTest database in MySQL, and create a UserTable table, the SQL statement is as follows:
CREATE TABLE usertable (
ID int(6) NOT NULL auto_increment,
Username varchar(24) NOT NULL default '',
Password varchar(24) NOT NULL default '',
PRIMARY KEY (ID)
);
Here, HibernateTest corresponds to HibernateTest in the hibernate.cfg.xml configuration file, and UserTable corresponds to the UserTable in the hbm mapping file.
7. Run the program
Right-click on Test.java and click Run. You can see that the console outputs a series of information. The last output statement should be:
Hibernate: insert into UserTable (username, password, id) values (?, ?, ?)
In the next article, I will show you how to use log4j to control the output information.
At the same time, you can see in the database that the data has been added to the table.
Summary:

Hibernate principle I don't want to say more, actually I don't know much. Moreover, there are a lot of information in this area, such as the Chinese document that comes with Hibernate itself, the Hibernate Development Guide written by Xia Wei, and the introduction of Hibernate written by Liang Gege. Everything is very good, and now there are more books about Hibetnate.

The job I am doing is to make it possible for novices to get started with Hibernate as soon as possible. I don't want to entangle too much in theory, try to talk as an example. I think, instead of saying that a technology is much better than nothing, it would be better to give me an example to get started. Ok, no more nonsense.


Related Article

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.