用Maven创建Hibernate项目

来源:互联网 发布:j20弹仓 知乎 编辑:程序博客网 时间:2024/05/29 13:10

本文将用Maven3、Hibernate3.6、Oracle10g整合,作为例子。

环境清单:

1.Maven3.0.5

2.Hibernate3.6.5 Final

3.JDK1.7.0.11

4.Oracle10g

一.首先创建表BDUSER

create table DBUSER(  user_id      NUMBER(5) not null,  username     VARCHAR2(20),  created_by   VARCHAR2(20),  created_date DATE)

二.用Maven3创建一个web项目,项目名称:maven-hibernate-demo

创建项目参考:Maven3路程(三)用Maven创建第一个web项目(1)

三.添加Hibernate和Oracle依赖,pom.xml如下

Hibernate有些依赖包必须添加

 

<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/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.lei.demo</groupId>  <artifactId>maven-hibernate-demo</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>maven-hibernate-demo Maven Webapp</name>  <url>http://maven.apache.org</url>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.8.2</version>      <scope>test</scope>    </dependency>    <!-- Oracle Jdbc Driver -->    <dependency>        <groupId>com.oracle</groupId>        <artifactId>ojdbc14</artifactId>        <version>10.2.0.4.0</version>    </dependency>    <!-- Hibernate 配置 -->    <dependency>        <groupId>org.hibernate</groupId>        <artifactId>hibernate-core</artifactId>        <version>3.6.5.Final</version>    </dependency>    <dependency>        <groupId>javassist</groupId>        <artifactId>javassist</artifactId>        <version>3.12.0.GA</version>    </dependency>    <dependency>        <groupId>antlr</groupId>        <artifactId>antlr</artifactId>        <version>2.7.6</version>    </dependency>    <dependency>        <groupId>commons-collections</groupId>        <artifactId>commons-collections</artifactId>        <version>3.1</version>    </dependency>    <dependency>        <groupId>dom4j</groupId>        <artifactId>dom4j</artifactId>        <version>1.6.1</version>    </dependency>    <dependency>        <groupId>javax.transaction</groupId>        <artifactId>jta</artifactId>        <version>1.1</version>    </dependency>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.6.1</version>    </dependency>    <dependency>        <groupId>org.hibernate.javax.persistence</groupId>        <artifactId>hibernate-jpa-2.0-api</artifactId>        <version>1.0.0.Final</version>    </dependency>  </dependencies>  <build>    <finalName>maven-hibernate-demo</finalName>  </build></project>

四.创建Hibernate Map文件和Model类

1.创建Dbuser.hbm.xml映射文件

路径src/main/resources/com/sulei/demo下

<?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 2013-10-22 15:28:34 by Hibernate Tools 3.4.0.CR1 --><hibernate-mapping>    <class name="com.sulei.demo.Dbuser" table="DBUSER" schema="GZIP_BASE">        <id name="userId" type="int">            <column name="USER_ID" precision="5" scale="0" />            <generator class="assigned" />        </id>        <property name="username" type="string">            <column name="USERNAME" length="20" />        </property>        <property name="createdBy" type="string">            <column name="CREATED_BY" length="20" />        </property>        <property name="createdDate" type="date">            <column name="CREATED_DATE" length="7" />        </property>    </class></hibernate-mapping>

2. 创建实体类Dbuser

路径src/main/java/com/sulei/demo下

package com.sulei.demo;// Generated 2013-10-22 15:28:34 by Hibernate Tools 3.4.0.CR1import java.util.Date;/** * Dbuser generated by hbm2java */public class Dbuser implements java.io.Serializable {    private int userId;    private String username;    private String createdBy;    private Date createdDate;    public Dbuser() {    }    public Dbuser(int userId) {        this.userId = userId;    }    public Dbuser(int userId, String username, String createdBy,            Date createdDate) {        this.userId = userId;        this.username = username;        this.createdBy = createdBy;        this.createdDate = createdDate;    }    public int getUserId() {        return this.userId;    }    public void setUserId(int userId) {        this.userId = userId;    }    public String getUsername() {        return this.username;    }    public void setUsername(String username) {        this.username = username;    }    public String getCreatedBy() {        return this.createdBy;    }    public void setCreatedBy(String createdBy) {        this.createdBy = createdBy;    }    public Date getCreatedDate() {        return this.createdDate;    }    public void setCreatedDate(Date createdDate) {        this.createdDate = createdDate;    }}


 

按 Ctrl+C 复制代码

可以用Hibernate Tools反向工程自动声场代码,见以下另一篇文章:

用Hibernate Tools生成Hibernate Mapping映射文件

五.创建Hibernate.cfg.xml

创建Hibernate配置文件 “hibernate.cfg.xml” 把他放在resources目录下: “src/main/resources/hibernate.cfg.xml“填写数据库相关信息。

加入Map文件,“DBUser.hbm.xml“.

hibernate.cfg.xml如下:

<?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"><hibernate-configuration> <session-factory name="">  <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>  <property name="hibernate.connection.password">password</property>  <property name="hibernate.connection.url">jdbc:oracle:thin:@databaseip:1521:gzip</property>  <property name="hibernate.connection.username">gzip_base</property>  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>  <property name="show_sql">true</property>  <mapping resource="com/sulei/demo/Dbuser.hbm.xml" /> </session-factory></hibernate-configuration>


六.创建Session工场

创建 “HibernateUtil.java” 类管理Hibernate Session。 路径:“src/main/java/com/sulei/util/HibernateUtil.java”

package com.sulei.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {        private static final SessionFactory sessionFactory = buildSessionFactory();         private static SessionFactory buildSessionFactory() {        try {            // Create the SessionFactory from hibernate.cfg.xml            return new Configuration().configure().buildSessionFactory();        } catch (Throwable ex) {            // Make sure you log the exception, as it might be swallowed            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }    }     public static SessionFactory getSessionFactory() {     System.out.println("test----1");        return sessionFactory;    }     public static void shutdown() {        // Close caches and connection pools        getSessionFactory().close();    }}


 

六. 代码测试

创建App.java向表中插入一条记录。

package com.sulei.test;import java.util.Date;import org.hibernate.Session;import com.sulei.util.HibernateUtil;import com.sulei.demo.Dbuser;public class App {    public static void main(String[] args) {        System.out.println("Maven3 + Hibernate + Oracle10g");        Session session = HibernateUtil.getSessionFactory().openSession();         session.beginTransaction();        Dbuser user = new Dbuser();         user.setUserId(100);        user.setUsername("leioolei");        user.setCreatedBy("system");        user.setCreatedDate(new Date());         session.save(user);        session.getTransaction().commit();    }}


 

项目组织好,目录结构见下图

在App.java上右键运行,结果如图

测试成功!!!

转载地址:http://www.cnblogs.com/leiOOlei/p/3376155.html

0 0
原创粉丝点击