Eclipse quickly hibernate--1. Getting Started example

Source: Internet
Author: User
Tags add date sql mysql net string version variable
    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.      A, download, install and configure  1. Required software Ant 1.6.2        http://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 ide http://www.jboss.org/products/jbosside   Look at the instructions, You need to pick the version that corresponds to the eclipse you are using, where you choose 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 wants to download the Hibernate Extensions 2.1.3, which contains some tool classes.      Downloads             http:// prdownloads.sourceforge.net/hibernate/hibernate-extensions-2.1.3.zip?download     mysql 4.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 file    2. Installation and configuration        Here it is highlighted that you need to set ant_home in the environment variable and point it to the ANT installation directory and add "%ant_home%\bin" to the path variable value. Java environment variable settings.    xmlbuddy  and Jboss-ide I have been installed by links,     reference    http://blog.csdn.net/javamxj/archive/ 2004/10/11/132311.aspx      Create a library folder:    under D disk, create a new Java directory, and create a new hibernate subdirectory under this directory. Under this subdirectory, create a new Lib 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: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.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:\ Java\hibernate\lib Directory · Extract Xdoclet-bin-1.2.2.zip, Xdoclet-1.2.2.jar, Xdoclet-hibernate-module-1.2.2.jar, Xjavadoc-1.1.jar, 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 User Library • Window-> preferences->java-> build path-> user Library, · Then click Add Jar so that 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 Update xdoclet-hibernate-module copy Xdoclet-hibernate-module-1.2.2.jar from XDoclet1.2.2 to Jbosside-1.4.1-e30 In the \eclipse\plugins\org.jboss.ide.eclipse.xdoclet.core_1.4.1 directory, and delete the Xdoclet-hibernate-module-1.2.1.jar file in its directory, and then in the Eclipse Interface, window-> preferences->jboss-ide->xdoclet->code Assist: Click the "Refresh XDoclet Data" column on the right to complete the update.    If you want to replace another module, the steps are similar.     Ii. 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 manually set the manual, this side of the full manual reason, is that you can know the basic flow of hibernate.    This is the structure of the entire project: OK, let's start with creating the project. 1. Create 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 "User Library" ·  Tick the previously set Hibernate user library. 2. Establishment of a sustainable category · 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 instance using the normal method * Creation Date 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 and select "Generate Getter and Setter" (right click, also available in pop-up menu), as shown: Click "OK" to generate the following code:
* * Develop a simple hibernate instance using the normal method * Creation Date 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 files under the Javamxj.hibernate package, create a new file called "User.hbm.xml" and edit it using Xmlbuddy (reference: Using 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 ">This XML file defines the relationship between object attributes mapped to database tables, where assigned (program settings) are used to generate primary keys.    Of course, there are other ways to generate the primary key, followed by the article in other ways to generate the primary key. <property> tags are used to define the properties of Java objects, and only the simplest way is defined by hibernate, which automatically determines the relationship between Java object Properties and database table names.  Additional settings on the <property/> label (such as NOT NULL, SQL-TYPE, etc.) can be used to automatically generate Java objects and database tables on the tool.   4. The configuration file hibernate can be configured using either an XML or a property file, and the profile name defaults to "Hibernate.cfg.xml" (or hibernate.properties). In the SRC directory, create a new Hibernate.cfg.xml file that reads as follows:
<?xml version= ' 1.0 ' encoding= ' GBK '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration dtd//en" "http:// Hibernate.sourceforge.net/hibernate-configuration-2.0.dtd ">Note: The Hibernatetest database in "Jdbc:mysql://localhost:3306/hibernatetest?useunicod ..." is used here, and you need to build this database in MySQL. 5. Test program under the Javamxj.hibernate package, create a new test class, the contents are as follows:
* * Simple Test User class * creation date 2005-3-31 * @author javamxj (share Java Fun) */package Javamxj.hibernate;import Net.sf.hibernate.*;impor T net.sf.hibernate.cfg.*;p Ublic class Test {public static void main (string[] args) {try {sessionfactory SF = new Configura tion (). Configure (). Buildsessionfactory (); Session session = Sf.opensession (); Transaction tx = Session.begintransaction (); User user = new user (); User.setusername ("Blog"); User.setpassword ("Share Java Happiness"); Session.save (user); Tx.commit (); Session.close ();} catch (Hibernateexception e) {e.printstacktrace ();}}}
     here simply talk about the process, first initialize configuration, load hibernate configuration information, and then configuration Get Sessionfactory object, And by it to open a session, which represents the object and the table of a conversation operation, and transaction represents a set of session operations, we need to directly manipulate the user object, and the session and transaction related operations, Hibernate will automatically complete the operation of the database.   6. Metabase     before you run the test program, you must set up the database first.    Create a hibernatetest database in MySQL and create a usertable table with SQL statements as follows:  create table usertable (  ID int (6) Not NULL auto_increment,  username varchar () NOT NULL default ',   password varchar (in) NOT null default ', &NBSP ; PRIMARY key  (ID))  create TABLE usertable (  ID int (6) not NULL auto_increment,  username varchar (24) Not null default ',   password varchar (a) NOT null default ',  PRIMARY key  (ID));   &nbsp ;   here, the hibernatetest corresponds to the hibernatetest in the Hibernate.cfg.xml configuration file, usertable corresponds to HBM in the usertable mapping file.   7. Run the program     right click Test.java, click to run, you can see the console output a series of information, the last output statement should be: Hibernate:insert into usertable (UsernamE, password, id) VALUES (?,?,?)    in the next article will describe how to use log4j to control output information.     at the same time, in the database can be seen, data has been added to the table:   Summary:      hibernate principle I do not want to say more, Actually know also not much, moreover this aspect information many, for example hibernate own Chinese document, Xia Xin writes "The Hibernate Development Guide", the good Gregor writes "The Hibernate to get started" and so on are very nice, Now there are more books about hibetnate.      my job is to enable beginners to get started as soon as possible hibernate, theoretical aspects I do not want too much entanglement, as far as possible to speak as examples. I think it's better to give me a hands-on example than to say how much better a technology is. Well, no more nonsense.     Summary:      hibernate principle I do not want to say, actually do not know much, and this aspect of information, such as hibernate itself with the Chinese document , Xia Xin prepared "Hibernate development Guide", Liang Gregor Prepared "Hibernate introduction" are very good, now about the Hibetnate books are also more up.      my job is to enable beginners to get started as soon as possible hibernate, theoretical aspects I do not want too much entanglement, as far as possible to speak as examples. I think it's better to give me a hands-on example than to say how much better a technology is. Well, 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.