从今天起开始学习hibernate3

阅读: 评论:0

从今天起开始学习hibernate3

从今天起开始学习hibernate3

从今天开始,要学学Hibernate。
先学习hibernate3的官方文档,e文太滥了,看的很费时。
按照Tutorial一步一步来:
一、建立以下目录结构及文件:

-d:projects
|-lib
|-jdbc
|-hsql.jar
|-hibernate3
|-antlr.jar
|-asm.jar
|-asm-attrs.jar
|-cglib.jar
|-commons-collections.jar
|-commons-logging.jar
|-dom4j.jar
|-ehcache.jar
|-hibernate3.jar
|-jta.jar
|-log4j.jar
|-hibernate3
|-tutorial
|-src
|-org
|-hibernate
|-tutorial
|-domain
|-Event.java
|-l
|-util
|-HibernateUtil.java

|-EventManager.java
|-l
|-log4j.properties
|-l
|-bin
|-hsql_database
|-start.bat
|-manager.bat



二、各文件内容及说明:

1、start.bat是启动hsql数据库的批处理文件,内容:

java -cp ../lib/jdbc/hsql.jar org.hsqldb.Server -database.0 tutorial -dbname.0 tutorial

用服务器模式启动hsql数据库
2、manager.bat是启动hsql数据库图形管理界面的处理文件,内容:

java -cp ..libjdbchsql.jar org.hsqldb.util.DatabaseManager -url jdbc:hsqldb:hsql://localhost/tutorial

3、l内容:


<project name="hibernate-tutorial" default="compile">

<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/bin"/>
<property name="librarydir" value="${basedir}/../../lib/hibernate"/>

<path id="libraries">
<fileset dir="${librarydir}">
<include name="*.jar"/>
</fileset>
<fileset dir="${librarydir}/../jdbc">
<include name="*.jar"/>
</fileset>
</path>

<target name="clean">
<delete dir="${targetdir}"/>
<mkdir dir="${targetdir}"/>
</target>

<target name="compile" depends="clean, copy-resources">
<javac srcdir="${sourcedir}"
destdir="${targetdir}"
classpathref="libraries"/>
</target>

<target name="copy-resources">
<copy todir="${targetdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>

<target name="run" depends="compile">
<java fork="true" classname="org.hibernate.tutorial.EventManager" classpathref="libraries">
<classpath path="${targetdir}"/>
<arg value="${action}"/>
</java>
</target>
</project>


dos命令行下输入“ant” 将编译程序,输入“ant run -Daction=store”将持久类Event的对象写入数据库中,输入“ant run -Daction=list”将显示存储在数据库中的被持久化的Event类对象。(当然前提是当前目录在d:projectshibernate3下)

4、log4j.properties内容:


Logger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout


[quote]
Hibernate uses commons logging and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer Log4j
[/quote]
hibernate采用commons logging并提供两种选择,Log4j 和 JDK 1.4 logging,多数开发者倾向于Log4j,如果是Log4j就要在类路径下配置log4j.properties(或者通过-figuration=xx.properties来指定),如果是JDK 1.4 logging就要配置:logging.properties 并通过-Djava.fig.file=D:yourpathtologging.properties来指定。具体的设置参考[url].html[/url]
5、l内容:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
".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/tutorial</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="org/hibernate/tutorial/domain/l"/>

</session-factory>
</hibernate-configuration>

6、Event.java

package org.hibernate.tutorial.domain;

import java.util.Date;

public class Event {
private Long id;

private String title;
private Date date;
/*The no-argument constructor is a requirement for all persistent classes;
The constructor can be private, however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation. */
public Event() {}

public Long getId() {
return id;
}
//由于id通常由hibernate产生,故id的setter方法一般用private来限制。
//

private void setId(Long id) {
this.id = id;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}



7、l

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
".0.dtd">

<hibernate-mapping package="org.hibernate.tutorial.domain">
<class name="Event" table="EVENTS">
<id name="id" column="EVENT_ID">
<generator class="native" />
</id>
<property name="date" type="timestamp" column="EVENT_DATE" />
<property name="title" />
</class>
</hibernate-mapping>


[quote]
Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name. Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL date, timestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter.
[/quote]
Hibernate 默认的把属性名作为列名,但是,date在大多数的数据库管理系统中是保留关键字,所以的映射一个其他的名字,当一个属性类型为java.util.Date时,hibernate不知道该如何映射到SQL类型的date, timestamp, or time,但是timestamp类型完全包含了date 和 time 的所有信息,所以可以将java.util.Date映射为timestamp

8、HibernateUtil.java
package org.hibernate.tutorial.util;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from l
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}



9、EventManager.java
package org.hibernate.tutorial;

import org.hibernate.Session;

import java.util.*;

import org.hibernate.tutorial.domain.Event;
import org.hibernate.tutorial.util.HibernateUtil;

public class EventManager {

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

if (args[0].equals("store")) {
ateAndStoreEvent("My Event", new Date());
}else if (args[0].equals("list")) {
List events = mgr.listEvents();
for (int i = 0; i < events.size(); i++) {
Event theEvent = (Event) (i);
System.out.println(
"Event: " + Title() + " Time: " + Date()
);
}
}
SessionFactory().close();
}

private void createAndStoreEvent(String title, Date theDate) {
Session session = SessionFactory().getCurrentSession();
session.beginTransaction();

Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);

Transaction()mit();
}
private List listEvents() {
Session session = SessionFactory().getCurrentSession();
session.beginTransaction();
List result = ateQuery("from Event").list();
Transaction()mit();
return result;
}

}

本文发布于:2024-02-02 02:58:18,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170681581640952.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23