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="hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.DB2Dialect</property> <property name="connection.url">jdbc:db2://192.168.25.230:50000/JSAMPLE</property> <property name="connection.username">zyl</property> <property name="connection.password">123</property> <property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property> <property name="myeclipse.connection.profile">zyl</property> <mapping resource="com/zyl/po/UsersPO.hbm.xml" /> </session-factory> </hibernate-configuration> ------------------------------------------------------------------------------------------- UsersPO.java package com.zyl.po; import java.io.Serializable; import java.util.Date; public class UsersPO implements Serializable{ /** * */ private Long usersID; private String username; private String userpassword; private Date regDate; public Long getUsersID() { return usersID; } public void setUsersID(Long usersID) { this.usersID = usersID; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpassword() { return userpassword; } public void setUserpassword(String userpassword) { this.userpassword = userpassword; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public UsersPO(String username, String userpassword, Date regDate) { super(); this.username = username; this.userpassword = userpassword; this.regDate = regDate; } } ------------------------------------------------------------------------------------------- UsersPO.hbm.xml <?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.zyl.po" schema="zyl"> <class name="UsersPO" table="zylUsers"> <id column="usersID" name="usersID" type="long"> <generator class="sequence"> <param name="sequence">users_seq</param> </generator> </id> <property name="username" type="string"/> <property name="userpassword" type="string"/> <property name="regDate" type="date"/> </class> <database-object> <create><![CDATA[create sequence users_seq start with 1]]></create> <drop></drop> <dialect-scope name="org.hibernate.dialect.DB2Dialect"/> </database-object> </hibernate-mapping> ------------------------------------------------------------------------------------------- UsersDAO.java package com.zyl.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.zyl.factory.HibernateSessionFactory; import com.zyl.po.UsersPO; public class UsersDAO { public void saveUser(UsersPO usersPO){ Session session = HibernateSessionFactory.getSession(); Transaction trans = session.beginTransaction(); session.save(usersPO); trans.commit(); session.close(); } public UsersPO findUsersById(Long id){ Session session = HibernateSessionFactory.getSession(); Transaction trans = session.beginTransaction(); UsersPO usersPO =(UsersPO)session.load(com.zyl.po.UsersPO.class, id); trans.commit(); session.close(); return usersPO; } public List<UsersPO> findAllUsersPO(){ Session session = HibernateSessionFactory.getSession(); Transaction trans = session.beginTransaction(); Query query = session.createQuery("select u from UsersPO u order by u.usersID desc"); List<UsersPO> usersList = query.list(); trans.commit(); session.close(); return usersList; } public void updateUsersPO(UsersPO usersPO){ Session session = HibernateSessionFactory.getSession(); Transaction trans = session.beginTransaction(); session.update(usersPO); trans.commit(); session.close(); } public void deleteUsersPO(UsersPO usersPO){ Session session = HibernateSessionFactory.getSession(); Transaction trans = session.beginTransaction(); session.delete(usersPO); trans.commit(); session.close(); } } ------------------------------------------------------------------------------------------- package com.ascent.dao.test; import java.util.List; import junit.framework.Assert; import org.junit.Test; import com.ascent.dao.UsersDAO; import com.ascent.po.UsersPO; public class UsersDAOTestCase { ///@Test public void testSaveUsers() { UsersPO usersPO = new UsersPO("zyl","123",new java.util.Date()); UsersDAO usersDAO = new UsersDAO(); usersDAO.saveUsers(usersPO); Assert.assertNotNull("插入失败",usersPO.getUsersID()); System.out.println(usersPO.getUsersID()); } //@Test public void testFindUsersPOById(){ UsersDAO usersDAO = new UsersDAO(); UsersPO usersPO = usersDAO.findUsersById(2L); Assert.assertNotNull("查询失败",usersPO); System.out.println(usersPO.toString()); } //@Test public void testFindAllUsersPO(){ UsersDAO usersDAO = new UsersDAO(); List<UsersPO> usersList = usersDAO.findAllUsersPO(); Assert.assertNotNull(usersList); for (UsersPO usersPO : usersList) { System.out.println(usersPO); } } ///@Test public void testUpdateUsersPO(){ UsersDAO usersDAO = new UsersDAO(); UsersPO usersPO = usersDAO.findUsersById(2L); Assert.assertNotNull("查询失败",usersPO); usersPO.setUsersName("xyf"); usersDAO.updateUsersPO(usersPO); } @Test public void testDeleteUsersPO(){ UsersDAO usersDAO = new UsersDAO(); UsersPO usersPO = usersDAO.findUsersById(1L); Assert.assertNotNull("查询失败",usersPO); // usersPO.setUsersName("ddd"); usersDAO.deleteUsersPO(usersPO); } }------------------------------------------------------------------------------------------- HibernateSessionFactory.java package com.zyl.hiber.SessionFactory; 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; } }------------------------------------------------------------------------------------------- ToDDL.java package com.zyl.util; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ToDDL { public static void main (String[] args) { Configuration configure= new Configuration(); configure.configure("hibernate.cfg.xml"); SchemaExport sc=new SchemaExport(configure); sc.create(true, true); } } ------------------------------------------------------------------------------------------- log4j.properties log4j.rootLogger=DEBUG,A1 log4j.appender.A1 = org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.TTCCLayout ------------------------------------------------------------------------------------------- junit测试 增删改查 hibernate连DB2 Zyl.java和Zyl.hbm.xml是由表ZYL是逆向工程生成的 DB Browser - 表(zyl) 右键 - Java src forder :/hibernateTest/src ,Java package:com.zyl.po - hibernate Reverse Engneering-选Create POJO和java data Object-Hibernate types 和 identity 表zylusers 是正向生成的表里有userid,username,userpassword,regDate <mapping resource="com/zyl/po/UsersPO.hbm.xml" /> HibernateSessionFactory.java 用myeclipse 自动生成hibernate 点项目名称--右键--MyEclipse--Add Hibernate Capabilities