Hibernate annotations automatically generate data tables

Source: Internet
Author: User
Tags sessions

As a rule, general system development is designed from a database. But from the angle of object-oriented development, the design of the system should be based on the object model, mainly consider the design and logic of object, then build the database structure according to the object model, and make use of Hibernate Schemaexport object to realize this conveniently. In addition, the use of annotations also eliminates a lot of complex configuration work, the following hibernate annotations automatically generate a datasheet process to do a detailed description.

One, the environment carries

Download the latest Hibernate-release-4.0.0.cr7.zip, import required package, this example is based on MySQL database, so also need Mysql-connector-java-5.1.5.jar

Second, the configuration

The hibernate configuration file can use XML or properties, and the XML used here:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http:// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">  

About Current_session_context_class Configuration items:

Through the hibernate operation of the database, mainly through session implementation, the session can be simply as a link to the database, there is its life cycle. Get session There are two methods in the Sessionfactory, Getcurrentsession () and Opensession (), which each create a new sessions each time, their differences:

1. The session created by Getcurrentsession is bound to the current thread, and Opensession does not.

The thread created by the

        2, Getcurrentsession automatically shuts down after a transaction rollback or when something is committed, and opensession must close manually

        Therefore, it is often convenient to use getcurrentsession (), but you need to configure Current_session_ in a configuration file Context_class, you can have two values JTA or thread.

        References: Most applications that use hibernate require some form of "context-related" session. A specific session is always valid throughout a particular context. However, it is often difficult for different types of applications to make the next definition of "context"; different contexts define different scopes for the concept of "current". Prior to version 3.0, a program using hibernate either uses a Threadlocal context session that is written on its own, or a secondary class such as Hibernateutil or a third-party framework (such as spring or Pico). They provide context-sensitive sessions based on proxy (proxy) or interceptor (interception).         

Starting with version 3.0.1, Hibernate added the Sessionfactory.getcurrentsession () method. Initially, it assumed that the JTA transaction was used, and the JTA transaction defined the scope and context of the current session. The Hibernate development team believes that because there are several independent JTA TransactionManager that are stable and usable, most (if not all) applications should be JTA transaction management, whether or not deployed to a Java EE container. Based on this, the context-related session with JTA can satisfy all your needs.

Better yet, starting at 3.1, the background implementation of sessionfactory.getcurrentsession () is pluggable. Therefore, we introduced a new extension interface (Org.hibernate.context.CurrentSessionContext) and a new configuration parameter (Hibernate.current_session_context_class), To plug the definition of what is the scope and context of the current session (scope and contexts).

See Javadoc for the Org.hibernate.context.CurrentSessionContext interface, where there is a detailed discussion of its contract. It defines a single method, Currentsession (), which is used by a specific implementation to track the current context session. Hibernate has two implementations of this interface built into it.

Org.hibernate.context.JTASessionContext-The current session is tracked and defined according to the JTA. This is exactly the same as the previous method of supporting only JTA. For more information, see Javadoc.                                    Org.hibernate.context.ThreadLocalSessionContext-The current session is tracked and defined through the currently executing threads. For more information, see Javadoc.       

Both implementations provide a programming model that corresponds to a session per database transaction, also known as a session per request. The start and end of the Hibernate session is controlled by the survival of the database transaction. If you are using your own code to manage transactions (for example, in pure j2se, or JTA/USERTRANSACTION/BMT), it is recommended that you use the Hibernate Transaction API to hide the underlying transaction implementation from your code. If you execute in the EJB container that supports CMT, the transaction boundary is declared, and you do not need to perform any transaction or session management operations in your code.        See chapter 11th Transactions and concurrency to read more content and sample code. The Hibernate.current_session_context_class configuration parameter defines which Org.hibernate.context.CurrentSessionContext implementation should be used. Note that for backward compatibility, if this parameter is not configured, But there is a org.hibernate.transaction.TransactionManagerLookup configuration, hibernate will use Org.hibernate.context.JTASessionContext. In general, the value of this parameter indicates the full name of the implementation class to use, but the two built-in implementations can use shorthand, i.e. "JTA" and "thread".

When the sessionfactory is started, Hibernate creates the corresponding Currentsessioncontext according to the configuration, and when Getcurrentsession () is invoked, the method that is actually executed is Currentsessioncontext.currentsession (). When Currentsession () executes, currentsession invokes the Sessionfactory opensession if the current session is empty. So Getcurrentsession () is a better way to get a session for Java EE.

Iii. Writing Persistent Objects

Package Cn.com.model;

Import java.io.Serializable;

Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.GenerationType;
Import Javax.persistence.Id;
Import javax.persistence.Table;

@Entity
@Table (name= "T_user") public
class user implements serializable{
	/**
	 * * *
	Private static final long serialversionuid = 1L;

	private long ID;

	private String name;
	
	@Id
	@GeneratedValue (strategy=generationtype.identity) public
	long GetId () {return
		Id;
	}

	public void SetId (long id) {
		this.id = ID;
	}

	@Column (name= "name", length=50) public
	String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}
	
}
After all the objects have been written, they need to be configured in the configuration file: <mapping class= "Cn.com.model.User"/>

Four, test

Configuration Configuration = new Annotationconfiguration ();
Configuration.configure ();
Schemaexport export = new Schemaexport (configuration);
Export.execute (True, True, false, true);
Sessionfactory factory = Configuration.buildsessionfactory ();
Session session = Factory.opensession ();
Session session = Factory.getcurrentsession ();
Session.begintransaction ();
User user = new user ();
User.setname ("Chengdu");
Session.save (user);
Session.gettransaction (). commit ();
Session.close ();

About the Schemaexport object there are several ways to build the database structure.

1, create (Boolean Script,boolean export)

Script: Whether the DDL statement is printed in the console, when export is true, the drop is executed first and the data table is created based on the persisted object, which may result in the loss of the database, or FALSE, the data table should be created before the table can be found, does not cause data loss.

2, Drop (Boolean Script,boolean export)

Script: If the DDL statement is printed on the console, when export is true, a drop operation is performed, False when

3, execute (Boolean script, Boolean Export,boolean Justdrop, Boolean justcreate)

When export is true, Justdrop is false,justcreate to true, and if the corresponding datasheet does not exist, create is done, and the Create is not performed if it exists

When export is true, Justdrop is true,justcreate to false, the drop operation is performed

Therefore, to create a new datasheet, it is best to use Create (true,true);

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.