一个简单的hibernate入门例子!

hibernate比较有用的一个简单入门例子,步骤详细见下面描述:

1、创建表 TEST_USER

                create table TEST_USER
                (
                   ID       VARCHAR2(40 CHAR) not null,
                   USERNAME VARCHAR2(255 CHAR),
                   PASSWORD VARCHAR2(255 CHAR)
                   );

2、创建对应的entity文件  User.java

              public class User implements Serializable
 {
 private String id;
 private String username;
 private String password;
 public User() {
 }
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 
}

 

3、创建user对象对应的hbm文件 User.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 package="cn.com.test.entity">
<class name="User" table="test_user" >
 <id name="id" column="id" length="40">
            <generator class="uuid.hex"/>
    </id>
 <property name="username" ></property>
 <property name="password" ></property>
</class>
</hibernate-mapping>

 

4、创建hibernate的配置文件  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>
    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 <property name="hibernate.connection.url">jdbc:oracle:thin:@datebaseIp:1521:sid</property>
 <property name="hibernate.connection.username">username</property>
 <property name="hibernate.connection.password">password</property>
 <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
 <!--
 <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
 <property name="hibernate.connection.url">jdbc:postgresql://devserver/devdb</property>
 <property name="hibernate.connection.username">username</property>
 <property name="hibernate.connection.password">password</property>
 <property name="hibernate.dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>
 -->
 
 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
 <property name="hibernate.show_sql">true</property>
 
    <mapping resource="cn/com/test/User.hbm.xml" />
</session-factory>

</hibernate-configuration>

 

5、创建sessionFactory工厂公共类

package com.pccw.dylan.demo.util;

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


public class HibernateUtil {
 private static SessionFactory factory;
 static {
  try {
   // 读取配置文件
   Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
   factory = cfg.buildSessionFactory();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 // 创建sessionFactory
 public static SessionFactory getSessionFactory() {
  return factory;
 }

 // 创建session
 public static Session getSession() {
  return factory.openSession();
 }

 // 关闭session,要关闭的时候条用这个方法就可以了
 public static void closeSession(Session session) {
  if (session != null) {
   if (session.isOpen()) {
    session.close();
   }
  }
 }
}

 

6、完成上面的步骤后,就可以写一个测试类进行测试

package com.pccw.dylan.demo.test;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.pccw.dylan.demo.entity.User;
import com.pccw.dylan.demo.util.HibernateUtil;

public class HibernateTest {
 private static final Logger log = Logger.getLogger(HibernateTest.class);

 /** */
 /**
  * @param args
  * @throws HibernateException
  * @throws SQLException
  */
 public void insertUser() throws HibernateException, SQLException {
  Session session = (Session) HibernateUtil.getSession();
  Transaction tx = session.beginTransaction();
  User user = new User();
  user.setUsername("ttt");
  user.setPassword("ttt");
  session.save(user);
  tx.commit();
  HibernateUtil.closeSession(session);
  System.out.println("新增成功!");
 }

 public List getUsers() {

  Session session = (Session) HibernateUtil.getSession();
  Transaction tx = session.beginTransaction();
  String hql = "from User d  where d.username=:name";
  Query query = session.createQuery(hql);
  query.setString("name", "test");
  List list = query.list();
  tx.commit();
  HibernateUtil.closeSession(session);
  return list;
 }

 public void updateUsers() {
  Session session = (Session) HibernateUtil.getSession();
  Transaction tx = session.beginTransaction();
  String hql = "update  User  set password='gm' ";
  Query query = session.createQuery(hql);
  query.executeUpdate();
  tx.commit();
  HibernateUtil.closeSession(session);
  log.info("更新成功!");
 }

 public void deleteUsers() {
  Session session = (Session) HibernateUtil.getSession();
  Transaction tx = session.beginTransaction();
  String hql = "delete from User  where id='f104ed282e7979b3012e7979b4430001'";
  Query query = session.createQuery(hql);
  query.executeUpdate();
  tx.commit();
  HibernateUtil.closeSession(session);
  log.info("删除成功!");
 }

 public static void main(String[] args) throws HibernateException, SQLException {
  log.info("====begin===test====");
  new HibernateTest().insertUser();
  // new HibernateTest().updateUsers();
  // new HibernateTest().deleteUsers();
  List list = new HibernateTest().getUsers();
  for (Iterator iter = list.iterator(); iter.hasNext();) {
   User user = (User) iter.next();
   log.info(user.getPassword());
  }
 }
}

在做的过程中可能会碰到一些问题,红色字体标明容易导致异常的地方,应该特别注意。项目依赖一些jar包入

antlr.jar

asm.jar

cglib.jar

commons-beanutils.jar

commons-collections.jar

commons-logging.jar

dom4j.jar

hibernate3.jar

j2ee.jar

log4j.jar

oracle.jar 

spring.jar

由于连接的是oracle数据库所以采用oracle的驱动

其中没有写明jar包的版本号,一般别太老的版本就应该没有问题的。

工程的目录结构不做强调,可以写到一起,也可以分成不同的包路径,不做详细说明。

希望这个例子能帮助需要的人。谢谢大家支持。特殊声明:部分代码也参照网上的例子。

 

          

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值