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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:orcl </property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <property name="myeclipse.connection.profile"> oracle.jdbc.driver.OracleDriver </property> <property name="format_sql">true</property> <property name="show_sql">true</property> <property name="connection.pool_size">3</property> <mapping resource="event.hbm.xml" /> <mapping resource="person.hbm.xml" /> </session-factory> </hibernate-configuration>
event.hbm.xml
<?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="com.main.java.bean"> <class name="Event" table="lsy_event"> <id name="id" type="java.lang.Integer" column="EVENT_ID"> <generator class="native" /> </id> <property name="date" type="java.util.Date" column="EVENT_DATE" /> <property name="title" type="java.lang.String"/> </class> </hibernate-mapping>
person.hbm.xml
<?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="com.main.java.bean"> <class name="Person" table="lsy_person"> <id name="id" type="java.lang.Integer" column="PERSON_ID"> <generator class="increment" /> </id> <property name="age" type="java.lang.Integer" /> <property name="firstname" type="java.lang.String" /> <property name="lastname" type="java.lang.String" /> <set name="events" table="lsy_person_event"> <key column="PERSON_ID"/> <many-to-many column="EVENT_ID" class="Event"/> </set> </class> </hibernate-mapping>
Event.java
package com.main.java.bean; import java.util.Date; public class Event { private int id; private String title; private Date date; public Event() {} public int getId() { return id; } public void setId(int 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; } }
Person.java
package com.main.java.bean; import java.util.HashSet; import java.util.Set; public class Person { private int id; private int age; private String firstname; private String lastname; private Set events = new HashSet(); public Person() {} public Set getEvents() { return events; } public void setEvents(Set events) { this.events = events; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } }
HibernateSessionFactory,java
package com.main.java; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; public static String PUBLIC_CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() {} /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
HibernateUtil.java
package com.main.java; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static String LSY_CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure(LSY_CONFIG_FILE_LOCATION).buildSessionFactory(); // return HibernateSessionFactory.getSessionFactory(); } 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; } }
2012-04-08我修改了这个类,加入了批量新增和批量修改的例子
EventManager.java
package com.main.java.event; import java.util.Date; import java.util.List; import org.hibernate.CacheMode; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import spring.container.SpringContainer; import com.main.java.HibernateSessionFactory; import com.main.java.HibernateUtil; import com.main.java.bean.Event; import com.main.java.bean.Person; /** * 本例主要实验hibernate的添删改查,研究其特点,所以都是单表操作 * @author Administrator * */ public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); // 作为测试,我们只用Event做添删改查 //1 新增 // mgr.createAndStoreEvent("My Event88", new Date()); // mgr.createAndStoreEvent("My Event2", new Date()); //批量插入 // mgr.createAndStoreEventBatch(); //插入1万条数据,耗时:消耗时间13秒,打印台打印如下: //消耗时间; //13 // 2查询 // List list=mgr.selectEvent("My Event1"); // System.out.println(list.size()); //3-1删除 // Event e1=new Event(); // e1.setTitle("My Event"); // //直接删除对象,其条件是id(主键)必须知道; // //不给主键的值,hibernate就删不了,可以先查询再删除 // e1.setId(3); // mgr.deleteEvent(e1); //3-2删除 // mgr.deleteEventById(4);//这里我直接把id传入了,你可以先查询 //4-1修改 // Event e2=new Event(); //e2.setTitle("My Ev1"); //同样,hibernate要update也必须知道id, //因为其默认的where条件就是: where id(主键)=? //另外要注意,hibernate默认把你给的对象的所有属性都更新, //你没给其他属性复制的话,最后其他属性都被更新成null了! //e2.setId(11); // mgr.updateEvent(e2); //如果你知道某个实例的持久化标识(identifier),你就可以使用 Session 的 load() 方法来获取它 //我们把上面都注掉 // Event e2=new Event(); // mgr.updateEventLoad(11);//使用load方法 // mgr.updateEventLoadObject(e2,11);//使用load方法 // mgr.updateEventGet(11);//使用get方法 /* 从上面的例子可以看出,hibernate的更新操作必须知道id, 因为这是where条件所必需的。 所以自然而然就分几种情况: 1,我知道id,给这个对象赋上值调用update方法就可以了; 2,我知道id,也确定session有这个对象(没有的话最后它去数据库查找), 就可以使用load方法。 3,我知道id,让它去数据库查找这个对象。 这3中方式无非就是先查找,找到后你再修改它的值,然后再调用update语句, 不同的只是查找的方式而已。 */ //4-2修改 // Event e3=new Event(); // e3.setTitle("My Event345"); //同样,hibernate要update也必须知道id, //因为其默认的where条件就是: where id(主键)=? //另外要注意,hibernate默认把你给的对象的所有属性都更新, //你没给其他属性复制的话,最后其他属性都被更新成null了! // e3.setId(7); // mgr.updateEventBySql(e3); //批量操作 //批量修改 mgr.updateEventBatch(); //测试数据1万条,耗时6秒,控制台输出如下: //消耗时间; //6 //最后关闭sessionFactory HibernateUtil.getSessionFactory().close(); } /** * 新增event对象 * 主键生成为"native",若报没有***序列,你到数据库建一个这样的序列 * @param title * @param theDate */ private void createAndStoreEvent(String title, Date theDate) { // 最原始的写法,这样很繁琐 // Configuration configuration = new Configuration(); // SessionFactory sfc = configuration.configure( // HibernateSessionFactory.PUBLIC_CONFIG_FILE_LOCATION) // .buildSessionFactory(); // Session session =sfc.openSession(); // 使用封装的HibernateUtil就很简洁 // Session session = // HibernateUtil.getSessionFactory().openSession();//测试成功 // 使用封装的HibernateSessionFactory就很简洁 Session session = HibernateSessionFactory.getSessionFactory() .openSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); } /** * 新增event对象,批量插入测试(测试1万条数据) * 主键生成为"native",若报没有***序列,你到数据库建一个这样的序列 * @param title * @param theDate */ private void createAndStoreEventBatch() { // 最原始的写法,这样很繁琐 // Configuration configuration = new Configuration(); // SessionFactory sfc = configuration.configure( // HibernateSessionFactory.PUBLIC_CONFIG_FILE_LOCATION) // .buildSessionFactory(); // Session session =sfc.openSession(); // 使用封装的HibernateUtil就很简洁 // Session session = // HibernateUtil.getSessionFactory().openSession();//测试成功 // 使用封装的HibernateSessionFactory就很简洁 Session session = HibernateSessionFactory.getSessionFactory() .openSession(); session.beginTransaction(); Date dd1=new Date(); //1万数据 for(int i=0;i<10000;i++){ Event theEvent = new Event(); theEvent.setTitle("title-"+i); theEvent.setDate(new Date()); session.save(theEvent); if(i%20==0){ //每一批20条数据就插入 session.flush(); session.clear(); System.out.println("刷新session--"+i); } } Date dd2=new Date(); System.out.println("消耗时间;"); System.out.println((dd2.getTime()-dd1.getTime())/1000); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); } /** * 查询event对象 * * @param title * @param theDate */ private List selectEvent(String title) { // 使用封装的HibernateUtil就很简洁 Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功 session.beginTransaction(); // Event theEvent = new Event(); // theEvent.setTitle(title); List res=session.createSQLQuery("select * from lsy_event b where b.title='"+title+"'").list(); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); return res; } /** * 删除event对象 * * @param title * @param theDate */ private void deleteEvent(Event theEvent) { // 使用封装的HibernateUtil就很简洁 Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功 session.beginTransaction(); session.delete(theEvent); System.out.println("here deleting~~~"); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); } /** * id删除event对象 * * @param title * @param theDate */ private void deleteEventById(int id) { // 使用封装的HibernateUtil就很简洁 Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功 session.beginTransaction(); String hql="delete from lsy_event b where b.event_id="+id; session.createSQLQuery(hql).executeUpdate(); System.out.println("here SQL deleting~~~"); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); } /** * 修改event对象 * * @param title * @param theDate */ private void updateEvent(Event theEvent) { // 使用封装的HibernateUtil就很简洁 // Session session = HibernateUtil.openSession();// 测试成功 SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory"); Session session=sessionFactory.openSession(); session.beginTransaction(); session.update(theEvent); System.out.println("here updating~~~"); session.getTransaction().commit(); session.close(); } /** * 批量修改event对象(测试1万条数据) * * @param title * @param theDate */ private void updateEventBatch() { // 使用封装的HibernateUtil就很简洁 // Session session = HibernateUtil.openSession();// 测试成功 SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory"); Session session=sessionFactory.openSession(); session.beginTransaction(); Date dd1=new Date(); ScrollableResults eventlist = session.createQuery("select e from Event e ") .setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); int count=0; while ( eventlist.next() ) { Event ee = (Event) eventlist.get(0);//注意这里确实是0,不是其他。为什么我也不清楚。 ee.setTitle("new-title"+count); if ( ++count % 20 == 0 ) { //flush a batch of updates and release memory: session.flush(); session.clear(); System.out.println("刷新session--"+count); } } Date dd2=new Date(); System.out.println("消耗时间;"); System.out.println((dd2.getTime()-dd1.getTime())/1000); session.getTransaction().commit(); session.close(); } /** * 修改event对象,使用load方法 * 如果你知道某个实例的持久化标识(identifier),你就可以使用 Session 的 load() 方法来获取它 * @param title * @param theDate */ private void updateEventLoad(int id) { // 使用封装的HibernateUtil就很简洁 // Session session = HibernateUtil.openSession();// 测试成功 SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory"); Session session=sessionFactory.openSession(); session.beginTransaction(); Event theEvent2=(Event)session.load(Event.class, id); theEvent2.setTitle("loadtttt"); System.out.println("here updating~~~"); session.getTransaction().commit(); session.close(); } /** * 修改event对象,使用load方法,传入对象 * 如果你知道某个实例的持久化标识(identifier),你就可以使用 Session 的 load() 方法来获取它 * @param title * @param theDate */ private void updateEventLoadObject(Event ev,int id) { // 使用封装的HibernateUtil就很简洁 // Session session = HibernateUtil.openSession();// 测试成功 SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory"); Session session=sessionFactory.openSession(); session.beginTransaction(); session.load(ev, id); ev.setTitle("loadooooo"); System.out.println("here updating~~~"); session.getTransaction().commit(); session.close(); } /** * 修改event对象,使用load方法,传入对象 * 如果你不确定是否有匹配的行存在,应该使用 get() 方法,它会立刻访问数据库,如果没有对应的记录,会返回 null。 * @param title * @param theDate */ private void updateEventGet(int id) { // 使用封装的HibernateUtil就很简洁 // Session session = HibernateUtil.openSession();// 测试成功 SessionFactory sessionFactory=(SessionFactory)SpringContainer.getBean("sessionFactory"); Session session=sessionFactory.openSession(); session.beginTransaction(); Event ee=(Event)session.get(Event.class, id); ee.setTitle("get"); System.out.println("here updating~~~"); session.getTransaction().commit(); session.close(); } /** * Sql修改event对象 * * @param title * @param theDate */ private void updateEventBySql(Event theEvent) { // 使用封装的HibernateUtil就很简洁 Session session = HibernateUtil.getSessionFactory().openSession();// 测试成功 session.beginTransaction(); String sql=" update lsy_event d set d.title='"+theEvent.getTitle()+"'" + " where d.event_id="+theEvent.getId(); session.createSQLQuery(sql).executeUpdate(); System.out.println("here SQL updating~~~"); session.getTransaction().commit(); session.close(); // HibernateUtil.getSessionFactory().close(); } }
数据库设计:
-- Create table create table LSY_EVENT ( event_id char(32), event_date date, title varchar2(32) ) tablespace USERS storage ( initial 64K minextents 1 maxextents unlimited ); -- Create/Recreate primary, unique and foreign key constraints alter table LSY_EVENT add constraint evente_pk primary key (EVENT_ID); -- Create table create table LSY_PERSON ( person_id char(32), age number, firstname varchar2(32), lastname varchar2(32) ) tablespace USERS storage ( initial 64K minextents 1 maxextents unlimited ); -- Add comments to the table comment on table LSY_PERSON is '人员表'; -- Create/Recreate primary, unique and foreign key constraints alter table LSY_PERSON add constraint person_pk primary key (PERSON_ID); -- Create table create table LSY_PERSON_EVENT ( event_id char(32), person_id char(32) ) tablespace USERS storage ( initial 64K minextents 1 maxextents unlimited ); -- Add comments to the table comment on table LSY_PERSON_EVENT is '人员事件关联表'; -- Create/Recreate primary, unique and foreign key constraints alter table LSY_PERSON_EVENT add constraint person_event_f1_person foreign key (PERSON_ID) references lsy_person (PERSON_ID); alter table LSY_PERSON_EVENT add constraint person_event_f1_event foreign key (EVENT_ID) references lsy_event (EVENT_ID);