2016年1月24日 星期日

HelloWorld 和 HibernateUtil (Hibernate4.x一)

Hibernate3.x的HibernateUtil裡面的buildSessionFactory()在第4版已經過時了,雖然還是可以run,如果不喜歡看到錯誤,稍加修改就沒問題了,從官網可以複製,但執行時出現「Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set」的錯,要修改成以下的樣子才OK
HibernateUtil.java
private static final SessionFactory sessionFactory = buildSessionFactory();
    
private static SessionFactory buildSessionFactory() {
    try {
        Configuration configuration = new Configuration();
        configuration.configure();
    
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    
        SessionFactory sessionFactory = configuration
                .buildSessionFactory(serviceRegistry);
        return sessionFactory;
        // return new Configuration().configure().buildSessionFactory(
        // new StandardServiceRegistryBuilder().build() );
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
    
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

※註解的部分是官網的,就是會錯

※使用時和第3版一樣Session s = HibernateUtil.getSessionFactory().getCurrentSession();



<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.11.Final</version>
</dependency>

※只下載hibernate-core,3.x版在執行時,會出現找不到javassist的錯誤訊息,所以還得下載org.javassist,但第4版我一樣用maven,就直接有了,所以下載這個jar即可



其他測試程式如下:

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="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hibernate.connection.username">username</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <!-- <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> -->
        <property name="hibernate.current_session_context_class">thread</property>
        <!-- <mapping resource="hbm/Dept.hbm.xml" /> -->
        <mapping class="vo.Dept" />
    </session-factory>
</hibernate-configuration>



Dept.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 2016/1/24 ?U?? 07:30:42 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="vo.Dept" table="DEPT">
        <id name="deptno" type="java.lang.Integer">
            <column name="DEPTNO" />
            <generator class="assigned" />
        </id>
        <property name="dname" type="java.lang.String">
            <column name="DNAME" />
        </property>
        <property name="loc" type="java.lang.String">
            <column name="LOC" />
        </property>
    </class>
</hibernate-mapping>



Dept.java

@Entity
@Table
public class Dept {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XXX")
    @SequenceGenerator(name = "XXX", sequenceName = "DEPT_SEQ")
    private Integer deptno;
    
    private String dname;
    
    private String loc;
    // setter/getter...
}



測試類

Session s = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = s.beginTransaction();
try {
    Query q = s.createQuery("from Dept");
    @SuppressWarnings("unchecked")
    List<Dept> e = q.list();
    for (Dept d : e) {
        System.out.println(d.getDeptno());
        System.out.println(d.getDname());
        System.out.println(d.getLoc());
        System.out.println();
    }

} catch (Exception e) {
    tx.rollback();
    System.err.println("例外錯誤!");
    e.printStackTrace();
} finally {
    if (s.isOpen()) {
        s.close();
    }
}

※我有將開發工具Hibernate3.x的Hello World (使用Hibernate tools)(Hibernate3.x一)設定成4.3版了,但cfg.xml和hbm.xml的dtd還是3,都和Hibernate3.x一樣

※cfg的mapping resource對應hbm.xml; cfg的mapping class對應annotation都和Hibernate3.x一樣,擇一使用即可

沒有留言:

張貼留言