Hibernate Demo1

Hibernate Demo1

Hibernate版本3.3.2GA

maven配置

<?xml version="1.0" encoding="UTF-8"?>
<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>demo</groupId>
    <artifactId>hibernate1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <!-- we dont want the version to be part of the generated war file name -->
        <finalName>${artifactId}</finalName>
    </build>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.3.2.GA</version>
        </dependency>
        <!--&lt;!&ndash; Because this is a web app, we also have a dependency on the servlet api. &ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>javax.servlet</groupId>-->
            <!--<artifactId>servlet-api</artifactId>-->
        <!--</dependency>-->

        <!--&lt;!&ndash; Hibernate uses slf4j for logging, for our purposes here use the simple backend &ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>org.slf4j</groupId>-->
            <!--<artifactId>slf4j-simple</artifactId>-->
        <!--</dependency>-->

        <!-- https://mvnrepository.com/artifact/javassist/javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb-j5</artifactId>
            <version>2.2.4</version>
        </dependency>

    </dependencies>
</project>

编写User bean

package demo.hibernate;

import java.util.Date;

public class User {
    private String id;
    private String name;
    private String email;
    private Date hiredate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }
}

编写User.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">
<hibernate-mapping package="demo.hibernate">

    <class name="User" table="USER">
        <id name="id" column="ID">
            <generator class="native"/>
        </id>
        <property name="name" type="string" column="name"/>
        <property name="email" type="string" column="email"/>
        <property name="hiredate" type="timestamp" column="hiredate"/>
    </class>

</hibernate-mapping>

编写 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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="User.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

编译程序

mvn compile

编写HibernateUtil.java

package demo.hibernate;

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() {
        return sessionFactory;
    }
}

编写UserManager.java

package demo.hibernate;

import org.hibernate.Session;

import java.util.Date;

public class UserManager {

        public static void main(String[] args) {
            UserManager mgr = new UserManager();

            mgr.createAndStoreUser("My User", new Date());

            HibernateUtil.getSessionFactory().close();
        }

        private void createAndStoreUser(String title, Date theDate) {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            User theUser = new User();
            theUser.setName(title);
            theUser.setHiredate(theDate);
            session.save(theUser);

            session.getTransaction().commit();
        }

    }
CREATE TABLE user (
   user_id INT NOT NULL IDENTITY,
   name VARCHAR(50) NOT NULL,
   email VARCHAR(20) NOT NULL,
   hiredata DATE,
   primary key(user_id)
);

运行

mvn exec:java -Dexec.mainClass="demo.hibernate.UserManager" -Dexec.args="store"

遇到错误整理

  • Unable to instantiate default tuplizer

    需要安装javassist包

  • HSQLDB server version is ‘2.4.1’ client version ‘2.1.0.0’ is not compatible.
    org.hibernate.exception.JDBCConnectionException: Cannot open connection

需要使用hsqldb中自带的jdbcdriver包

  • integrity constraint violation: NOT NULL check constraint; SYS_CT_10224 table: USER column: USER_ID

需要修改native为increament

<id name="id" column="user_id">
    <generator class="increment"/>
</id>        

或者修改建表,添加identity字段

   user_id INT NOT NULL IDENTITY,

hibernate generator的备选字段

increment
用于为long, short或者int类型生成 唯一标识。只有在没有其他进程往同一张表中插入数据时才能使用。 在集群下不要使用。

identity
对DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL的内置标识字段提供支持。 返回的标识符是long, short 或者int类型的。

sequence
在DB2,PostgreSQL, Oracle, SAP DB, McKoi中使用序列(sequence), 而在Interbase中使用生成器(generator)。返回的标识符是long, short或者 int类型的。

hilo
使用一个高/低位算法高效的生成long, short 或者 int类型的标识符。给定一个表和字段(默认分别是 hibernate_unique_key 和next_hi)作为高位值的来源。 高/低位算法生成的标识符只在一个特定的数据库中是唯一的。

seqhilo
使用一个高/低位算法来高效的生成long, short 或者 int类型的标识符,给定一个数据库序列(sequence)的名字。

uuid
uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid
在MS SQL Server 和 MySQL 中使用数据库生成的GUID字符串。

native
selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned
lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select
retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign
uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值