`
hustlong
  • 浏览: 121448 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

hibernate Step By Step (1)

阅读更多
Hibernate的第一个例子,用hibernate3.0  数据库用Hsql(因为运行起来简单)
描述我要达到的目的:完成一个最简单的功能:在表User中插入一条记录。

1,新建工程,添加Hibernate支持,可以用Myeclipse自带的加入Hibernate支持功能。不过这里我想自己引入包:<url>http://ikeel.iteye.com/admin/blogs/174641</url>可以参考这篇文章。
然后为了使用Hsql还要引入hsql.jar
2,有这样几个配置文件:

log4j.properties;
hibernate.cfg.xml;
xxx.hbm.xml;

分别说明:
log4j:位于src根目录下,不用多说,但是如果不加入这个配置会报警告的。并且也看不到执行过程中的日志记录。
内容:

log4j.rootLogger=WARN, Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=(%r ms) [%t] %-5p: %c#%M %x: %m%n

log4j.logger.com.genuitec.eclipse.sqlexplorer=DEBUG
log4j.logger.org.apache=WARN
log4j.logger.org.hibernate=WARN


hibernate.cfg.xml:
位于src根目录下。
<?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>

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

<property name="dialect">
org.hibernate.dialect.HSQLDialect
</property>
<property name="show_sql">true</property>
<property name="connection.pool_size">3</property>

<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>


<mapping resource="dian/ikeel/hibernate/beans/Users.hbm.xml" />

</session-factory>

</hibernate-configuration>


对这个配置文件,有几点需要说明的,就是DTD的引入,可以采用本地文件系统的,也可以采用上面所写的网络地址。
注意:<property name="current_session_context_class">thread</property>
如果缺少这一句时会报错:No CurrentSessionContext configured!

xxx.hbm.xml:
映射文件,内容如下:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
       "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >


<hibernate-mapping>

<class name="dian.ikeel.hibernate.beans.Users" table="User">
<id name="id" column="userid">
<generator class="native"></generator>
</id>
<property name="username" column="name"></property>

<property name="password" column="pwd"></property>
</class>
</hibernate-mapping>


对应的Users.java内容如下:
package dian.ikeel.hibernate.beans;


public class Users {

private long id;
private String username;
private String password;

public Users()
{}

   gets  &  sets ...
}



attention:
<class name="dian.ikeel.hibernate.beans.Users" table="User">需要指定包名。如果不指定就会报错:Could not read mappings from resource: Users.hbm.xml

2,到目前基本的配置已经完成,开始使用操作了。

package dian.ikeel.hibernate.BLL;



import org.hibernate.Session;


import dian.ikeel.hibernate.beans.*;
import dian.ikeel.hibernate.util.hibernateutil.*;
import dian.ikeel.hibernate.util.SessionFactory.*;

public class Entry {

public  static void main(String[] args)
{

Session  session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
     session.beginTransaction();
      Users  user=new Users();
      user.setUsername("ikeel");
      user.setPassword("ikeel");
      session.save(user);
      session.getTransaction().commit();
      System.out.println("KKKKKK");
           
     
}



其中用到一个Util类:HibernateSessionFactory:

package dian.ikeel.hibernate.util.SessionFactory;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;


public class HibernateSessionFactory {

        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

static {
    try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
    }
    private HibernateSessionFactory() {
    }

     public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

        return session;
    }

public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

     public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}

}
 

}

3,OK了,可以开始使用了,在命令行下进入到 Project/HibernateStudy/data 目录下,先建立data目录吧。然后执行:  java -classpath ..\lib\hsql.jar org.hsqldb.Server 数据库就启动了。
开始Run Entry,可以看到都发生了什么.....


4,接下来,我不想用xxx.hbm.xml了,我想试试annotation ....
分享到:
评论

相关推荐

    step by step 06 ssh整合hibernate

    struts2、spring、hibernate3.0整合

    ssh框架整合step by step (springMVC + spring 5.0.4 + hibernate 5.0.12)

    ssh框架搭建step by step (springMVC + spring 5.0.4 + hibernate 5.0.12) 好久不弄web了, 周末心血来潮, 使用较新spirng/hibernate搭建一个ssh框架, 供有需要的同学参考/学习/使用. 使用eclipse开发, 搭建,分三步: ...

    hibernate中文文档

    1. Read 第 1 章 教程 for a tutorial with step-by-step instructions. The source code for the tutorial is included in the distribution in the doc/reference/tutorial/ directory. 2. Read 第 2 章 体系结构...

    step by step ssh 10

    ssh整合开发,用户管理模块,包括用户登录、删除、修改、查询等功能,集成Hibernate事务管理、数据源配置、拦截器等

    hibernate-shards.jar

    We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To ...

    Spring Hibernate, Jersey 创建restful 服务的例子

    Spring Hibernate, Jersey 创建restful 服务的例子 图文并茂,step by step

    Hibernate+Struts 无限级树形菜单(MSSQL).rar

    内含step by step 开发文档 一、说明: 1、开发环境: Eclipse3.2.1+MyEclipse5.1+Tomcat5.5+Microsoft SQL Server 2000 2、主要实现技术:Struts1.2+Hibernate3.0+JavaScript+JSTL1.1+自定义标签 3、页面的树形...

    NHibernate-MVC3 入门例子

    很多NHibernate的学习者往往都是通过Hibernate的文档来学习,但是毕竟不是所有的.Net开发者都熟悉Java,也不是所有的人都有精力有时间去学习Java,所以,我准备开始一个Step by Step的NHibernate教程,以便有兴趣的...

    HibernateValidatorJSR303的参考实现使用指南.pdf

    2. Validation step by step 2.1. 定义约束 2.1.1. 字段级(field level) 约束 2.1.2. 属性级别约束 2.1.3. 类级别约束 2.1.4. 约束继承 2.1.5. 对象图 2.2. 校验约束 2.2.1. 获取一个Validator的实例 2.2.2. ...

    GWT数据库管理系统

    Without Eclipse: 1) Create a new directory for ...5) Add extra libraries as required by the chapters to the scripts classpath (google apis, hibernate, etc) 6) Run either the launch or compile script.

    基于JAVA的BBS论坛的设计与实现.doc

    It makes the communication between people, communication becomes easier, especially in the field of IT, we were only able to communicate well, technology will be promoted step by step. Therefore, how...

    NHibernate中文文档

    很多NHibernate的学习者往往都是通过Hibernate的文档来学习,但是毕竟不是所有的.Net开发者都熟悉Java,也不是所有的人都有精力有时间去学习Java,所以,我准备开始一个Step by Step的NHibernate教程,以便有兴趣的...

    Spring Recipes: A Problem-Solution Approach, Second Edition

    This book guides you step by step through topics using complete and real-world code examples. Instead of abstract descriptions on complex concepts, you will find live examples in this book. When you ...

    JdbcTemplateTool.zip

    快速开始STEP 1. 创建一个maven项目  创建一个maven项目叫testjtt. 添加jdbctemplatetool 依赖到pom.xml. 再添加以下依赖到 pom.xml.  &lt;groupId&gt;junit  &lt;artifactId&gt;junit  &lt;version&gt;4.11  &lt;scope&gt;test  ...

Global site tag (gtag.js) - Google Analytics