使用Hibernate步骤:(一)
先部署jar文件
1、根目录下的 \hibernate3.jar
2、lib\required目录下所有jar
3、lib\jpa(java持久化API)\hibernate-jpa-2.0-api-1.0.1.Final.jar(Jpa是一种规范,而Hibernate是它的一种实现)
4、Oracle数据库的驱动包(在数据库安装目录 jdbc\lib\下 找对应的版本的驱动)
编写Hibernate配置文件:
<?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> <!-- 数据库连接 --> <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:oracle</property> <property name="connection.username">user01</property> <property name="connection.password">1234</property> <!-- 辅助参数 --> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="current_session_context_class">thread</property> <!-- 映射文件 --> <mapping resource="po/User.hbm.xml"/> </session-factory> </hibernate-configuration>
创建持久化类和映射文件:
持久化类示例:
package po; public class User implements java.io.Serializable { private static final long serialVersionUID = -2998707288951184222L; private Integer id; //OID private String name; private String password; private String telephone; private String username; private String isAdmin; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getIsAdmin() { return isAdmin; } public void setIsAdmin(String isAdmin) { this.isAdmin = isAdmin; } }
映射文件示例:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- dynamic-update 动态更新 --> <class name="po.User" table="`USERS`" dynamic-update="true"> <id name="id" type="java.lang.Integer" ><!-- setId,访问时直接调用的方法 --> <column name="`ID`" precision="4" scale="0"></column> <!-- assigned 需要由程序去生产主键,根据业务要求拼接的编码,要在程序中创建类 --> <!-- sequence 访问序列获得编码 identity自增序列 increment (不安全)先查出最大的编码,再加1当成主键 --> <!-- uuid uuid的算法创建uuid --> <!-- native 自增,hibernate自行判断自增类型,有默认的类型 --> <!--<generator class=sequence> [如果不写param,自行寻找名为hibernate_sequence的序列] [如果每张表用的序列不一样,就应写出如下<param>,指明序列名] <param name="sequence">SEQ_ID</param> </generator> --> <generator class="increment"></generator> </id> <!-- property 的name 为pojo里get,set方法名里的名 ,不是属性名 --> <!-- 注意not-null,对delete()的影响 --> <property name="name" type="java.lang.String" column="`NAME`" length="50" not-null="true"></property> <property name="password" type="java.lang.String"> <column name="`PASSWORD`" length="50" not-null="true"></column> </property> <property name="telephone" type="java.lang.String" column="`TELEPHONE`" length="15"></property> <property name="username" type="java.lang.String" column="`USERNAME`" length="50"></property> <property name="isAdmin" type="java.lang.String" column="`ISADMIN`" length="2"></property> </class> </hibernate-mapping>
使用Hibernate API;
得到Session - - >
package common; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static Configuration cfg; private static SessionFactory sessionFactory; static { try { //读取默认位置的配置文件(如果改了路径,就应带参) cfg = new Configuration().configure(); //得到SessionFactory对象. sessionFactory = cfg.buildSessionFactory(); } catch (HibernateException e) { //此处应有日志 throw new RuntimeException("Hibernate初始化失败",e); } } public static Session getSession(){ //sessionFactory.openSession();不建议用opensession,因为这个会话没有绑定线程,需通过额外的代码来实现 //建议用如下方法,得到与当前线程绑定的session, 但要注意此session要在事物环境下工作 return sessionFactory.getCurrentSession(); } }
编写Dao
package dao; import po.User; import common.HibernateSessionFactory; public class UserDao { //增加 public void add(User user){ HibernateSessionFactory.getSession().save(user); } //查询 public User queryById(java.io.Serializable id){ //可以这样写 --》HibernaterSessionFactory.getSession().get("po.User", id); return (User)HibernateSessionFactory.getSession().get(User.class, id); //get() 查不到返回null (OID 异常时) //load() 查不到,就报异常exception (OID 异常时) } //更新 public void update(User user){ HibernateSessionFactory.getSession().update(user); } // for save or update public void test(User user){ //方法一 、 id==null? save() : update() 产生的SQL语句,会把字段全部更新 //HibernateSessionFactory.getSession().saveOrUpdate(user); /* //方法二 、 快照(在表中查询结果) User u = (User) HibernateSessionFactory .getSession().get(User.class,user.getId()); //在查询的基础上,给查询的结果重新赋值,它会有一个比照的效果,u与user比照; //在比照中,如果数据有更新,就会更新表中数据 (hibernate中java对象的三种状态) //如果没有变化,就不产生变化 //如果在User.hbm.xml中配置 (动态更新配置) //动态更新配置 dynamic-update="true" ,SQL语句就只更新变化的字段 u.setIsAdmin(user.getIsAdmin()); u.setName(user.getName()); u.setPassword(user.getPassword()); u.setTelephone(user.getTelephone()); u.setUsername(user.getUsername()); */ //方法三、 for save or update // 配置 dynamic-update="true" // merge()可以实现 动态更新 HibernateSessionFactory.getSession().merge(user); } public void delete(User user){ //建议先查 快照 // 例如传过来的user只有oid,但name = null,此时直接delete会报错,因为映射文件里设置了name--》not-null,可以手动去把这个限制去掉 //User u = (User) HibernateSessionFactory // .getSession().get(User.class,user.getId()); // HibernateSessionFactory.getSession().delete(u); HibernateSessionFactory.getSession().delete(user); } }
编写 service
package biz; import org.hibernate.HibernateException; import org.hibernate.Transaction; import common.HibernaterSessionFactory; import po.User; import dao.UserDao; public class UserBiz { private UserDao userDao = new UserDao(); public void addUser(User user){ Transaction tx = null; try { //开启事务 tx = HibernaterSessionFactory.getSession().beginTransaction(); userDao.add(user); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if(tx != null){ tx.rollback(); } } }; public User getUserById(java.io.Serializable id){ Transaction tx = null; User user = null; try { //开启事务 tx = HibernaterSessionFactory.getSession().beginTransaction(); user = userDao.queryById(id); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if(tx != null){ tx.rollback(); } } return user; } //省略部分代码 }