hibernate手动配置实例



hibernate手动配置实例

package com.ru.utils;会话工厂的工具类

 import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

public class GetSession {

private static SessionFactory sf=null;

//实例块只会被调用一次

static{

//读取hibernate的配置文件并且初始化“hibernate.cfg.xml”如果放在src下可以不写

Configuration configuration=new Configuration().configure(“hibernate.cfg.xml”);

//创建会话工厂

sf=configuration.buildSessionFactory();

}

public static SessionFactory getSessionFactory(){

return sf;

}

}
开发流程

1.       创建一个项目

2.       画出一个简单项目框架示意图

3.       引入hibernate 开发包 (从网上下载google  hibernate  http://www.hibernate.org),完后我们

4.       开发hibernate 有三种方法(开发顺序)该成mysql数据库

我们使用第二种开发项目

创建employe 表.

create table employee(

id int primary key,

name varchar(64) not null,

email varchar(64) not null,

hiredate date not null);

创建一个序列,将来用于主键的自增长 :

–创建一个序列

create sequence emp_seq

start with 1

increment by 1

minvalue 1

nomaxvalue

nocycle

nocache

5.       开发domain对象和对象关系映射文件

对象关系映射文件: 作用是用于指定 domain对象和表的映射关系. ,该文件的取名有规范:

domain对象.hbm.xml,一般我们放在 和domain对象同一个文件夹下(包下)

我们的Employee.hbml.xml配置文件 :

<!DOCTYPE hibernate-mapping PUBLIC

      ”-//Hibernate/Hibernate Mapping DTD 3.0//EN”

      ”http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping package=”com.hsp.domain”>

      <class name=”Employee” table=”employee”>

      <!– id元素用于指定主键属性–>

      <id name=”id” column=”id” type=”java.lang.Integer”>

      <!– 该元素用于指定主键值生成策略hilo native increment sequence uuid –>

 <!–如果是mysql的话:<generator></generator>自增长改成这样 就可以了–>
     
      <generator>

      <param name=”sequence”>emp_seq</param>

      </generator>

      </id>

      <!– 对其它属性还有配置–>

      <property name=”name” type=”java.lang.String”>

      <column name=”name” not-null=”false”  />

      </property>

      <property name=”email” type=”java.lang.String” >

      <column name=”email” not-null=”false”/>

      </property>

      <property name=”hiredate” type=”java.util.Date”>

      <column name=”hiredate” not-null=”false” />

      </property>

      </class>

     

</hibernate-mapping>

6.       手动配置我们的hibernate.cfg.xml文件,该文件用于配置 连接的数据库的类型,driver,

,用户名,密码 ,url ….同时管理 对象关系映射文件 ,该文件的名称,我们一般不修改.

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>

      <!– hibernate 设计者,给我们提供了一写常用的配置 –>

      <!– 配置使用的driver –>

      <property name=”connection.driver_class”>oracle.jdbc.driver.OracleDriver</property>

      <property name=”connection.username”>scott</property>

      <property name=”connection.password”>tiger</property>

      <property name=”connection.url”>jdbc:oracle:thin:@127.0.0.1:1521:orclhsp</property>

      <!– 配置dialect方言,明确告诉hibernate连接是哪种数据库 –>

      <property name=”dialect”>org.hibernate.dialect.OracleDialect</property>

      <!– 显示出对于sql –>

      <property name=”show_sql”>true</property>

<!– 让hibernate给我们自动创建表 create   每次都创建新表,update,如果没表创建新表,如果有表,查看关系映射文件是否有变化,没有变化更新数据,有变化创建新表. –>

<property name=”hbm2ddl.auto”>update</property>

<!– 当获取session的方式为getcurrentsession的时候需要配置 –>

<property name=”hibernate.current_session_context_class”>

thread

</property>

      <!– 指定管理的对象映射文件–>

      <mapping resource=”com/hsp/domain/Employee.hbm.xml”/>

</session-factory>

</hibernate-configuration>

 7.测试文件
test.java

package com.ru.service;

 

import java.util.Date;

import java.util.Iterator;

import java.util.List;

 

 

import javax.transaction.HeuristicMixedException;

import javax.transaction.HeuristicRollbackException;

import javax.transaction.RollbackException;

import javax.transaction.SystemException;

 

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.hibernate.classic.Session;

 

import com.ru.domain.Employee;

import com.ru.utils.GetSession;

 

 

 

public class test1 {


 

public static void main(String[] args) {

insertuser();

//updateuser();

//deleteuser();

queryuser();

//loaduser();

// getuser();

}

//查询用户1

//getCurrentSession需要事务。并且session自动关闭。

public static void queryuser(){

SessionFactory sf=GetSession.getSessionFactory();

Session session=sf.getCurrentSession();

Transaction ts=session.beginTransaction();

//query查询,Employee是类,不是表。name是变量

try {

Query query=(Query)session.createQuery(“from Employee where name=’南成如’”);

List<Employee> list=query.list();

for (Employee employee : list) {

System.out.print(employee.getId()+”–”+employee.getName()+”–”+employee.getEmail());

}

ts.commit();

} catch (HibernateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//查询用户2

//如果使用openSession不需要事务,需要手动关闭session

public static void loaduser(){

SessionFactory sf=GetSession.getSessionFactory();

Session session=sf.getCurrentSession();

Transaction ts=session.beginTransaction();

try {

Employee em=(Employee) session.load(Employee.class, 1);

System.out.print(em.getName());

ts.commit();

} catch (HibernateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//查询用户3

//如果使用openSession不需要事务,需要手动关闭session

public static void getuser(){

SessionFactory sf=GetSession.getSessionFactory();

Session session=sf.openSession();

try {

Employee em=(Employee) session.load(Employee.class, 4);

System.out.print(em.getName());

} catch (HibernateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if (session!=null) {

session.close();

}

}

}

//修改用户

public static void updateuser(){

//得到会话工厂

SessionFactory sf=GetSession.getSessionFactory();

//创建会话,得到连接

Session session=sf.openSession();

//设置事务

Transaction transation=session.beginTransaction();

//修改用户要先获取用户

//load会通过主键属性,获取给对象实例。

Employee em=(Employee)session.load(Employee.class, 1);//产生一个select语句

em.setName(“如”);//导致一个update语句

em.setEmail(“*********@qq.com”);

//提交事务,关闭会话

transation.commit();

session.close();

}

//删除用户

public static void deleteuser(){

//获取会话工厂

SessionFactory sf=GetSession.getSessionFactory();

//打开会话

Session session=sf.openSession();

//设置事务,增删改都要设置事务,否则不执行

Transaction ts=null;

try {

ts=session.beginTransaction();

//删除用户先要获取用户

Employee em=(Employee)session.load(Employee.class, 1);

session.delete(em);

//提交事务,关闭会话

ts.commit();

} catch (HibernateException e) {

// TODO Auto-generated catch block

if (ts!=null) {

ts.rollback();//回滚

}

throw new RuntimeException(e.getMessage());

}finally{

if (session!=null&&session.isOpen()) {

session.close();

}

}

}

//添加用户

public static void insertuser() {

//1.读取heibernate的配置文件hibernate.cfg.xml,并完成初始化

Configuration configure=new Configuration().configure(“hibernate.cfg.xml”);

//2.创建会话工厂

SessionFactory sf=configure.buildSessionFactory();

//3.创建session,相当于连接jdbc

Session session=sf.openSession();

//4.4.对hiberate而言,要求程序员,在进行 增加,删除,修改的时候使用事务提交,

Transaction transation=session.beginTransaction();

//5.创建对象

Employee e=new Employee();

e.setName(“如”);

e.setEmail(“*********@qq.com”);

e.setHiredate(new Date());

//6.save employee就是持久化该对象 (把对象保存到了数据库中称为一条记录)

//==>insert into ….[被hiberante封装]

session.save(e);

//提交事务。关闭会话

transation.commit();

session.close();

}

 

}