Deploy the jar file first
1. \hibernate3.jar in the root directory
2. All jars in the lib\required directory
3. lib\jpa (java persistence API)\hibernate-jpa-2.0-api-1.0.1.Final.jar (Jpa is a specification, and Hibernate is an implementation of it)
4. Oracle database driver package (find the corresponding version of the driver in the database installation directory jdbc\lib\)
Write the Hibernate configuration file:
<?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--> <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> <!-- Auxiliary parameters --> <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> <!-- map file --> <mapping resource="po/User.hbm.xml"/> </session-factory> </hibernate-configuration>
Create persistent classes and mapping files:
Example of a persistent class:
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; } }
Example of map file:
<?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 dynamic update --> <class name="po.User" table="`USERS`" dynamic-update="true"> <id name="id" type="java.lang.Integer" ><!-- setId, the method called directly when accessing --> <column name="`ID`" precision="4" scale="0"></column> <!-- assigned The program needs to produce the primary key, and the code spliced according to the business requirements, to create a class in the program --> <!-- sequence access sequence to obtain code identity self-increment sequence increment (unsafe) first find out the largest code, add 1 as the primary key --> <!-- The algorithm of uuid uuid creates uuid --> <!-- native auto-increment, hibernate judges the auto-increment type by itself, there is a default type --> <!--<generator class=sequence> [If you don't write param, find the sequence named hibernate_sequence by yourself] [If the sequence used in each table is different, the following <param> should be written, specifying the sequence name] <param name="sequence">SEQ_ID</param> </generator> --> <generator class="increment"></generator> </id> <!-- The name of the property is the name in the get and set method names in pojo, not the property name--> <!-- Note not-null, the effect on 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>
Use Hibernate API;
get 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 { //Read the configuration file in the default location (if the path is changed, it should take parameters) cfg = new Configuration().configure(); //Get the SessionFactory object. sessionFactory = cfg.buildSessionFactory(); } catch (HibernateException e) { //There should be a log here throw new RuntimeException("Hibernate initialization failed",e); } } public static Session getSession(){ //sessionFactory.openSession(); It is not recommended to use opensession, because this session is not bound to a thread and needs to be implemented through additional code //It is recommended to use the following method to get the session bound to the current thread, but it should be noted that this session must work in a transaction environment return sessionFactory.getCurrentSession(); } }
Write Dao
package dao;
import po.User;
import common.HibernateSessionFactory;
public class UserDao {
//Increase
public void add(User user){
HibernateSessionFactory.getSession().save(user);
}
//Inquire
public User queryById(java.io.Serializable id){
//You can write like this--"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; } //省略部分代码 }