一、先给出测试用表的结构和原始数据:
create table T_GRADES ( ID VARCHAR2(20) PRIMARY KEY, SUBJECT VARCHAR2(20), GRADE NUMBER(3,1), TEACHER VARCHAR2(20), STUDENTID VARCHAR2(20) ); INSERT INTO T_GRADES (ID, SUBJECT, GRADE, TEACHER, STUDENTID) VALUES ('1', '语文', 80, 'Miss_zhang', '050104010121'); INSERT INTO T_GRADES (ID, SUBJECT, GRADE, TEACHER, STUDENTID) VALUES ('2', '数学', 90, 'Miss_zhang', '050104010121'); INSERT INTO T_GRADES (ID, SUBJECT, GRADE, TEACHER, STUDENTID) VALUES ('3', '数学', 99.9, 'MR_huang', '050104010120'); INSERT INTO T_GRADES (ID, SUBJECT, GRADE, TEACHER, STUDENTID) VALUES ('4', '英语', 90, 'MR_huang', '050104010120'); COMMIT;二、在Myeclipse中新建一个java project,然后为该project 添加hibernate capabilities,在添加的过程中,会根据你设置的路径生成一些文件,包括:hibernate.cfg.xml,HibernateSessinFactory.java,当然会把需要的jar包一包含进来,下面就是自己的开发工作了。
三、首先给出MyEclipse生成的原始的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="connection.username">scott</property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:orcl </property> <property name="connection.password">test</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> </session-factory> </hibernate-configuration>现在这个文件中内容是在我们添加hibernate capabilities时,MyEclipse根据你的设置自动生成的,这部分是不用改动的。将来我们需要做的就是添加
四、下面给出Myeclipse自动生成的会话工厂类,这个类我们一点都不用动,直接用其中实现的方法即可。
package com.neuqsoft.hibernate; 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"; 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; } }五、下面开始就是自己亲手要做的工作了,下面的顺序依个人喜好而定,在程序运行之前只要这些文件齐全,应该就没有问题。
<?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="com.neuqsoft.model"> <class name="Grade" table="T_GRADES"> <id name="id" column="ID"> <generator class="assigned"></generator> </id> <property name="subject" column="SUBJECT"></property> <property name="grade" column="GRADE"></property> <property name="teacher" column="TEACHER"></property> <property name="studentId" column="STUDENTID"></property> </class> </hibernate-mapping>可以看出这里面定义的属性跟我给出的表结构是完全对应的。
package com.neuqsoft.model; public class Grade { private String id; private String subject; private float grade; private String teacher; private String studentId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public float getGrade() { return grade; } public void setGrade(float grade) { this.grade = grade; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } }5.3 根据HibernateSessionFactory.java提供的方法,自己生成了一个CRUD类,供后面自己使用起来方便简单,本工程的目录结构通过相应的包名都能看出来。
package com.neuqsoft.crud; import org.hibernate.*; import com.neuqsoft.model.Grade; import com.neuqsoft.hibernate.HibernateSessionFactory; import java.util.*; public class CRUD { private Session session; private Transaction ts; //构造函数初始化session和事务 public CRUD() { session = HibernateSessionFactory.getSession(); ts = session.beginTransaction(); } //添加 public void insert(Grade grade) { session.save(grade); } // 删除,通过ID public void delete(Grade grade) { session.delete(grade); } //删除通过HQL public int deletebyHQL(String hql){ Query query=session.createQuery(hql); int ref=query.executeUpdate(); return ref; } //查询ByCretria public List<Grade> queryByCriteria(Criteria c){ List<Grade> list=c.list(); return list; } //查询ByHQL public List<Grade> queryByHQL(String hql){ Query query=session.createQuery(hql); List<Grade> list=query.list(); return list; } //修改 public void update(Grade grade){ session.update(grade); } //提交事务,关闭session public void commit() { ts.commit(); } public void close(){ session.close(); } //重新开启事务: public void restartTransaction(){ ts = session.beginTransaction(); } //获取session public Session getSession(){ return HibernateSessionFactory.getSession(); } }5.4 下面给出真正的测试用类,这里提供的每一个方法都能单独使用,我这里全部写到一起了,一起执行也没问题的。
package com.neuqsoft.crud; import com.neuqsoft.model.*; import org.hibernate.Criteria; import org.hibernate.criterion.Expression; import java.util.*; public class CrudTest { public static void main(String args[]){ CRUD crud=new CRUD(); Grade grade=new Grade(); //1.新增一个grade记录到数据库中 grade.setId("25"); grade.setSubject("testsubject"); grade.setGrade((float)52.25); grade.setTeacher("MIss liu"); grade.setStudentId("050104010125"); crud.insert(grade); crud.commit(); System.out.println("成功插入一条记录"); //2.删除记录byID crud.restartTransaction(); Grade grade1=new Grade(); grade1.setId("20"); crud.delete(grade1); crud.commit(); System.out.println("成功通过ID删除一条记录"); //3.删除记录BYHQL crud.restartTransaction(); String hql="delete Grade where teacher like 'MIss%'"; int ref=crud.deletebyHQL(hql); crud.commit(); System.out.println("通过HQL已成功删除:"+ref+"条"); // 4.查询使用criteria Criteria criteria=crud.getSession().createCriteria(Grade.class); criteria.add(Expression.lt("teacher","Miss_zhang")); List<Grade> list=crud.queryByCriteria(criteria); for (int i=0;i<list.size();i++){ System.out.println(list.get(i).getId()+" " +list.get(i).getSubject()+" " +list.get(i).getGrade()+" " +list.get(i).getTeacher()+" " +list.get(i).getStudentId()); } System.out.println(); //5.查询使用HQL List<Grade> list1=crud.queryByHQL(" from Grade"); for (int i=0;i<list1.size();i++){ System.out.println(list1.get(i).getId()+" " +list1.get(i).getSubject()+" " +list1.get(i).getGrade()+" " +list1.get(i).getTeacher()+" " +list1.get(i).getStudentId()); } //6.更新,通过ID更新,按ID找到行,将grade改为相应的值,其他值不变。 crud.restartTransaction(); Grade grade2=(Grade)crud.getSession().get(Grade.class,"3"); grade2.setGrade((float)99.9); crud.update(grade2); crud.commit(); System.out.println("/n成功更新"); //7.关闭session crud.close(); } }5.5 最后的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="connection.username">scott</property> <property name="connection.url"> jdbc:oracle:thin:@127.0.0.1:1521:orcl </property> <property name="connection.password">test</property> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property> <mapping resource="Grade.hbm.xml" /> </session-factory> </hibernate-configuration>六、实际上hibernate并不像想象的那么神秘,不是Hibernate总是跟struts,spring捆绑的 它是自成一体的,为面向对象的访问数据库提供了很好的
src com.neuqsoft.crud CURD.java CurdTest.java com.neqsoft.hibernate HibernateSessionFactory.java com.nequsoft.model Grade.java hibernate.cfg.xml Grade.hbm.xml八、结束。