在Maven的Web項目中用Main函數測試Hibernate


1. 編寫Main測試Hibernate代碼(與非Web項目一樣)

<pre name="code" class="java">public class HibernateTest {	 
	public static void main(String[] args) {
		Configuration conf = new AnnotationConfiguration().configure();
		SessionFactory factory = conf.buildSessionFactory();
		Session session = factory.openSession();
		session.beginTransaction();
		
		List<Req> l = (List<Req>)session.createCriteria(Req.class).list();
		System.out.println(l.size());
		
		session.getTransaction().commit();
		session.close();		
	}
}


Run報錯:

INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found

2.  編寫 hibernate.cfg.xml,並移動到 /target/classes 目錄下面去(由於每次Maven Clean後,會被清理掉,所以可以手動複製過去)

<?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.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/fulfillment</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>        
        <mapping class="com.pactera.req.model.Req"></mapping>
		<mapping class="com.pactera.common.model.Dept"></mapping> 
    </session-factory>
</hibernate-configuration>















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章