Hibernate3参考手册内容
Hibernate3参考手册内容
首先需要的包:
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collentions-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
jta.jar
log4j-1.2.11.jar
hibernate.jar
hsqldb.jar
mysql-connector-java-5.0.3-bin.jar
1。////////////////////////////////////////要持久化处理的类Event
package events;
import java.util.*;
public class Event {
private Long id;
private String title;
private Date date;
public Long getId() {
return id;
}
//注意是private,原因是我们一般不去处理这个id的
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;
}
}
2。/////////////////////////////////////////////////////Event类的数据库匹配文件Event.hbm.xml
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="events.Event" table="event">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="date" type="timestamp" column="date"/>
<property name="title"/>
</class>
</hibernate-mapping>
//注意这个配置文件和Event类最好放在同一个目录下,即配置文件也在这个events包下面
3。log4j.properties文件
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
4。.////////////////////////////////////////////////Hibernate.hbm.xml数据库配置文件
注意它和包在同一层次上
a。针对mysql的(这个是我家的,原文是hsqldb数据库)
<?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/yay</property>
<property name="connection.username">root</property>
<property name="connection.password">qwe123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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">create</property-->
<mapping resource="events/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
用mysql时候需要在yay数据库目录下建立表event,sql语句如下:
create table event
(
id bigint(5) auto_increment primary key,
date timestamp not null,
title varchar(50)
);
b。这个是以用hsqldb时候的配置文件
<?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">create</property-->
<mapping resource="events/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
这里需要提醒的是:你只需要启动数据库系统,不需要你自己去建立表格或者库。
启动数据库时候需要建立一个目录,比如data,然后在这个目录下键入这个dos命令:
D:/hibernate3/data>java -classpath ../lib/hsqldb.jar org.hsqldb.Server
这个时候如果你到data目录下去看,会看到自动生成3个文件,可见数据是保存在调用启动数据库命令的目录里面的。
5。/////////////////////////////////////////////////////获取SessionFactory对象的辅助类:
package 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;
}
}
6。////////////////////////////////////////////用来做测试,包含main方法的类
package events;
import org.hibernate.*;
import org.hibernate.criterion.Expression;
import java.util.*;
import 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();
System.out.println("**************************");
for (int i = 0; i < events.size(); i++) {
Event theEvent = (Event) events.get(i);
System.out.println("Event: " + theEvent.getTitle() +
" Time: " + theEvent.getDate());
}
System.out.println("**************************");
}
HibernateUtil.getSessionFactory().close();
}
private Long 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();
return theEvent.getId();
}
private List listEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery("from events.Event").list();
//List result = session.createQuery("from Event").list();也是可以的
session.getTransaction().commit();
return result;
}
}
7。////////////////////////////////////////少不了ant工具的配合
<project name="hibernate-tutorial" default="compile">
<property name="sourcedir" value="${basedir}/src"/>
<property name="targetdir" value="${basedir}/bin"/>
<property name="librarydir" value="${basedir}/lib"/>
<path id="libraries">
<fileset dir="${librarydir}">
<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="events.EventManager" classpathref="libraries">
<classpath path="${targetdir}"/>
<arg value="${action}"/>
</java>
</target>
<target name="war" depends="compile">
<war destfile="hibernate-tutorial.war" webxml="web.xml">
<lib dir="${librarydir}">
<exclude name="jsdk*.jar"/>
</lib>
<classes dir="${targetdir}"/>
</war>
</target>
</project>
注意这里的${basedir}指的就是build.xml文件所在的目录。
8。//////////////////////////////////运行:
注意,可以从命令行里面传递参数赋到ant中,比如这里的${action}"
参数一 run -Daction=store
参数二 run -Daction=list
给大家看看我的目录结构吧:》
hibernate目录
data目录 在这个目录下,调用命令启动hsqldb的
lib目录 在这个目录下,把需要的包全部放进来
SQL目录 在这个目录下,我生成mysql需要的sql语句
enentTable.sql 文件
src目录
events包
Event.hbm.xml 文件
Event.java文件
EventManager.java文件
util包
HibernateUtil.java 文件
hibernate.cfg.xml文件(注意针对mysql和hsqldb的各不相同)
log4j.properties文件
build.xml文件