Java learning: getting started with hibernate

Source: Internet
Author: User

Compared with Microsoft's LINQ-to-SQL or EF framework, "Hibernate is not easy for eclipse Integrated Development". The following are the steps for beginners:

I. preparations:

1,First download eclipse (Official Website http://eclipse.org/) Note: such as the Local has installed eclipse, can skip

2,Download the latest version of hibernate (has reached version 4. x) (Official Website http://hibernate.org /)

3,Download the corresponding JDBC driver package based on your database usage (this article uses Oracle, which can be found after the Oracle client is installed on the local machine)

4,Download the commons-logging.jar package (hibernate internal logging with it) (Official Website http://commons.apache.org/logging)

5,Create a test table tmp_emp in the database (although hibernate recommends designing the domainmodel first> and then persists to the database, in actual development, the table structure is usually first available before writing.CodeSo most people are used to it)

-- Create a table first -- create tablecreate table tmp_emp (ID number (10) Not null, name varchar2 (50), birthday date, sex char (1), salary number (8, 2 )); -- add comments to the columns comment on column tmp_emp.id is 'Primary key id'; Comment on column tmp_emp.name is 'name'; Comment on column tmp_emp.birthday is 'date '; comment on column tmp_emp.sex is 'gender (f female, M male) '; Comment on column tmp_emp.salary is 'wage'; -- create/recreate primary, unique and foreign key constraints alter table tmp_emp add constraint pk_tmp_emp_id primary key (ID); -- create sequence sq_tmp_empminvalue 1 maxvalue 9999999999999999999999999 start with 201 increment by 1 cache 200;

6,Install the hibernate tools plug-in (in theory, this step is not required, but without this plug-in, you can only manually write a variety of hibernate configuration XML)

After eclipse is enabled, if file-> New can find the options related to hibernate, it means that your machine has installed hibernate tools. skip this step.

Otherwise, help-> eclipse marketplace

Enter hibernate in the "find" column to find the relevant link on the Internet:

2. Create a regular Java project named hellohibernate

During the creation process, pay attention to import the required jar packages, these jar packages can be divided into three categories: hibernate extract directory Lib \ required jar package, JDBC database driver package, common-logging.jar log Toolkit

3. Create a hibernate configuration file (hibernate. cfg. XML)

If no other DB connections have been configured before, click get values from connection to create a connection.

Set related parameters. If no problem occurs, click test connection to test whether the parameters are normal.

Save the connection named myconn and click "Get values from connection". In the displayed dialog box, you can see the connection myconn.

In fact, this series of operations is nothing more than to let ide help us generate the following XML:

 
   
   
   
    
    
      oracle. JDBC. oracledriver 
     
    
      password 
     
    
      JDBC: oracle: thin: @ // server IP Address: 1521/orcltest 
     
    
      User Name 
     
    
      default schema 
     
    
      Org. hibernate. dialect. oracle10gdialect 
     
    
   

It records some key information about database connection, so you can know how to connect to the database and how to generate SQL statements during hibernate runtime.

After completing this step, you can verify whether the DB connection is normal on the hibernate deployments panel. For details, refer to window-> show view-> Other.

 

Input Hiber to automatically filter out the desired records.

In eclipse, you can find this panel and expand the database. If everything goes well, the corresponding table name should be automatically listed.

4. Create a reverse engineering configuration file (hibernate. reveng. XML) and automatically generate an object class based on the table structure.

In ORM: A table usually corresponds to a class. If all classes need to be written manually, it will be exhausting, fortunately, Hibernate tools provides the "reverse object class Generation Based on DB table structure" function.

See create a hibernate reverse engineering File

For reference, Click Refresh to first list all the columns. For demonstration, we only include the test table tmp_emp (that is, only this table is processed)

After that, you can see many other options. Click "tables & columns"

Add tmp_emp

Similarly, these graphical operations are actually to generate an XML

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype hibernate-reverse-engineering public "-// hibernate/hibernate reverse engineering DTD 3.0/EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">  

The XML content is equivalent to the metadata of the DB table structure. With this XML content, Hibernate can understand how each table (and each field in the table) generates classes (and class members) in Java)

The following describes how to run these configurations. For details, see: (this is very difficult. It seems that you cannot find the configuration in the menu. You can only click it in the toolbar and hide a drop-down menu)

At this time, the hibernate code generation and configuration interface will pop up. The most important thing is: the output directory generated by the code, and select the reveng just created. XML (without this option, Hibernate does not know which tables to generate and the rules to generate)

In the exporters panel, we usually only need to generate domain code (that is, object class ),

Sometimes, after a Java class is generated, eclipse does not automatically refresh the file structure. We recommend that you check the following

Finally, click run to see the newly generated Java class.

5. Generate the hibernate ing configuration file

The reverse engineering configuration file just created does not play much role during runtime. It is only used to tell higoal how to generate a Java entity Class Based on the table structure, for existing Java classes (such as hand-written ones), how does hibernate know which table corresponds to the database during runtime? The answer is the configuration file. For more information, see create a hibernate XML Mapping File (HBM file)

Select the package (or a specific class) corresponding to the object class)

All the way to next, until the completion, we get the file: tmpemp. HBM. xml

<? XML version = "1.0"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <! -- Generated dec 26,201 2 1:44:52 by hibernate tools 3.4.0.cr1 --> 

This record the ing between each Java class and table. The last step is to configure related operations:

After an HBM file is generated, how does hibernate know to read it? We have to give some tips to hibernate. Double-click the hibernate. cfg. xml file and find the mappings node, such:

Click Add to add the created tmpemp. HBM. xml.

After saving, you will find that, in fact, it is nothing more than adding a line automatically in hibernate. cfg. xml:

 
<Mapping Resource = "domain/tmpemp. HBM. xml"/>

Finally, let's take a look: Create a class with the main method

Package app; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. cfg. configuration; import domain. tmpemp; import Java. util. list; public class Hello {/*** @ Param ARGs */public static void main (string [] ARGs) {session Ss = getsession (); List result = ss. createquery ("from tmpemp "). list (); For (tmpemp T: (list <tmpemp>) result) {system. out. println ("ID:" + T. GETID () + ", name:" + T. getname ();} ss. close ();} static sessionfactory; static session getsession () {If (sessionfactory = NULL) {sessionfactory = new configuration (). configure (). buildsessionfactory ();} return sessionfactory. opensession ();}}

Only the simplest query is demonstrated here. If the query succeeds, the console panel should have the result (for example)

 

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.