文件结构如下 开发工具myEclipse6.M1

代码(具体位置看package位置)
 package com.lusm.hib.dao;
package com.lusm.hib.dao;

 import org.hibernate.Session;
import org.hibernate.Session;


 public interface IBaseHibernateDAO
public interface IBaseHibernateDAO  {
{
 public Session getSession();
    public Session getSession();
 }
} package com.lusm.hib.dao.impl;
package com.lusm.hib.dao.impl;

 import org.hibernate.Session;
import org.hibernate.Session;

 import com.lusm.hib.dao.IBaseHibernateDAO;
import com.lusm.hib.dao.IBaseHibernateDAO;
 import com.lusm.hib.factory.HibernateSessionFactory;
import com.lusm.hib.factory.HibernateSessionFactory;


 public class BaseHibernateDAO implements IBaseHibernateDAO
public class BaseHibernateDAO implements IBaseHibernateDAO  {
{


 public Session getSession()
    public Session getSession()  {
{
 return HibernateSessionFactory.getSession();
        return HibernateSessionFactory.getSession();
 }
    }

 }
} package com.lusm.hib.factory;
package com.lusm.hib.factory;

 import org.hibernate.HibernateException;
import org.hibernate.HibernateException;
 import org.hibernate.Session;
import org.hibernate.Session;
 import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Configuration;


 public class HibernateSessionFactory
public class HibernateSessionFactory  {
{

 private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
 private static Configuration configuration = new Configuration();
    private static Configuration configuration = new Configuration();
 private static org.hibernate.SessionFactory sessionFactory;
    private static org.hibernate.SessionFactory sessionFactory;
 private static String configFile = CONFIG_FILE_LOCATION;
    private static String configFile = CONFIG_FILE_LOCATION;


 static
    static  {
{

 try
        try  {
{
 configuration.configure(configFile);
            configuration.configure(configFile);
 sessionFactory = configuration.buildSessionFactory();
            sessionFactory = configuration.buildSessionFactory();

 } catch (Exception e)
        } catch (Exception e)  {
{
 System.err.println("%%%% Error Creating SessionFactory %%%%");
            System.err.println("%%%% Error Creating SessionFactory %%%%");
 e.printStackTrace();
            e.printStackTrace();
 }
        }
 }
    }


 private HibernateSessionFactory()
    private HibernateSessionFactory()  {
{
 }
    }


 public static Session getSession() throws HibernateException
    public static Session getSession() throws HibernateException  {
{
 Session session = (Session) threadLocal.get();
        Session session = (Session) threadLocal.get();


 if (session == null || !session.isOpen())
        if (session == null || !session.isOpen())  {
{

 if (sessionFactory == null)
            if (sessionFactory == null)  {
{
 rebuildSessionFactory();
                rebuildSessionFactory();
 }
            }
 session = (sessionFactory != null) ? sessionFactory.openSession()
            session = (sessionFactory != null) ? sessionFactory.openSession()
 : null;
                    : null;
 threadLocal.set(session);
            threadLocal.set(session);
 }
        }

 return session;
        return session;
 }
    }


 public static void rebuildSessionFactory()
    public static void rebuildSessionFactory()  {
{

 try
        try  {
{
 configuration.configure(configFile);
            configuration.configure(configFile);
 sessionFactory = configuration.buildSessionFactory();
            sessionFactory = configuration.buildSessionFactory();

 } catch (Exception e)
        } catch (Exception e)  {
{
 System.err.println("%%%% Error Creating SessionFactory %%%%");
            System.err.println("%%%% Error Creating SessionFactory %%%%");
 e.printStackTrace();
            e.printStackTrace();
 }
        }
 }
    }


 public static void closeSession() throws HibernateException
    public static void closeSession() throws HibernateException  {
{
 Session session = (Session) threadLocal.get();
        Session session = (Session) threadLocal.get();
 threadLocal.set(null);
        threadLocal.set(null);


 if (session != null)
        if (session != null)  {
{
 session.close();
            session.close();
 }
        }
 }
    }


 public static org.hibernate.SessionFactory getSessionFactory()
    public static org.hibernate.SessionFactory getSessionFactory()  {
{
 return sessionFactory;
        return sessionFactory;
 }
    }


 public static void setConfigFile(String configFile)
    public static void setConfigFile(String configFile)  {
{
 HibernateSessionFactory.configFile = configFile;
        HibernateSessionFactory.configFile = configFile;
 sessionFactory = null;
        sessionFactory = null;
 }
    }


 public static Configuration getConfiguration()
    public static Configuration getConfiguration()  {
{
 return configuration;
        return configuration;
 }
    }

 }
} package com.lusm.stu.dao;
package com.lusm.stu.dao;

 import java.util.List;
import java.util.List;

 import org.apache.commons.logging.Log;
import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.LogFactory;
 import org.hibernate.LockMode;
import org.hibernate.LockMode;
 import org.hibernate.Query;
import org.hibernate.Query;
 import org.hibernate.criterion.Example;
import org.hibernate.criterion.Example;

 import com.lusm.hib.dao.impl.BaseHibernateDAO;
import com.lusm.hib.dao.impl.BaseHibernateDAO;
 import com.lusm.stu.vo.Student;
import com.lusm.stu.vo.Student;


 public class StudentDAO extends BaseHibernateDAO
public class StudentDAO extends BaseHibernateDAO  {
{
 private static final Log log = LogFactory.getLog(StudentDAO.class);
    private static final Log log = LogFactory.getLog(StudentDAO.class);
 // property constants
    // property constants
 public static final String NAME = "name";
    public static final String NAME = "name";


 public void save(Student transientInstance)
    public void save(Student transientInstance)  {
{
 log.debug("saving Student instance");
        log.debug("saving Student instance");

 try
        try  {
{
 getSession().save(transientInstance);
            getSession().save(transientInstance);
 log.debug("save successful");
            log.debug("save successful");

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("save failed", re);
            log.error("save failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public void delete(Student persistentInstance)
    public void delete(Student persistentInstance)  {
{
 log.debug("deleting Student instance");
        log.debug("deleting Student instance");

 try
        try  {
{
 getSession().delete(persistentInstance);
            getSession().delete(persistentInstance);
 log.debug("delete successful");
            log.debug("delete successful");

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("delete failed", re);
            log.error("delete failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public Student findById(java.lang.Long id)
    public Student findById(java.lang.Long id)  {
{
 log.debug("getting Student instance with id: " + id);
        log.debug("getting Student instance with id: " + id);

 try
        try  {
{
 Student instance = (Student) getSession().get(
            Student instance = (Student) getSession().get(
 "com.lusm.stu.vo.Student", id);
                    "com.lusm.stu.vo.Student", id);
 return instance;
            return instance;

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("get failed", re);
            log.error("get failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public List findByExample(Student instance)
    public List findByExample(Student instance)  {
{
 log.debug("finding Student instance by example");
        log.debug("finding Student instance by example");

 try
        try  {
{
 List results = getSession().createCriteria(
            List results = getSession().createCriteria(
 "com.lusm.stu.vo.Student").add(Example.create(instance))
                    "com.lusm.stu.vo.Student").add(Example.create(instance))
 .list();
                    .list();
 log.debug("find by example successful, result size: "
            log.debug("find by example successful, result size: "
 + results.size());
                    + results.size());
 return results;
            return results;

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("find by example failed", re);
            log.error("find by example failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public List findByProperty(String propertyName, Object value)
    public List findByProperty(String propertyName, Object value)  {
{
 log.debug("finding Student instance with property: " + propertyName
        log.debug("finding Student instance with property: " + propertyName
 + ", value: " + value);
                + ", value: " + value);

 try
        try  {
{
 String queryString = "from Student as model where model."
            String queryString = "from Student as model where model."
 + propertyName + "= ?";
                    + propertyName + "= ?";
 Query queryObject = getSession().createQuery(queryString);
            Query queryObject = getSession().createQuery(queryString);
 queryObject.setParameter(0, value);
            queryObject.setParameter(0, value);
 return queryObject.list();
            return queryObject.list();

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("find by property name failed", re);
            log.error("find by property name failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public List findByName(Object name)
    public List findByName(Object name)  {
{
 return findByProperty(NAME, name);
        return findByProperty(NAME, name);
 }
    }


 public List findAll()
    public List findAll()  {
{
 log.debug("finding all Student instances");
        log.debug("finding all Student instances");

 try
        try  {
{
 String queryString = "from Student";
            String queryString = "from Student";
 Query queryObject = getSession().createQuery(queryString);
            Query queryObject = getSession().createQuery(queryString);
 return queryObject.list();
            return queryObject.list();

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("find all failed", re);
            log.error("find all failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public Student merge(Student detachedInstance)
    public Student merge(Student detachedInstance)  {
{
 log.debug("merging Student instance");
        log.debug("merging Student instance");

 try
        try  {
{
 Student result = (Student) getSession().merge(detachedInstance);
            Student result = (Student) getSession().merge(detachedInstance);
 log.debug("merge successful");
            log.debug("merge successful");
 return result;
            return result;

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("merge failed", re);
            log.error("merge failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public void attachDirty(Student instance)
    public void attachDirty(Student instance)  {
{
 log.debug("attaching dirty Student instance");
        log.debug("attaching dirty Student instance");

 try
        try  {
{
 getSession().saveOrUpdate(instance);
            getSession().saveOrUpdate(instance);
 log.debug("attach successful");
            log.debug("attach successful");

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("attach failed", re);
            log.error("attach failed", re);
 throw re;
            throw re;
 }
        }
 }
    }


 public void attachClean(Student instance)
    public void attachClean(Student instance)  {
{
 log.debug("attaching clean Student instance");
        log.debug("attaching clean Student instance");

 try
        try  {
{
 getSession().lock(instance, LockMode.NONE);
            getSession().lock(instance, LockMode.NONE);
 log.debug("attach successful");
            log.debug("attach successful");

 } catch (RuntimeException re)
        } catch (RuntimeException re)  {
{
 log.error("attach failed", re);
            log.error("attach failed", re);
 throw re;
            throw re;
 }
        }
 }
    }
 }
} package com.lusm.stu.vo;
package com.lusm.stu.vo;


 public class Student implements java.io.Serializable
public class Student implements java.io.Serializable  {
{

 private Long id;
    private Long id;
 private String name;
    private String name;


 public Student()
    public Student()  {
{
 }
    }


 public Student(Long id, String name)
    public Student(Long id, String name)  {
{
 this.id = id;
        this.id = id;
 this.name = name;
        this.name = name;
 }
    }


 public Long getId()
    public Long getId()  {
{
 return this.id;
        return this.id;
 }
    }


 public void setId(Long id)
    public void setId(Long id)  {
{
 this.id = id;
        this.id = id;
 }
    }


 public String getName()
    public String getName()  {
{
 return this.name;
        return this.name;
 }
    }


 public void setName(String name)
    public void setName(String name)  {
{
 this.name = name;
        this.name = name;
 }
    }

 }
}
Student.hbm.xml
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <!--
<!-- 
 Mapping file autogenerated by MyEclipse Persistence Tools
    Mapping file autogenerated by MyEclipse Persistence Tools
 -->
-->
 <hibernate-mapping>
<hibernate-mapping>
 <class name="com.lusm.stu.vo.Student" table="STUDENT" schema="LUSM">
    <class name="com.lusm.stu.vo.Student" table="STUDENT" schema="LUSM">
 <id name="id" type="java.lang.Long">
        <id name="id" type="java.lang.Long">
 <column name="ID" precision="22" scale="0" />
            <column name="ID" precision="22" scale="0" />
 <generator class="assigned" />
            <generator class="assigned" />
 </id>
        </id>
 <property name="name" type="java.lang.String">
        <property name="name" type="java.lang.String">
 <column name="NAME" length="20" not-null="true" />
            <column name="NAME" length="20" not-null="true" />
 </property>
        </property>
 </class>
    </class>
 </hibernate-mapping>
</hibernate-mapping> package com.lusm.test;
package com.lusm.test;

 import java.util.Iterator;
import java.util.Iterator;
 import java.util.List;
import java.util.List;

 import org.hibernate.Query;
import org.hibernate.Query;
 import org.hibernate.Session;
import org.hibernate.Session;

 import com.lusm.hib.factory.HibernateSessionFactory;
import com.lusm.hib.factory.HibernateSessionFactory;
 import com.lusm.stu.vo.Student;
import com.lusm.stu.vo.Student;


 public class Test
public class Test  {
{

 public static void main(String[] args)
    public static void main(String[] args)  {
{
 Session session = HibernateSessionFactory.getSession();
        Session session = HibernateSessionFactory.getSession();
 String sql = "from Student";
        String sql = "from Student";
 Query query = session.createQuery(sql);
        Query query = session.createQuery(sql);
 List list = query.list();
        List list = query.list();
 session.close();
        session.close();
 Iterator i = list.iterator();
        Iterator i = list.iterator();
 System.out.println("id"+"\t"+"name");
        System.out.println("id"+"\t"+"name");
 System.out.println("---------------");
        System.out.println("---------------");

 while (i.hasNext())
        while (i.hasNext())  {
{
 Student stu = (Student) i.next();
            Student stu = (Student) i.next();
 System.out.println(stu.getId() + "\t" + stu.getName());
            System.out.println(stu.getId() + "\t" + stu.getName());
 }
        }

 }
    }
 }
}
hibernate.cfg.xml
 <?xml version='1.0' encoding='UTF-8'?>
<?xml version='1.0' encoding='UTF-8'?>
 <!DOCTYPE hibernate-configuration PUBLIC
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 <!-- Generated by MyEclipse Hibernate Tools.                   -->
<!-- Generated by MyEclipse Hibernate Tools.                   -->
 <hibernate-configuration>
<hibernate-configuration>

 <session-factory>
    <session-factory>
 <property name="connection.username">test</property>
        <property name="connection.username">test</property>
 <property name="connection.url">
        <property name="connection.url">
 jdbc:oracle:thin:@localhost:1521:oracle
            jdbc:oracle:thin:@localhost:1521:oracle
 </property>
        </property>
 <property name="dialect">
        <property name="dialect">
 org.hibernate.dialect.Oracle9Dialect
            org.hibernate.dialect.Oracle9Dialect
 </property>
        </property>
 <property name="myeclipse.connection.profile">
        <property name="myeclipse.connection.profile">
 Oracle
            Oracle
 </property>
        </property>
 <property name="connection.password">123456</property>
        <property name="connection.password">123456</property>
 <property name="connection.driver_class">
        <property name="connection.driver_class">
 oracle.jdbc.OracleDriver
            oracle.jdbc.OracleDriver
 </property>
        </property>
 <property name="show_sql">true</property>
        <property name="show_sql">true</property>
 <mapping resource="com/lusm/stu/vo/Student.hbm.xml" />
        <mapping resource="com/lusm/stu/vo/Student.hbm.xml" />

 </session-factory>
    </session-factory>

 </hibernate-configuration>
</hibernate-configuration>
运行结果是
 log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
 log4j:WARN Please initialize the log4j system properly.
log4j:WARN Please initialize the log4j system properly.
 Hibernate: select student0_.ID as ID0_, student0_.NAME as NAME0_ from LUSM.STUDENT student0_
Hibernate: select student0_.ID as ID0_, student0_.NAME as NAME0_ from LUSM.STUDENT student0_
 id    name
id    name
 ---------------
---------------
 1    aaaaa
1    aaaaa
 2    bbbbb
2    bbbbb
 3    ccccc
3    ccccc
 
 
	posted on 2007-09-14 21:37 
小寻 阅读(885) 
评论(0)  编辑  收藏  所属分类: 
j2se/j2ee/j2me