Java Web (2) Hibernate integration using

Source: Internet
Author: User
Tags log4j

1. After you have finished with Maven, create a new dynamic Web Project in Eclipse. Select New Project Right-->configure->convert to Maven project. Creating a new Dynamic Web project directory structure in this way will also be familiar to the directory structure of Eclipse, even after conversion to MAVEN project, will still maintain the original directory structure, but added the pom.xml maven configuration file

2. To use hibernate in a project, you must add the Hibernate class library, so the next step is to hiberante the dependent class library configuration on the MAVEN configuration, as shown in the following code

<project xmlns= "http://maven.apache.org/POM/4.0.0"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/ Maven-4.0.0.xsd "><modelVersion>4.0.0</modelVersion><groupId>tian</groupId>< artifactid>tian</artifactid><version>1.0-snapshot</version><packaging>war</ Packaging><name>tian system</name><dependencies><dependency><groupid> Org.hibernate</groupid><artifactid>hibernate-core</artifactid><version>4.3.11.final </version></dependency><dependency><groupId>org.hibernate</groupId>< Artifactid>hibernate-c3p0</artifactid><version>4.3.11.final</version></dependency> <dependency><groupid>org.apache.struts</groupid><artifactid>struts2-spring-plugin</ Artifactid><version>2.3.8</version>&lT;/dependency><dependency><groupid>junit</groupid><artifactid>junit</artifactid ><version>4.9</version><scope>test</scope></dependency><dependency>< Groupid>log4j</groupid><artifactid>log4j</artifactid><version>1.2.14</version ></dependency><dependency><groupId>Mysql</groupId><artifactId> Mysql-connector-java</artifactid><version>5.1.30</version></dependency><dependency ><groupId>javax.transaction</groupId><artifactId>javax.transaction-api</artifactId> <version>1.2</version></dependency></dependencies><build><sourceDirectory> Src</sourcedirectory><resources><resource><directory>src</directory><excludes ><exclude>**/*.java</exclude></excludes></resource></resources><plugins ><plugin><artifactid>maven-war-plugin</artifactid><version>2.3</version><configuration>< warsourcedirectory>webcontent</warsourcedirectory><failonmissingwebxml>false</ Failonmissingwebxml></configuration></plugin><plugin><artifactid> Maven-compiler-plugin</artifactid><version>3.1</version><configuration><source> 1.7</source><target>1.7</target></configuration></plugin></plugins></ Build></project>

Because MySQL is used, it also configures the JDBC driver for MySQL, as well as the JUnit test framework. One of the hibernate-c3p0 is a third-party connection pool. After saving, MAVEN will be from the Central class library download down so the need for the class library file, when the need to open the source, it will automatically load the corresponding source and Doc. Of course, this is the effect of the Eclipse integration Maven plug-in automation tool.

3. After the class library is available, you need to write a copy of the Hibernate.cfg.xml configuration XML file. To use Hiberanate to know how to access your database, and what metadata mappings are available. Here is a copy of the template

<?xml version= ' 1.0 '? ><! doctype hibernate-configuration public         "-//Hibernate/ hibernate configuration dtd 3.0//en "        "/http Www.hibernate.org/dtd/hibernate-configuration-3.0.dtd ">

4. Classes that write metadata

In the XML configuration above, two metadata is mapped, where the attribute class is a description of the mapping of the class by annotations to map properties

If it is an XML mapping file, use the Resouce property to indicate the file path of the XML, for example, if it is placed under the same package, it should be

<mapping resouce= "Cn/tian/vo/mission"/>

These are the details of the problem, down is the user code

package cn.tian.vo;import javax.persistence.*; @Entity @table (name= "Tian_user") public class  user {/** *  uses a business-independent surrogate primary key, which is automatically generated by the hiberante   */@Id  //is identified as the primary key @generatedvalue@column ( Name= "id") private long id;/** * {@code  string } name  */@Column (name= "name", NULLABLE=FALSE,LENGTH=20)  //The column information for the configuration table, name is the specified column name, nullable is the allowed null value, length specifies the field length private string name;/**  * {@code  string&nbsp, password  */@Column (name= "pwd", length=40) private string pwd;/**  * {@code  string  current position  */@Column (name= "job", nullable=false,length=20) private  string job;/** * {@code  string } sex  */@Column (name= "Sex", nullable=false,length=4) private string sex;/** * {@code  string&nbsp, phone  */@Column (name= "Phone", length=11 ) private string phone;/** * {@code  string&nbsp, the date of birth  */@Column (name= "Brithday", LENGTH=8) private  string brithday;/** * {@code  string } represents the Structure category  */@Column (name= "Struct_type", nullable=false,length=40) private string struct_type;/** * {@code  cn.tian.vo.mission &NBSP; The delegation  */@ManyToOne (Targetentity=mission.class)   //here is the relationship   many-to-one in establishing a data relationship model, That is, the attribute is associated with a foreign key to the Tian_mission table in @joincolumn (name= "mission_id", [email protected] (name= "fk_user_mission"))  // FOREGINKEY Specifies the foreign key name, and the foreign key field name private mission mission;/*    getter/setter     ***********/}

and Misssion Code

Package Cn.tian.vo;import javax.persistence.*, @Entity @table (name= "tian_mission") public class Mission {@Id @ Generatedvalue@column (name= "mission_id") Private Long id;/** * {@code String} delegation name */@Column (name= "Mission_name", Length=40,nullable=false) Private String name;/** * {@code string} Note */@Column (name= "remark", length=40) private string remark;/* Getter/setter ***********/}

5. Write hibernate test class to test if hibernate can be successfully loaded

IMPORT&NBSP;JAVA.UTIL.*;IMPORT&NBSP;JPA. DEPARTMENT;IMPORT&NBSP;JPA. Employee;import org.hibernate.hibernateexception; import org.hibernate.session; import  org.hibernate.Transaction;import org.hibernate.SessionFactory;import  org.hibernate.boot.registry.standardserviceregistry;import  Org.hibernate.boot.registry.standardserviceregistrybuilder;import org.hibernate.cfg.configuration;public  class TestMain {   private static SessionFactory factory;     public static void main (String[] args)  {       try{         configuration cfg  =  new configuration (). Configure ();          Standardserviceregistry registry = new standardserviceregistrybuilder (). ApplySettings ( Cfg.getproperties ()). build ();   &nbsP;      factory = cfg.buildsessionfactory (registry);       }catch  (Throwable ex)  {           system.err.println ("Failed to create sessionfactory object.") &NBSP;+&NBSP;EX);         throw new  Exceptionininitializererror (ex);        }   }  }

How to do it without exception throws is a good way to run it successfully.

6. If you want to customize the output mode of the logging, you can place a log4j.properties under Classpath, how to configure, you can refer to Apache log4j 1.2

Java Web (2) Hibernate integration using

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.