从今天开始,要学学Hibernate。
先学习hibernate3的官方文档,e文太滥了,看的很费时。
按照Tutorial一步一步来:
一、建立以下目录结构及文件:
二、各文件内容及说明:
1、start.bat是启动hsql数据库的批处理文件,内容:
用服务器模式启动hsql数据库
2、manager.bat是启动hsql数据库图形管理界面的处理文件,内容:
3、build.xml内容:
dos命令行下输入“ant” 将编译程序,输入“ant run -Daction=store”将持久类Event的对象写入数据库中,输入“ant run -Daction=list”将显示存储在数据库中的被持久化的Event类对象。(当然前提是当前目录在d:\projects\hibernate3下)
4、log4j.properties内容:
[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(或者通过-Dlog4j.configuration=xx.properties来指定),如果是JDK 1.4 logging就要配置:logging.properties 并通过-Djava.util.logging.config.file=D:\your\path\to\logging.properties来指定。具体的设置参考[url]http://www.blogjava.net/tedeyang/articles/18935.html[/url]
5、hibernate.cfg.xml内容:
6、Event.java
7、Event.hbm.xml
[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
9、EventManager.java
先学习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
|-Event.hbm.xml
|-util
|-HibernateUtil.java
|-EventManager.java
|-hibernate.cfg.xml
|-log4j.properties
|-build.xml
|-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 ..\lib\jdbc\hsql.jar org.hsqldb.util.DatabaseManager -url jdbc:hsqldb:hsql://localhost/tutorial
3、build.xml内容:
<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:\projects\hibernate3下)
4、log4j.properties内容:
og4j.rootLogger=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(或者通过-Dlog4j.configuration=xx.properties来指定),如果是JDK 1.4 logging就要配置:logging.properties 并通过-Djava.util.logging.config.file=D:\your\path\to\logging.properties来指定。具体的设置参考[url]http://www.blogjava.net/tedeyang/articles/18935.html[/url]
5、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/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/Event.hbm.xml"/>
</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、Event.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="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 hibernate.cfg.xml
sessionFactory = 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;
}
}
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")) {
mgr.createAndStoreEvent("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) events.get(i);
System.out.println(
"Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
);
}
}
HibernateUtil.getSessionFactory().close();
}
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
}
private List listEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from Event").list();
session.getTransaction().commit();
return result;
}
}