不细说了直接上代码
代码中的注释可以参考Hibernate-学习笔记01
1、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"> <hibernate-configuration> <session-factory> <property name="connection.username">its</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="connection.password">its</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 配饰AnnotationConfiguration时使用的 --> <mapping class="com.scal.entity.Teacher"/> </session-factory> </hibernate-configuration>
2、log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=info #log4j.logger.org.hibernate=debug ### log HQL query parser activity #log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL #log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### ###log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=debug ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log transaction activity #log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
3、HibernateSessionFactory
package com.scal.entity; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.AnnotationConfiguration; 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 { /* 使用配置文件的获取config */ configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { try{ /* 使用注解的获取config */ configuration = new AnnotationConfiguration().configure(); sessionFactory = configuration.buildSessionFactory(); }catch (Exception es) { System.err.println("%%%% Error Creating SessionFactory %%%%"); es.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; } }
4、Teacher (基于注解的实体)
package com.scal.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Teacher implements Serializable{ private static final long serialVersionUID = 729474527745209202L; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TEACHER_SEQ") @SequenceGenerator(name="TEACHER_SEQ",allocationSize=1,initialValue=1, sequenceName="TEACHER_SEQ") private Long id; private String name; private String age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public static long getSerialVersionUID() { return serialVersionUID; } }
5、DoTest
package com.scal.run; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.scal.entity.HibernateSessionFactory; import com.scal.entity.Teacher; public class DoTest { public static void main(String[] args) { SessionFactory sf= HibernateSessionFactory.getSessionFactory(); Session session = sf.getCurrentSession(); Teacher teacher = new Teacher(); teacher.setAge("10"); teacher.setName("tom"); session.beginTransaction(); session.save(teacher); session.getTransaction().commit(); sf.close(); } }