第一个最简单的Hibernate

需要导入
hibernate3.jar和required文件夹下的所有jar及jpa文件夹下的包
1。hibernate.cfg.xml 放在src根目录下面
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="connection.url">jdbc:oracle:thin:@localhost:1521:dbname</property>
  <property name="connection.username">userName</property>
  <property name="connection.password">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 -->
  <!--
  hbm2ddl.auto的值设为create的时候会先删除数据库中的表和记录。
  设为update的时候不会删除表和记录,如果**.hbm.xml中定义的表字段
  在原数据库表中没有的时候会增加一列,该列值设为空,其他记录值都不变;
  如果**.hbm.xml中定义的表字段是主键,则会抛出异常。
   -->
  <property name="hbm2ddl.auto">update</property>
  <mapping resource="test/domain/Event.hbm.xml" />
<!--
  <mapping resource="test/domain/Person.hbm.xml"/>
-->
 </session-factory>
</hibernate-configuration>


2。从hibernate包的project/etc目录下面拷贝log4j.properties到src根目录下面,用来输出日志
### 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

 

3.建实体类Event.java
package test.domain;

import java.util.Date;

public class Event {
 private Long id;
 private String title;
 private Date date;
 private String discrib;

 public String getDiscrib() {
  return discrib;
 }

 public void setDiscrib(String discrib) {
  this.discrib = discrib;
 }

// 要有个无参数的构造函数

 public Event() {
 }

 public Long getId() {
  return 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;
 }
}


4.将实体类和数据库映射文件Event.hbm.xml放在一个包下面。Hibernate会根据该文件在数据库中建表
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="test.domain">
<class name="Event" table="EVENTS">

<!-- column 属性告诉 Hibernate EVENTS表的哪个字段持有主键值。 -->
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
<!-- 当没有设定column attribute 的时候,Hibernate 缺省地使用 JavaBean 的属性名作为字段 -->
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
<property name="discrib"/>
</class>
</hibernate-mapping>

 

5。建管理session的类HibernateUtil.java
package test.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 // SessionFactory 可以创建并打开新的 Session。一个 Session 代表一个单线程的单元
 // 操作,org.hibernate.SessionFactory 则是个线程安全的全局对象,只需要被实例化一次
 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;
 }
}

 

6.建测试类EventManager.java
package test.main;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import test.domain.Event;
import test.domain.Person;
import test.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() + "Discrib:" + theEvent.getDiscrib());
   }
  }
  HibernateUtil.getSessionFactory().close();
 }

 private List listEvents() {
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  List result = session.createQuery("from Event").list();
  session.getTransaction().commit();
  return result;
 }

 private Long createAndStoreEvent(String title, Date theDate) {
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();
  Event theEvent = new Event();
  theEvent.setTitle(title);
  theEvent.setDate(theDate);
  theEvent.setDiscrib("描述");
  session.save(theEvent);
  session.getTransaction().commit();
  return theEvent.getId();
 }
}

 

Hibernate体系结构图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值