Hibernate自動建表(使用DDL語句)
阿新 • • 發佈:2019-01-08
Gd上次和大家談到使用DDL語句實現自動建表失敗的問題,過了幾天再回頭看果然思路就變得清晰許多,原來是xxx.hbm.xml檔案的配置上出了問題,因為上次沒有用Junit進行測試,所以沒有看明白問題的描述,這裡不得不說一句,Junit真是個好東西,emmmmmm。Junit測試後報的錯誤是這樣的: Could not parse mapping document: org/User/hibernate.hbm.xml (RESOURCE),大概意思就是無法解析這個xxx.hbm.xml檔案,對於初學者來說,我覺得應對這麼大範圍的錯誤最好的辦法就是把以前用的正確的xxx.hbm.xml檔案拷貝過來測試成功了再說,Gd把之前測試成功的xxx.hbm.xml檔案拷貝過來,再次進行測試,果不其然,測試成功!
再回過頭去找之前的錯誤所在,發現是粗心大意的自己把generator class那一行給落下了,真的是因小失大啊!!!
下面給出我的測試成功的檔案供大家借鑑:
1.xxx.hbm.xml檔案
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2017-8-22 10:37:16 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="org.User.User" table="X_USER"> <id name="id" type="int"> <column name="ID" /> <generator class="increment" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" /> </property> <property name="age" type="int"> <column name="AGE" /> </property> <property name="gender" type="java.lang.String"> <column name="Gender" /> </property> </class> </hibernate-mapping>
這裡的generator class屬性值是increment,使用native也一樣會測試成功。
2.xxx.cfg.xml檔案
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="show_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.username">system</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- 自動建表語句,其屬性值有多個,create是其中一個,屬性值不同功能不同 --> <property name="hibernate.hbm2ddl.auto" >create</property> <mapping resource="org/User/hibernate.hbm.xml"/> </session-factory> </hibernate-configuration>
3.測試類
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import org.User.User;
public class TestX_user{
@Test
public void testIncrease(){
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
try {
User u = new User();
u.setName("張三");
u.setAge(23);
u.setPassword("zhangsan");
session.save(u);
tx.commit();
} catch (Exception e)
{
// TODO: handle exception
if(null!=tx){tx.rollback();}
e.printStackTrace();
}
finally
{
session.close();
sf.close();
}
}
}
如此便大功告成了,歡迎一起學習的同志們多多交流!!!