因为工作的关系,最近需要在项目中使用 hibernate 实现持久层,从来没有用过 hibernate, 刚开始确实有些不好掌握。从网上查了不小的资料,确定选用hibernate 的版本为 3.3.1 GA。
hibernate 的包分为两部分,第一部分为运行所需的JAR包,还有一部分是生成代码所需的工具包。使用hibernate时,会根据数据库的结构,自动生成持久化的代码,这部分代码的生成,需要相关工具的支持。这就是为什么需要工具的原因。对于工具,有多种选择,可以根据不同情况,进行选择。一般情况下,可以使用 Hibernate Synchronizer,我们选用 HibernateSynchronizer-3.1.9,接下来,就是在 eclipse 中安装 hibernate 插件。
先做一个简单的例子:新找一个 java project, 并添加所需的 jar 包:
classes12.jar (Oracle 连接包)
hibernate3.jar
dom4j-1.6.1.jar (开源XML解析包)
slf4j-log4j12-1.5.2.jar (日志)
slf4j-api-1.5.2.jar (日志)
log4j-1.2.15.jar 日志记录包
jta-1.1.jar (JTA规范)
antlr-2.7.6.jar (语法分析生成器)
commons-collections-3.1.jar (json依赖包)
javassist-3.4.GA.jar (类文件操作器)
hibernate-testing.jar
另外,还要加上JUNIT 包。
做完以上的工作后,开发环境基本上就完成了。
接下来,首先添加一个 hibernate 的配置文件:hibernate.cfg.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-configuration
- PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory name="cdma">
- <!-- local connection properties -->
- <property name="hibernate.connection.url">
- jdbc:oracle:thin:@10.52.16.138:1521:oragxlu
- </property>
- <property name="hibernate.connection.driver_class">
- oracle.jdbc.driver.OracleDriver
- </property>
- <property name="hibernate.connection.username">cdmagis</property>
- <property name="hibernate.connection.password">cdmagis</property>
- <!-- property name="hibernate.connection.pool_size"></property -->
- <!-- dialect for Oracle (any version) -->
- <property name="dialect">
- org.hibernate.dialect.OracleDialect
- </property>
- <property name="hibernate.show_sql">false</property>
- <property name="hibernate.transaction.factory_class">
- org.hibernate.transaction.JDBCTransactionFactory
- </property>
- <mapping resource="CdmaBts.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
在这个文件中,定义了数据库的连接信息。另外,还可以定义连接池。
再添加一个 mapping 文件。
- <?xml version="1.0"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
- <hibernate-mapping package="test.src">
- <class
- name="test.src.CdmaBts"
- table="CDMA_BTS"
- >
- <meta attribute="sync-DAO">true</meta>
- <id
- name="Id"
- type="integer"
- column="ID"
- >
- <generator class="sequence"/>
- </id>
- <property
- name="Code"
- column="CODE"
- type="string"
- not-null="false"
- length="40"
- />
- <property
- name="Name"
- column="NAME"
- type="string"
- not-null="false"
- length="40"
- />
- <property
- name="Areaid"
- column="AREAID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Barnid"
- column="BARNID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Type"
- column="TYPE"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Factory"
- column="FACTORY"
- type="string"
- not-null="false"
- length="100"
- />
- <property
- name="Spec"
- column="SPEC"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Usebegintime"
- column="USEBEGINTIME"
- type="date"
- not-null="false"
- length="7"
- />
- <property
- name="Staff"
- column="STAFF"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Recordtime"
- column="RECORDTIME"
- type="date"
- not-null="false"
- length="7"
- />
- <property
- name="Property"
- column="PROPERTY"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="FixedCode"
- column="FIXED_CODE"
- type="string"
- not-null="false"
- length="40"
- />
- <property
- name="State"
- column="STATE"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="MaintenanceMode"
- column="MAINTENANCE_MODE"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Note"
- column="NOTE"
- type="string"
- not-null="false"
- length="300"
- />
- <property
- name="Zczt"
- column="ZCZT"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Local"
- column="LOCAL"
- type="string"
- not-null="false"
- length="100"
- />
- <property
- name="Whburden"
- column="WHBURDEN"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Stationid"
- column="STATIONID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Covertype"
- column="COVERTYPE"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Chaincount"
- column="CHAINCOUNT"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Shootcount"
- column="SHOOTCOUNT"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Mscid"
- column="MSCID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Bscid"
- column="BSCID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Towerid"
- column="TOWERID"
- type="integer"
- not-null="false"
- length="18"
- />
- <property
- name="Ifsurvey"
- column="IFSURVEY"
- type="integer"
- not-null="false"
- length="1"
- />
- <property
- name="Networdcode"
- column="NETWORDCODE"
- type="string"
- not-null="false"
- length="40"
- />
- <property
- name="Rated"
- column="RATED"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Maxshoot"
- column="MAXSHOOT"
- type="integer"
- not-null="false"
- length="12"
- />
- <property
- name="Maintenance"
- column="MAINTENANCE"
- type="string"
- not-null="false"
- length="40"
- />
- <property
- name="Aegisagreement"
- column="AEGISAGREEMENT"
- type="string"
- not-null="false"
- length="40"
- />
- </class>
- </hibernate-mapping>
这个文件,定义了DB表的信息,对应的创建表的SQL如下:
- create table CDMA_BTS
- (
- ID NUMBER(18) not null,
- CODE VARCHAR2(40),
- NAME VARCHAR2(40),
- AREAID NUMBER(18),
- BARNID NUMBER(18),
- TYPE NUMBER(18),
- FACTORY VARCHAR2(100),
- SPEC NUMBER(18),
- USEBEGINTIME DATE,
- STAFF NUMBER(12),
- RECORDTIME DATE,
- PROPERTY NUMBER(12),
- FIXED_CODE VARCHAR2(40),
- STATE NUMBER(12),
- MAINTENANCE_MODE NUMBER(12),
- NOTE VARCHAR2(300),
- ZCZT NUMBER(12),
- LOCAL VARCHAR2(100),
- WHBURDEN NUMBER(12),
- STATIONID NUMBER(18),
- COVERTYPE NUMBER(12),
- CHAINCOUNT NUMBER(12),
- SHOOTCOUNT NUMBER(12),
- MSCID NUMBER(18),
- BSCID NUMBER(18),
- TOWERID NUMBER(18),
- IFSURVEY NUMBER(1),
- NETWORDCODE VARCHAR2(40),
- RATED NUMBER(12),
- MAXSHOOT NUMBER(12),
- MAINTENANCE VARCHAR2(40),
- AEGISAGREEMENT VARCHAR2(40)
- );
然后再同步文件,会生成如下的文件:
- package test.src;
- import test.src.base.BaseCdmaBts;
- public class CdmaBts extends BaseCdmaBts {
- private static final long serialVersionUID = 1L;
- /*[CONSTRUCTOR MARKER BEGIN]*/
- public CdmaBts () {
- super();
- }
- /**
- * Constructor for primary key
- */
- public CdmaBts (java.lang.Integer id) {
- super(id);
- }
- /*[CONSTRUCTOR MARKER END]*/
- }
_BaseRootDAO.java:
- package test.src.base;
- import java.io.Serializable;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import org.hibernate.Criteria;
- import org.hibernate.HibernateException;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.criterion.Expression;
- import org.hibernate.criterion.Order;
- public abstract class _BaseRootDAO {
- public _BaseRootDAO () {}
- public _BaseRootDAO (Session session) {
- setSession(session);
- }
- protected static Map<String, SessionFactory> sessionFactoryMap;
- protected SessionFactory sessionFactory;
- protected Session session;
- protected final static ThreadLocal<Session> currentSession = new ThreadLocal<Session>();
- /**
- * Return a new Session object that must be closed when the work has been completed.
- * @return the active Session
- */
- public Session getSession() {
- return getSession(
- getConfigurationFileName());
- }
- /**
- * Return a new Session object that must be closed when the work has been completed.
- * @param configFile the config file must match the meta attribute "config-file" in the hibernate mapping file
- * @return the active Session
- */
- protected Session getSession(String configFile) {
- if (null != session && session.isOpen()) return session;
- else if (null != sessionFactory) {
- Session s = currentSession.get();
- if (null == s || !s.isOpen()) {
- s = sessionFactory.openSession();
- currentSession.set(s);
- }
- return s;
- }
- else {
- Session s = currentSession.get();
- if (null == s || !s.isOpen()) {
- s = getSessionFactory(configFile).openSession();
- currentSession.set(s);
- }
- return s;
- }
- }
- public void setSession (Session session) {
- this.session = session;
- }
- /**
- * Configure the session factory by reading hibernate config file
- */
- public static void initialize () {
- test.src.dao._RootDAO.initialize(
- (String) null);
- }
- /**
- * Configure the session factory by reading hibernate config file
- * @param configFileName the name of the configuration file
- */
- public static void initialize (String configFileName) {
- test.src.dao._RootDAO.initialize(
- configFileName,
- test.src.dao._RootDAO.getNewConfiguration(
- null));
- }
- public static void initialize (String configFileName, Configuration configuration) {
- if (null != sessionFactoryMap && null != sessionFactoryMap.get(configFileName)) return;
- else {
- if (null == configFileName) {
- configuration.configure();
- test.src.dao._RootDAO.setSessionFactory(
- null,
- configuration.buildSessionFactory());
- }
- else {
- configuration.configure(
- configFileName);
- test.src.dao._RootDAO.setSessionFactory(
- configFileName,
- configuration.buildSessionFactory());
- }
- }
- }
- /**
- * Set the session factory
- */
- public void setSessionFactory (SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- /**
- * Set the session factory
- */
- protected static void setSessionFactory (String configFileName, SessionFactory sf) {
- if (null == configFileName) configFileName = "";
- if (null == sessionFactoryMap) sessionFactoryMap = new HashMap<String, SessionFactory>();
- sessionFactoryMap.put(
- configFileName,
- sf);
- }
- /**
- * Return the SessionFactory that is to be used by these DAOs. Change this
- * and implement your own strategy if you, for example, want to pull the SessionFactory
- * from the JNDI tree.
- */
- public SessionFactory getSessionFactory() {
- if (null != sessionFactory) return sessionFactory;
- else return getSessionFactory(
- getConfigurationFileName());
- }
- public SessionFactory getSessionFactory(String configFileName) {
- if (null == configFileName) configFileName = "";
- if (null == sessionFactoryMap)
- initialize(configFileName);
- SessionFactory sf = (SessionFactory) sessionFactoryMap.get(configFileName);
- if (null == sf)
- throw new RuntimeException("The session factory for '" + configFileName + "' has not been initialized (or an error occured during initialization)");
- else
- return sf;
- }
- /**
- * Close all sessions for the current thread
- */
- public static void closeCurrentSession () {
- Session s = currentSession.get();
- if (null != s) {
- if (s.isOpen()) s.close();
- currentSession.set(null);
- }
- }
- /**
- * Close the session
- */
- public void closeSession (Session session) {
- if (null != session) session.close();
- }
- /**
- * Begin the transaction related to the session
- */
- public Transaction beginTransaction(Session s) {
- return s.beginTransaction();
- }
- /**
- * Commit the given transaction
- */
- public void commitTransaction(Transaction t) {
- t.commit();
- }
- /**
- * Return a new Configuration to use. This is not a mistake and is meant
- * to be overridden in the RootDAO if you want to do something different.
- * The file name is passed in so you have that to access. The config file
- * is read in the initialize method.
- */
- public static Configuration getNewConfiguration (String configFileName) {
- return new Configuration();
- }
- /**
- * Return the name of the configuration file to be used with this DAO or null if default
- */
- public String getConfigurationFileName () {
- return null;
- }
- /**
- * Return the specific Object class that will be used for class-specific
- * implementation of this DAO.
- * @return the reference Class
- */
- protected abstract Class getReferenceClass();
- /**
- * Used by the base DAO classes but here for your modification
- * Get object matching the given key and return it.
- */
- protected Object get(Class refClass, Serializable key) {
- Session s = null;
- try {
- s = getSession();
- return get(refClass, key, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Get object matching the given key and return it.
- */
- protected Object get(Class refClass, Serializable key, Session s) {
- return s.get(refClass, key);
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Load object matching the given key and return it.
- */
- protected Object load(Class refClass, Serializable key) {
- Session s = null;
- try {
- s = getSession();
- return load(refClass, key, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Load object matching the given key and return it.
- */
- protected Object load(Class refClass, Serializable key, Session s) {
- return s.load(refClass, key);
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- */
- public java.util.List findAll () {
- Session s = null;
- try {
- s = getSession();
- return findAll(s);
- }
- finally {
- closeSession(s);
- }
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- * Use the session given.
- * @param s the Session
- */
- public java.util.List findAll (Session s) {
- return findAll(s, getDefaultOrder());
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- */
- public java.util.List findAll (Order defaultOrder) {
- Session s = null;
- try {
- s = getSession();
- return findAll(s, defaultOrder);
- }
- finally {
- closeSession(s);
- }
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- * Use the session given.
- * @param s the Session
- */
- public java.util.List findAll (Session s, Order defaultOrder) {
- Criteria crit = s.createCriteria(getReferenceClass());
- if (null != defaultOrder) crit.addOrder(defaultOrder);
- return crit.list();
- }
- /**
- * Return all objects related to the implementation of this DAO with a filter.
- * Use the session given.
- * @param propName the name of the property to use for filtering
- * @param filter the value of the filter
- */
- protected Criteria findFiltered (String propName, Object filter) {
- return findFiltered(propName, filter, getDefaultOrder());
- }
- /**
- * Return all objects related to the implementation of this DAO with a filter.
- * Use the session given.
- * @param propName the name of the property to use for filtering
- * @param filter the value of the filter
- * @param orderProperty the name of the property used for ordering
- */
- protected Criteria findFiltered (String propName, Object filter, Order order) {
- Session s = null;
- try {
- s = getSession();
- return findFiltered(s, propName, filter, order);
- }
- finally {
- closeSession(s);
- }
- }
- /**
- * Return all objects related to the implementation of this DAO with a filter.
- * Use the session given.
- * @param s the Session
- * @param propName the name of the property to use for filtering
- * @param filter the value of the filter
- * @param orderProperty the name of the property used for ordering
- */
- protected Criteria findFiltered (Session s, String propName, Object filter, Order order) {
- Criteria crit = s.createCriteria(getReferenceClass());
- crit.add(Expression.eq(propName, filter));
- if (null != order) crit.addOrder(order);
- return crit;
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * @param name the name of a query defined externally
- * @return Query
- */
- protected Query getNamedQuery(String name) {
- Session s = null;
- try {
- s = getSession();
- return getNamedQuery(name, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the session given.
- * @param name the name of a query defined externally
- * @param s the Session
- * @return Query
- */
- protected Query getNamedQuery(String name, Session s) {
- Query q = s.getNamedQuery(name);
- return q;
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * @param name the name of a query defined externally
- * @param param the first parameter to set
- * @return Query
- */
- protected Query getNamedQuery(String name, Serializable param) {
- Session s = null;
- try {
- s = getSession();
- return getNamedQuery(name, param, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the session given.
- * @param name the name of a query defined externally
- * @param param the first parameter to set
- * @param s the Session
- * @return Query
- */
- protected Query getNamedQuery(String name, Serializable param, Session s) {
- Query q = s.getNamedQuery(name);
- q.setParameter(0, param);
- return q;
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given.
- * @param name the name of a query defined externally
- * @param params the parameter array
- * @return Query
- */
- protected Query getNamedQuery(String name, Serializable[] params) {
- Session s = null;
- try {
- s = getSession();
- return getNamedQuery(name, params, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given and the Session given.
- * @param name the name of a query defined externally
- * @param params the parameter array
- * @s the Session
- * @return Query
- */
- protected Query getNamedQuery(String name, Serializable[] params, Session s) {
- Query q = s.getNamedQuery(name);
- if (null != params) {
- for (int i = 0; i < params.length; i++) {
- q.setParameter(i, params[i]);
- }
- }
- return q;
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given.
- * @param name the name of a query defined externally
- * @param params the parameter Map
- * @return Query
- */
- protected Query getNamedQuery(String name, Map params) {
- Session s = null;
- try {
- s = getSession();
- return getNamedQuery(name, params, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given and the Session given.
- * @param name the name of a query defined externally
- * @param params the parameter Map
- * @s the Session
- * @return Query
- */
- protected Query getNamedQuery(String name, Map params, Session s) {
- Query q = s.getNamedQuery(name);
- if (null != params) {
- for (Iterator i=params.entrySet().iterator(); i.hasNext(); ) {
- Map.Entry entry = (Map.Entry) i.next();
- q.setParameter((String) entry.getKey(), entry.getValue());
- }
- }
- return q;
- }
- /**
- * Execute a query.
- * @param queryStr a query expressed in Hibernate's query language
- * @return a distinct list of instances (or arrays of instances)
- */
- public Query getQuery(String queryStr) {
- Session s = null;
- try {
- s = getSession();
- return getQuery(queryStr, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Execute a query but use the session given instead of creating a new one.
- * @param queryStr a query expressed in Hibernate's query language
- * @s the Session to use
- */
- public Query getQuery(String queryStr, Session s) {
- return s.createQuery(queryStr);
- }
- /**
- * Execute a query.
- * @param query a query expressed in Hibernate's query language
- * @param queryStr the name of a query defined externally
- * @param param the first parameter to set
- * @return Query
- */
- protected Query getQuery(String queryStr, Serializable param) {
- Session s = null;
- try {
- s = getSession();
- return getQuery(queryStr, param, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Execute a query but use the session given instead of creating a new one.
- * @param queryStr a query expressed in Hibernate's query language
- * @param param the first parameter to set
- * @s the Session to use
- * @return Query
- */
- protected Query getQuery(String queryStr, Serializable param, Session s) {
- Query q = getQuery(queryStr, s);
- q.setParameter(0, param);
- return q;
- }
- /**
- * Execute a query.
- * @param queryStr a query expressed in Hibernate's query language
- * @param params the parameter array
- * @return Query
- */
- protected Query getQuery(String queryStr, Serializable[] params) {
- Session s = null;
- try {
- s = getSession();
- return getQuery(queryStr, params, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Execute a query but use the session given instead of creating a new one.
- * @param queryStr a query expressed in Hibernate's query language
- * @param params the parameter array
- * @s the Session
- * @return Query
- */
- protected Query getQuery(String queryStr, Serializable[] params, Session s) {
- Query q = getQuery(queryStr, s);
- if (null != params) {
- for (int i = 0; i < params.length; i++) {
- q.setParameter(i, params[i]);
- }
- }
- return q;
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given.
- * @param queryStr a query expressed in Hibernate's query language
- * @param params the parameter Map
- * @return Query
- */
- protected Query getQuery(String queryStr, Map params) {
- Session s = null;
- try {
- s = getSession();
- return getQuery(queryStr, params, s);
- } finally {
- closeSession(s);
- }
- }
- /**
- * Obtain an instance of Query for a named query string defined in the mapping file.
- * Use the parameters given and the Session given.
- * @param queryStr a query expressed in Hibernate's query language
- * @param params the parameter Map
- * @s the Session
- * @return Query
- */
- protected Query getQuery(String queryStr, Map params, Session s) {
- Query q = getQuery(queryStr, s);
- if (null != params) {
- for (Iterator i=params.entrySet().iterator(); i.hasNext(); ) {
- Map.Entry entry = (Map.Entry) i.next();
- q.setParameter((String) entry.getKey(), entry.getValue());
- }
- }
- return q;
- }
- protected Order getDefaultOrder () {
- return null;
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Persist the given transient instance, first assigning a generated identifier.
- * (Or using the current value of the identifier property if the assigned generator is used.)
- */
- protected Serializable save(final Object obj) {
- return (Serializable) run (
- new TransactionRunnable () {
- public Object run (Session s) {
- return save(obj, s);
- }
- });
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Persist the given transient instance, first assigning a generated identifier.
- * (Or using the current value of the identifier property if the assigned generator is used.)
- */
- protected Serializable save(Object obj, Session s) {
- return s.save(obj);
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Either save() or update() the given instance, depending upon the value of its
- * identifier property.
- */
- protected void saveOrUpdate(final Object obj) {
- run (
- new TransactionRunnable () {
- public Object run (Session s) {
- saveOrUpdate(obj, s);
- return null;
- }
- });
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Either save() or update() the given instance, depending upon the value of its
- * identifier property.
- */
- protected void saveOrUpdate(Object obj, Session s) {
- s.saveOrUpdate(obj);
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param obj a transient instance containing updated state
- */
- protected void update(final Object obj) {
- run (
- new TransactionRunnable () {
- public Object run (Session s) {
- update(obj, s);
- return null;
- }
- });
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param obj a transient instance containing updated state
- * @param s the Session
- */
- protected void update(Object obj, Session s) {
- s.update(obj);
- }
- /**
- * Delete all objects returned by the query
- */
- protected int delete (final Query query) {
- Integer rtn = (Integer) run (
- new TransactionRunnable () {
- public Object run (Session s) {
- return new Integer(delete((Query) query, s));
- }
- });
- return rtn.intValue();
- }
- /**
- * Delete all objects returned by the query
- */
- protected int delete (Query query, Session s) {
- List list = query.list();
- for (Iterator i=list.iterator(); i.hasNext(); ) {
- delete(i.next(), s);
- }
- return list.size();
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- */
- protected void delete(final Object obj) {
- run (
- new TransactionRunnable () {
- public Object run (Session s) {
- delete(obj, s);
- return null;
- }
- });
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- */
- protected void delete(Object obj, Session s) {
- s.delete(obj);
- }
- /**
- * Used by the base DAO classes but here for your modification
- * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
- * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
- */
- protected void refresh(Object obj, Session s) {
- s.refresh(obj);
- }
- protected void throwException (Throwable t) {
- if (t instanceof HibernateException) throw (HibernateException) t;
- else if (t instanceof RuntimeException) throw (RuntimeException) t;
- else throw new HibernateException(t);
- }
- /**
- * Execute the given transaction runnable.
- */
- protected Object run (TransactionRunnable transactionRunnable) {
- Transaction t = null;
- Session s = null;
- try {
- s = getSession();
- t = beginTransaction(s);
- Object obj = transactionRunnable.run(s);
- commitTransaction(t);
- return obj;
- }
- catch (Throwable throwable) {
- if (null != t) {
- try {
- t.rollback();
- }
- catch (HibernateException e) {handleError(e);}
- }
- if (transactionRunnable instanceof TransactionFailHandler) {
- try {
- ((TransactionFailHandler) transactionRunnable).onFail(s);
- }
- catch (Throwable e) {handleError(e);}
- }
- throwException(throwable);
- return null;
- }
- finally {
- closeSession(s);
- }
- }
- /**
- * Execute the given transaction runnable.
- */
- protected TransactionPointer runAsnyc (TransactionRunnable transactionRunnable) {
- final TransactionPointer transactionPointer = new TransactionPointer(transactionRunnable);
- ThreadRunner threadRunner = new ThreadRunner(transactionPointer);
- threadRunner.start();
- return transactionPointer;
- }
- /**
- * This class can be used to encapsulate logic used for a single transaction.
- */
- public abstract class TransactionRunnable {
- public abstract Object run (Session s) throws Exception;
- }
- /**
- * This class can be used to handle any error that has occured during a transaction
- */
- public interface TransactionFailHandler {
- public void onFail (Session s);
- }
- /**
- * This class can be used to handle failed transactions
- */
- public abstract class TransactionRunnableFailHandler extends TransactionRunnable implements TransactionFailHandler {
- }
- public class TransactionPointer {
- private TransactionRunnable transactionRunnable;
- private Throwable thrownException;
- private Object returnValue;
- private boolean hasCompleted = false;
- public TransactionPointer (TransactionRunnable transactionRunnable) {
- this.transactionRunnable = transactionRunnable;
- }
- public boolean hasCompleted() {
- return hasCompleted;
- }
- public void complete() {
- this.hasCompleted = true;
- }
- public Object getReturnValue() {
- return returnValue;
- }
- public void setReturnValue(Object returnValue) {
- this.returnValue = returnValue;
- }
- public Throwable getThrownException() {
- return thrownException;
- }
- public void setThrownException(Throwable thrownException) {
- this.thrownException = thrownException;
- }
- public TransactionRunnable getTransactionRunnable() {
- return transactionRunnable;
- }
- public void setTransactionRunnable(TransactionRunnable transactionRunnable) {
- this.transactionRunnable = transactionRunnable;
- }
- /**
- * Wait until the transaction completes and return the value returned from the run method of the TransactionRunnable.
- * If the transaction throws an Exception, throw that Exception.
- * @param timeout the timeout in milliseconds (or 0 for no timeout)
- * @return the return value from the TransactionRunnable
- * @throws TimeLimitExcededException if the timeout has been reached before transaction completion
- * @throws Throwable the thrown Throwable
- */
- public Object waitUntilFinish (long timeout) throws Throwable {
- long killTime = -1;
- if (timeout > 0) killTime = System.currentTimeMillis() + timeout;
- do {
- try {
- Thread.sleep(50);
- }
- catch (InterruptedException e) {}
- }
- while (!hasCompleted && ((killTime > 0 && System.currentTimeMillis() < killTime) || killTime <= 0));
- if (!hasCompleted) throw new javax.naming.TimeLimitExceededException();
- if (null != thrownException) throw thrownException;
- else return returnValue;
- }
- }
- private class ThreadRunner extends Thread {
- private TransactionPointer transactionPointer;
- public ThreadRunner (TransactionPointer transactionPointer) {
- this.transactionPointer = transactionPointer;
- }
- public void run () {
- Transaction t = null;
- Session s = null;
- try {
- s = getSession();
- t = beginTransaction(s);
- Object obj = transactionPointer.getTransactionRunnable().run(s);
- t.commit();
- transactionPointer.setReturnValue(obj);
- }
- catch (Throwable throwable) {
- if (null != t) {
- try {
- t.rollback();
- }
- catch (HibernateException e) {handleError(e);}
- }
- if (transactionPointer.getTransactionRunnable() instanceof TransactionFailHandler) {
- try {
- ((TransactionFailHandler) transactionPointer.getTransactionRunnable()).onFail(s);
- }
- catch (Throwable e) {handleError(e);}
- }
- transactionPointer.setThrownException(throwable);
- }
- finally {
- transactionPointer.complete();
- try {
- closeSession(s);
- }
- catch (HibernateException e) {
- transactionPointer.setThrownException(e);
- }
- }
- }
- }
- protected void handleError (Throwable t) {
- }
- }
BaseCdmaBts.java
- package test.src.base;
- import java.io.Serializable;
- /**
- * This is an object that contains data related to the CDMA_BTS table.
- * Do not modify this class because it will be overwritten if the configuration file
- * related to this class is modified.
- *
- * @hibernate.class
- * table="CDMA_BTS"
- */
- public abstract class BaseCdmaBts implements Serializable {
- public static String REF = "CdmaBts";
- public static String PROP_RATED = "Rated";
- public static String PROP_TYPE = "Type";
- public static String PROP_PROPERTY = "Property";
- public static String PROP_LOCAL = "Local";
- public static String PROP_SPEC = "Spec";
- public static String PROP_USEBEGINTIME = "Usebegintime";
- public static String PROP_AREAID = "Areaid";
- public static String PROP_IFSURVEY = "Ifsurvey";
- public static String PROP_RECORDTIME = "Recordtime";
- public static String PROP_TOWERID = "Towerid";
- public static String PROP_FIXED_CODE = "FixedCode";
- public static String PROP_CHAINCOUNT = "Chaincount";
- public static String PROP_MAINTENANCE_MODE = "MaintenanceMode";
- public static String PROP_BSCID = "Bscid";
- public static String PROP_NETWORDCODE = "Networdcode";
- public static String PROP_STAFF = "Staff";
- public static String PROP_FACTORY = "Factory";
- public static String PROP_SHOOTCOUNT = "Shootcount";
- public static String PROP_ZCZT = "Zczt";
- public static String PROP_CODE = "Code";
- public static String PROP_COVERTYPE = "Covertype";
- public static String PROP_NOTE = "Note";
- public static String PROP_NAME = "Name";
- public static String PROP_MAXSHOOT = "Maxshoot";
- public static String PROP_BARNID = "Barnid";
- public static String PROP_MSCID = "Mscid";
- public static String PROP_STATE = "State";
- public static String PROP_AEGISAGREEMENT = "Aegisagreement";
- public static String PROP_MAINTENANCE = "Maintenance";
- public static String PROP_STATIONID = "Stationid";
- public static String PROP_WHBURDEN = "Whburden";
- public static String PROP_ID = "Id";
- // constructors
- public BaseCdmaBts () {
- initialize();
- }
- /**
- * Constructor for primary key
- */
- public BaseCdmaBts (java.lang.Integer id) {
- this.setId(id);
- initialize();
- }
- protected void initialize () {}
- private int hashCode = Integer.MIN_VALUE;
- // primary key
- private java.lang.Integer id;
- // fields
- private java.lang.String code;
- private java.lang.String name;
- private java.lang.Integer areaid;
- private java.lang.Integer barnid;
- private java.lang.Integer type;
- private java.lang.String factory;
- private java.lang.Integer spec;
- private java.util.Date usebegintime;
- private java.lang.Integer staff;
- private java.util.Date recordtime;
- private java.lang.Integer property;
- private java.lang.String fixedCode;
- private java.lang.Integer state;
- private java.lang.Integer maintenanceMode;
- private java.lang.String note;
- private java.lang.Integer zczt;
- private java.lang.String local;
- private java.lang.Integer whburden;
- private java.lang.Integer stationid;
- private java.lang.Integer covertype;
- private java.lang.Integer chaincount;
- private java.lang.Integer shootcount;
- private java.lang.Integer mscid;
- private java.lang.Integer bscid;
- private java.lang.Integer towerid;
- private java.lang.Integer ifsurvey;
- private java.lang.String networdcode;
- private java.lang.Integer rated;
- private java.lang.Integer maxshoot;
- private java.lang.String maintenance;
- private java.lang.String aegisagreement;
- /**
- * Return the unique identifier of this class
- * @hibernate.id
- * generator-class="sequence"
- * column="ID"
- */
- public java.lang.Integer getId () {
- return id;
- }
- /**
- * Set the unique identifier of this class
- * @param id the new ID
- */
- public void setId (java.lang.Integer id) {
- this.id = id;
- this.hashCode = Integer.MIN_VALUE;
- }
- /**
- * Return the value associated with the column: CODE
- */
- public java.lang.String getCode () {
- return code;
- }
- /**
- * Set the value related to the column: CODE
- * @param code the CODE value
- */
- public void setCode (java.lang.String code) {
- this.code = code;
- }
- /**
- * Return the value associated with the column: NAME
- */
- public java.lang.String getName () {
- return name;
- }
- /**
- * Set the value related to the column: NAME
- * @param name the NAME value
- */
- public void setName (java.lang.String name) {
- this.name = name;
- }
- /**
- * Return the value associated with the column: AREAID
- */
- public java.lang.Integer getAreaid () {
- return areaid;
- }
- /**
- * Set the value related to the column: AREAID
- * @param areaid the AREAID value
- */
- public void setAreaid (java.lang.Integer areaid) {
- this.areaid = areaid;
- }
- /**
- * Return the value associated with the column: BARNID
- */
- public java.lang.Integer getBarnid () {
- return barnid;
- }
- /**
- * Set the value related to the column: BARNID
- * @param barnid the BARNID value
- */
- public void setBarnid (java.lang.Integer barnid) {
- this.barnid = barnid;
- }
- /**
- * Return the value associated with the column: TYPE
- */
- public java.lang.Integer getType () {
- return type;
- }
- /**
- * Set the value related to the column: TYPE
- * @param type the TYPE value
- */
- public void setType (java.lang.Integer type) {
- this.type = type;
- }
- /**
- * Return the value associated with the column: FACTORY
- */
- public java.lang.String getFactory () {
- return factory;
- }
- /**
- * Set the value related to the column: FACTORY
- * @param factory the FACTORY value
- */
- public void setFactory (java.lang.String factory) {
- this.factory = factory;
- }
- /**
- * Return the value associated with the column: SPEC
- */
- public java.lang.Integer getSpec () {
- return spec;
- }
- /**
- * Set the value related to the column: SPEC
- * @param spec the SPEC value
- */
- public void setSpec (java.lang.Integer spec) {
- this.spec = spec;
- }
- /**
- * Return the value associated with the column: USEBEGINTIME
- */
- public java.util.Date getUsebegintime () {
- return usebegintime;
- }
- /**
- * Set the value related to the column: USEBEGINTIME
- * @param usebegintime the USEBEGINTIME value
- */
- public void setUsebegintime (java.util.Date usebegintime) {
- this.usebegintime = usebegintime;
- }
- /**
- * Return the value associated with the column: STAFF
- */
- public java.lang.Integer getStaff () {
- return staff;
- }
- /**
- * Set the value related to the column: STAFF
- * @param staff the STAFF value
- */
- public void setStaff (java.lang.Integer staff) {
- this.staff = staff;
- }
- /**
- * Return the value associated with the column: RECORDTIME
- */
- public java.util.Date getRecordtime () {
- return recordtime;
- }
- /**
- * Set the value related to the column: RECORDTIME
- * @param recordtime the RECORDTIME value
- */
- public void setRecordtime (java.util.Date recordtime) {
- this.recordtime = recordtime;
- }
- /**
- * Return the value associated with the column: PROPERTY
- */
- public java.lang.Integer getProperty () {
- return property;
- }
- /**
- * Set the value related to the column: PROPERTY
- * @param property the PROPERTY value
- */
- public void setProperty (java.lang.Integer property) {
- this.property = property;
- }
- /**
- * Return the value associated with the column: FIXED_CODE
- */
- public java.lang.String getFixedCode () {
- return fixedCode;
- }
- /**
- * Set the value related to the column: FIXED_CODE
- * @param fixedCode the FIXED_CODE value
- */
- public void setFixedCode (java.lang.String fixedCode) {
- this.fixedCode = fixedCode;
- }
- /**
- * Return the value associated with the column: STATE
- */
- public java.lang.Integer getState () {
- return state;
- }
- /**
- * Set the value related to the column: STATE
- * @param state the STATE value
- */
- public void setState (java.lang.Integer state) {
- this.state = state;
- }
- /**
- * Return the value associated with the column: MAINTENANCE_MODE
- */
- public java.lang.Integer getMaintenanceMode () {
- return maintenanceMode;
- }
- /**
- * Set the value related to the column: MAINTENANCE_MODE
- * @param maintenanceMode the MAINTENANCE_MODE value
- */
- public void setMaintenanceMode (java.lang.Integer maintenanceMode) {
- this.maintenanceMode = maintenanceMode;
- }
- /**
- * Return the value associated with the column: NOTE
- */
- public java.lang.String getNote () {
- return note;
- }
- /**
- * Set the value related to the column: NOTE
- * @param note the NOTE value
- */
- public void setNote (java.lang.String note) {
- this.note = note;
- }
- /**
- * Return the value associated with the column: ZCZT
- */
- public java.lang.Integer getZczt () {
- return zczt;
- }
- /**
- * Set the value related to the column: ZCZT
- * @param zczt the ZCZT value
- */
- public void setZczt (java.lang.Integer zczt) {
- this.zczt = zczt;
- }
- /**
- * Return the value associated with the column: LOCAL
- */
- public java.lang.String getLocal () {
- return local;
- }
- /**
- * Set the value related to the column: LOCAL
- * @param local the LOCAL value
- */
- public void setLocal (java.lang.String local) {
- this.local = local;
- }
- /**
- * Return the value associated with the column: WHBURDEN
- */
- public java.lang.Integer getWhburden () {
- return whburden;
- }
- /**
- * Set the value related to the column: WHBURDEN
- * @param whburden the WHBURDEN value
- */
- public void setWhburden (java.lang.Integer whburden) {
- this.whburden = whburden;
- }
- /**
- * Return the value associated with the column: STATIONID
- */
- public java.lang.Integer getStationid () {
- return stationid;
- }
- /**
- * Set the value related to the column: STATIONID
- * @param stationid the STATIONID value
- */
- public void setStationid (java.lang.Integer stationid) {
- this.stationid = stationid;
- }
- /**
- * Return the value associated with the column: COVERTYPE
- */
- public java.lang.Integer getCovertype () {
- return covertype;
- }
- /**
- * Set the value related to the column: COVERTYPE
- * @param covertype the COVERTYPE value
- */
- public void setCovertype (java.lang.Integer covertype) {
- this.covertype = covertype;
- }
- /**
- * Return the value associated with the column: CHAINCOUNT
- */
- public java.lang.Integer getChaincount () {
- return chaincount;
- }
- /**
- * Set the value related to the column: CHAINCOUNT
- * @param chaincount the CHAINCOUNT value
- */
- public void setChaincount (java.lang.Integer chaincount) {
- this.chaincount = chaincount;
- }
- /**
- * Return the value associated with the column: SHOOTCOUNT
- */
- public java.lang.Integer getShootcount () {
- return shootcount;
- }
- /**
- * Set the value related to the column: SHOOTCOUNT
- * @param shootcount the SHOOTCOUNT value
- */
- public void setShootcount (java.lang.Integer shootcount) {
- this.shootcount = shootcount;
- }
- /**
- * Return the value associated with the column: MSCID
- */
- public java.lang.Integer getMscid () {
- return mscid;
- }
- /**
- * Set the value related to the column: MSCID
- * @param mscid the MSCID value
- */
- public void setMscid (java.lang.Integer mscid) {
- this.mscid = mscid;
- }
- /**
- * Return the value associated with the column: BSCID
- */
- public java.lang.Integer getBscid () {
- return bscid;
- }
- /**
- * Set the value related to the column: BSCID
- * @param bscid the BSCID value
- */
- public void setBscid (java.lang.Integer bscid) {
- this.bscid = bscid;
- }
- /**
- * Return the value associated with the column: TOWERID
- */
- public java.lang.Integer getTowerid () {
- return towerid;
- }
- /**
- * Set the value related to the column: TOWERID
- * @param towerid the TOWERID value
- */
- public void setTowerid (java.lang.Integer towerid) {
- this.towerid = towerid;
- }
- /**
- * Return the value associated with the column: IFSURVEY
- */
- public java.lang.Integer getIfsurvey () {
- return ifsurvey;
- }
- /**
- * Set the value related to the column: IFSURVEY
- * @param ifsurvey the IFSURVEY value
- */
- public void setIfsurvey (java.lang.Integer ifsurvey) {
- this.ifsurvey = ifsurvey;
- }
- /**
- * Return the value associated with the column: NETWORDCODE
- */
- public java.lang.String getNetwordcode () {
- return networdcode;
- }
- /**
- * Set the value related to the column: NETWORDCODE
- * @param networdcode the NETWORDCODE value
- */
- public void setNetwordcode (java.lang.String networdcode) {
- this.networdcode = networdcode;
- }
- /**
- * Return the value associated with the column: RATED
- */
- public java.lang.Integer getRated () {
- return rated;
- }
- /**
- * Set the value related to the column: RATED
- * @param rated the RATED value
- */
- public void setRated (java.lang.Integer rated) {
- this.rated = rated;
- }
- /**
- * Return the value associated with the column: MAXSHOOT
- */
- public java.lang.Integer getMaxshoot () {
- return maxshoot;
- }
- /**
- * Set the value related to the column: MAXSHOOT
- * @param maxshoot the MAXSHOOT value
- */
- public void setMaxshoot (java.lang.Integer maxshoot) {
- this.maxshoot = maxshoot;
- }
- /**
- * Return the value associated with the column: MAINTENANCE
- */
- public java.lang.String getMaintenance () {
- return maintenance;
- }
- /**
- * Set the value related to the column: MAINTENANCE
- * @param maintenance the MAINTENANCE value
- */
- public void setMaintenance (java.lang.String maintenance) {
- this.maintenance = maintenance;
- }
- /**
- * Return the value associated with the column: AEGISAGREEMENT
- */
- public java.lang.String getAegisagreement () {
- return aegisagreement;
- }
- /**
- * Set the value related to the column: AEGISAGREEMENT
- * @param aegisagreement the AEGISAGREEMENT value
- */
- public void setAegisagreement (java.lang.String aegisagreement) {
- this.aegisagreement = aegisagreement;
- }
- public boolean equals (Object obj) {
- if (null == obj) return false;
- if (!(obj instanceof test.src.CdmaBts)) return false;
- else {
- test.src.CdmaBts cdmaBts = (test.src.CdmaBts) obj;
- if (null == this.getId() || null == cdmaBts.getId()) return false;
- else return (this.getId().equals(cdmaBts.getId()));
- }
- }
- public int hashCode () {
- if (Integer.MIN_VALUE == this.hashCode) {
- if (null == this.getId()) return super.hashCode();
- else {
- String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
- this.hashCode = hashStr.hashCode();
- }
- }
- return this.hashCode;
- }
- public String toString () {
- return super.toString();
- }
- }
BaseCdmaBtsDAO.java
- package test.src.base;
- import org.hibernate.Hibernate;
- import org.hibernate.Session;
- import test.src.dao.iface.CdmaBtsDAO;
- import org.hibernate.criterion.Order;
- /**
- * This is an automatically generated DAO class which should not be edited.
- */
- public abstract class BaseCdmaBtsDAO extends test.src.dao._RootDAO {
- public BaseCdmaBtsDAO () {}
- public BaseCdmaBtsDAO (Session session) {
- super(session);
- }
- // query name references
- public static CdmaBtsDAO instance;
- /**
- * Return a singleton of the DAO
- */
- public static CdmaBtsDAO getInstance () {
- if (null == instance) instance = new test.src.dao.CdmaBtsDAO();
- return instance;
- }
- public Class getReferenceClass () {
- return test.src.CdmaBts.class;
- }
- public Order getDefaultOrder () {
- return Order.asc("Name");
- }
- /**
- * Cast the object as a test.src.CdmaBts
- */
- public test.src.CdmaBts cast (Object object) {
- return (test.src.CdmaBts) object;
- }
- public test.src.CdmaBts get(java.lang.Integer key)
- {
- return (test.src.CdmaBts) get(getReferenceClass(), key);
- }
- public test.src.CdmaBts get(java.lang.Integer key, Session s)
- {
- return (test.src.CdmaBts) get(getReferenceClass(), key, s);
- }
- public test.src.CdmaBts load(java.lang.Integer key)
- {
- return (test.src.CdmaBts) load(getReferenceClass(), key);
- }
- public test.src.CdmaBts load(java.lang.Integer key, Session s)
- {
- return (test.src.CdmaBts) load(getReferenceClass(), key, s);
- }
- public test.src.CdmaBts loadInitialize(java.lang.Integer key, Session s)
- {
- test.src.CdmaBts obj = load(key, s);
- if (!Hibernate.isInitialized(obj)) {
- Hibernate.initialize(obj);
- }
- return obj;
- }
- /* Generic methods */
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- */
- public java.util.List<test.src.CdmaBts> findAll () {
- return super.findAll();
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- */
- public java.util.List<test.src.CdmaBts> findAll (Order defaultOrder) {
- return super.findAll(defaultOrder);
- }
- /**
- * Return all objects related to the implementation of this DAO with no filter.
- * Use the session given.
- * @param s the Session
- */
- public java.util.List<test.src.CdmaBts> findAll (Session s, Order defaultOrder) {
- return super.findAll(s, defaultOrder);
- }
- /**
- * Persist the given transient instance, first assigning a generated identifier. (Or using the current value
- * of the identifier property if the assigned generator is used.)
- * @param cdmaBts a transient instance of a persistent class
- * @return the class identifier
- */
- public java.lang.Integer save(test.src.CdmaBts cdmaBts)
- {
- return (java.lang.Integer) super.save(cdmaBts);
- }
- /**
- * Persist the given transient instance, first assigning a generated identifier. (Or using the current value
- * of the identifier property if the assigned generator is used.)
- * Use the Session given.
- * @param cdmaBts a transient instance of a persistent class
- * @param s the Session
- * @return the class identifier
- */
- public java.lang.Integer save(test.src.CdmaBts cdmaBts, Session s)
- {
- return (java.lang.Integer) save((Object) cdmaBts, s);
- }
- /**
- * Either save() or update() the given instance, depending upon the value of its identifier property. By default
- * the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the
- * identifier property mapping.
- * @param cdmaBts a transient instance containing new or updated state
- */
- public void saveOrUpdate(test.src.CdmaBts cdmaBts)
- {
- saveOrUpdate((Object) cdmaBts);
- }
- /**
- * Either save() or update() the given instance, depending upon the value of its identifier property. By default the
- * instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the identifier
- * property mapping.
- * Use the Session given.
- * @param cdmaBts a transient instance containing new or updated state.
- * @param s the Session.
- */
- public void saveOrUpdate(test.src.CdmaBts cdmaBts, Session s)
- {
- saveOrUpdate((Object) cdmaBts, s);
- }
- /**
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param cdmaBts a transient instance containing updated state
- */
- public void update(test.src.CdmaBts cdmaBts)
- {
- update((Object) cdmaBts);
- }
- /**
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * Use the Session given.
- * @param cdmaBts a transient instance containing updated state
- * @param the Session
- */
- public void update(test.src.CdmaBts cdmaBts, Session s)
- {
- update((Object) cdmaBts, s);
- }
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * @param id the instance ID to be removed
- */
- public void delete(java.lang.Integer id)
- {
- delete((Object) load(id));
- }
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * Use the Session given.
- * @param id the instance ID to be removed
- * @param s the Session
- */
- public void delete(java.lang.Integer id, Session s)
- {
- delete((Object) load(id, s), s);
- }
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * @param cdmaBts the instance to be removed
- */
- public void delete(test.src.CdmaBts cdmaBts)
- {
- delete((Object) cdmaBts);
- }
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * Use the Session given.
- * @param cdmaBts the instance to be removed
- * @param s the Session
- */
- public void delete(test.src.CdmaBts cdmaBts, Session s)
- {
- delete((Object) cdmaBts, s);
- }
- /**
- * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
- * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
- * For example
- * <ul>
- * <li>where a database trigger alters the object state upon insert or update</li>
- * <li>after executing direct SQL (eg. a mass update) in the same session</li>
- * <li>after inserting a Blob or Clob</li>
- * </ul>
- */
- public void refresh (test.src.CdmaBts cdmaBts, Session s)
- {
- refresh((Object) cdmaBts, s);
- }
- }
_RootDAO.java
- package test.src.dao;
- import org.hibernate.Session;
- public abstract class _RootDAO extends test.src.base._BaseRootDAO {
- public _RootDAO () {}
- public _RootDAO (Session session) {
- setSession(session);
- }
- /*
- If you are using lazy loading, uncomment this
- Somewhere, you should call RootDAO.closeCurrentThreadSessions();
- public void closeSession (Session session) {
- // do nothing here because the session will be closed later
- }
- */
- /*
- If you are pulling the SessionFactory from a JNDI tree, uncomment this
- protected SessionFactory getSessionFactory(String configFile) {
- // If you have a single session factory, ignore the configFile parameter
- // Otherwise, you can set a meta attribute under the class node called "config-file" which
- // will be passed in here so you can tell what session factory an individual mapping file
- // belongs to
- return (SessionFactory) new InitialContext().lookup("java:/{SessionFactoryName}");
- }
- */
- }
CdmaBtsDAO.java
- package test.src.dao;
- import org.hibernate.Session;
- import test.src.base.BaseCdmaBtsDAO;
- public class CdmaBtsDAO extends BaseCdmaBtsDAO implements test.src.dao.iface.CdmaBtsDAO {
- public CdmaBtsDAO () {}
- public CdmaBtsDAO (Session session) {
- super(session);
- }
- }
最后,是JUNIT 測試類:CdmaBtsTest
CdmaBtsDAO.java
- package test.src.dao.iface;
- import java.io.Serializable;
- public interface CdmaBtsDAO {
- public test.src.CdmaBts get(java.lang.Integer key);
- public test.src.CdmaBts load(java.lang.Integer key);
- public java.util.List<test.src.CdmaBts> findAll ();
- /**
- * Persist the given transient instance, first assigning a generated identifier. (Or using the current value
- * of the identifier property if the assigned generator is used.)
- * @param cdmaBts a transient instance of a persistent class
- * @return the class identifier
- */
- public java.lang.Integer save(test.src.CdmaBts cdmaBts);
- /**
- * Either save() or update() the given instance, depending upon the value of its identifier property. By default
- * the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the
- * identifier property mapping.
- * @param cdmaBts a transient instance containing new or updated state
- */
- public void saveOrUpdate(test.src.CdmaBts cdmaBts);
- /**
- * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
- * instance with the same identifier in the current session.
- * @param cdmaBts a transient instance containing updated state
- */
- public void update(test.src.CdmaBts cdmaBts);
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * @param id the instance ID to be removed
- */
- public void delete(java.lang.Integer id);
- /**
- * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
- * Session or a transient instance with an identifier associated with existing persistent state.
- * @param cdmaBts the instance to be removed
- */
- public void delete(test.src.CdmaBts cdmaBts);
- }
最后,是JUNIT 的测试类:CdmaBtsTest.java
- package test.src;
- import junit.framework.TestCase;
- import org.junit.After;
- import org.junit.Before;
- import test.src.dao.CdmaBtsDAO;
- import test.src.dao._RootDAO;
- public class CdmaBtsTest extends TestCase {
- @Before
- public void setUp() throws Exception {
- }
- @After
- public void tearDown() throws Exception {
- }
- public void testInsert() {
- /*
- * sessionFactory=new Configuration().configure().buildSessionFactory();
- * Session s=sessionFactory.openSession();
- *
- * Transaction t=s.beginTransaction();
- *
- * CdmaBts bts=new CdmaBts("1001"); bts.setCODE("What");
- *
- * s.save(bts); t.commit(); s.close();
- */
- _RootDAO.initialize();
- CdmaBtsDAO dao = new CdmaBtsDAO();
- CdmaBts bts = new CdmaBts();
- // bts.setId(11032);
- bts.setCode(bts.toString());
- dao.save(bts);
- }
- }
另外,还需要新建一个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
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.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
以上是一个简单的 hibernate 实例。
可以运行 junit 测试类 CdmaBtsTest 看到运行结果。