HibernateTools implements mutual conversion of schma ing in pojo Databases

Source: Internet
Author: User
Tags log log

Core

Using HibernateTools, from the POJO class, Mapping file, there is one of the database tables, you can generate the other two.


Overview

When using Hibernate to develop the persistent layer of the system, follow the general development process


1. Analyze the business

2. Obtain the system entity class

3. Write the Hibernate ing file of Hibernate.

4. Generate a database table based on the ing File


The above steps are the beginning of Hibernate development. Depending on the Development habits, some project teams may write POJO classes first, some projects may design databases first, and some project teams may write ing files first to complete one of them, the class structure or table structure can be determined.

Now that the structure can be determined, you can use tools instead of manual work.

Prerequisites

Install the Eclipse plug-in HibernateTools. There are many tutorials for installing the eclipse plug-in Baidu. We recommend that you use copy or link to install the plug-in. Then, the version of HibernateTools corresponds to a specific Eclipse version, therefore, check your eclipse version before installation.

Then, create a Project. In this article, create a Dynamic Web Project, use the mysql database, create a Project, introduce the mysql driver jar, and introduce the Hibernate (4.3.5 is used in this article) package, all the jar files in the required folder under lib

After installing the plug-in, use the tool to generate the Hibernate configuration file. Right-click the project --> new. After the hibernatgatels is installed, there are four more types of files. Select the first one:


Enter required attributes based on the database used:


Generate the hibernate. cfg. xml code:

 
     
          
   
    false
           
   
    com.mysql.jdbc.Driver
           
   
    123456
           
   
    jdbc:mysql://localhost:3306/test
           
   
    root
           
   
    org.hibernate.dialect.MySQLDialect
           
   
    false
                      
  
 

Mutual Conversion

Next, you can start with the question. This article starts from each of the three items and generates the other two items.

Idea 1: A mapping File and DDL are generated by the POJO class.

The POJO class code is very convenient to write. Therefore, I first introduce this method, and I personally think this method is the most efficient. First, create two POJO classes.

package org.hibernate.test;public class Student implements java.io.Serializable {private int id;private String name;public Student() {}public Student(int id) {this.id = id;}public Student(int id, String name) {this.id = id;this.name = name;}public int getId() {return this.id;}public void setId(int id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}}

package org.hibernate.test;import java.util.ArrayList;import java.util.List;public class Class implements java.io.Serializable {private int id;private String name;private List students = new ArrayList(0);public Class() {}public Class(int id) {this.id = id;}public Class(int id, String name, List students) {this.id = id;this.name = name;this.students = students;}public int getId() {return this.id;}public void setId(int id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public List getStudents() {return this.students;}public void setStudents(List students) {this.students = students;}}

The next step is to generate the other two items. Right-click the project --> new, select the fourth item under Hibernate, create the mapping file, and generate the Mapping File Based on the existing POJO class.


Add two existing POJO classes


Next, you can view the generated hbm. xml file in advance, and make slight modifications to the file that can be generated with special requirements.

Code Generation:

 
 
     
          
               
                
            
           
               
            
       
  
 

 
 
     
          
               
                
            
           
               
            
           
               
                    
                 
                
                    
                 
                
            
       
  
 

The mapping File is generated, and the ddl is generated. Right-click the project --> new, and select Hibernate Console Configuration.



After selecting the corresponding item, finish, and then add Hibernate code Generation, Windows --> Customer Perspective to the toolbar.


Then, the toolbar has an icon similar to the running button. Click the drop-down button and select the second item. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140602/20140602090355283.png" alt = "\">


Authorization + CjxwPjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20140602/20140602090356287.png" alt = "\">

Select the second item, which is to generate the ddl we want. Of course, we also select DAO Code to generate DAO Code for the Operation questions (hibernatgatels is really considerate)


This is the generated image.

Ddl table creation statement:

create table CLASS (ID integer not null, NAME varchar(255), primary key (ID));create table STUDENT (ID integer not null, NAME varchar(255), idx integer, primary key (ID));alter table STUDENT add index FKBACA0E1BE081A5FD (ID), add constraint FKBACA0E1BE081A5FD foreign key (ID) references CLASS (ID);


The DAO code is as follows:

package org.hibernate.test;// Generated 2014-5-30 23:18:05 by Hibernate Tools 4.0.0import java.util.List;import javax.naming.InitialContext;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.LockMode;import org.hibernate.SessionFactory;import org.hibernate.criterion.Example;/** * Home object for domain model class Class. * @see org.hibernate.test.Class * @author Hibernate Tools */public class ClassHome {private static final Log log = LogFactory.getLog(ClassHome.class);private final SessionFactory sessionFactory = getSessionFactory();protected SessionFactory getSessionFactory() {try {return (SessionFactory) new InitialContext().lookup("SessionFactory");} catch (Exception e) {log.error("Could not locate SessionFactory in JNDI", e);throw new IllegalStateException("Could not locate SessionFactory in JNDI");}}public void persist(Class transientInstance) {log.debug("persisting Class instance");try {sessionFactory.getCurrentSession().persist(transientInstance);log.debug("persist successful");} catch (RuntimeException re) {log.error("persist failed", re);throw re;}}public void attachDirty(Class instance) {log.debug("attaching dirty Class instance");try {sessionFactory.getCurrentSession().saveOrUpdate(instance);log.debug("attach successful");} catch (RuntimeException re) {log.error("attach failed", re);throw re;}}public void attachClean(Class instance) {log.debug("attaching clean Class instance");try {sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);log.debug("attach successful");} catch (RuntimeException re) {log.error("attach failed", re);throw re;}}public void delete(Class persistentInstance) {log.debug("deleting Class instance");try {sessionFactory.getCurrentSession().delete(persistentInstance);log.debug("delete successful");} catch (RuntimeException re) {log.error("delete failed", re);throw re;}}public Class merge(Class detachedInstance) {log.debug("merging Class instance");try {Class result = (Class) sessionFactory.getCurrentSession().merge(detachedInstance);log.debug("merge successful");return result;} catch (RuntimeException re) {log.error("merge failed", re);throw re;}}public Class findById(int id) {log.debug("getting Class instance with id: " + id);try {Class instance = (Class) sessionFactory.getCurrentSession().get("org.hibernate.test.Class", id);if (instance == null) {log.debug("get successful, no instance found");} else {log.debug("get successful, instance found");}return instance;} catch (RuntimeException re) {log.error("get failed", re);throw re;}}public List findByExample(Class instance) {log.debug("finding Class instance by example");try {List results = sessionFactory.getCurrentSession().createCriteria("org.hibernate.test.Class").add(Example.create(instance)).list();log.debug("find by example successful, result size: "+ results.size());return results;} catch (RuntimeException re) {log.error("find by example failed", re);throw re;}}}

At this point, we have generated the hbm. xml file and DDL by using the POJO class.


Idea 2: Generate POJO classes and DDL from hbm. xml

...

Idea 3: POJO class and hbm. xml are generated by database tables (or DDL ).

...


Idea 2 3. Refer to the next blog!


Email Address: 350676076@qq.com, reprint please indicate the source!


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.