下面是 MyEclipse 的示例代码
它把 transaction 的实现交给了调用类,
这样似乎DAO层的依赖类 Session,Transaction 越过了DAO层,
所以,最好还是考虑把 Transaction 放到DAO层中

package com.genuitec.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateWriteTest {
    public static void main(String[] args) {
        // Step 1 - Create the DAO
        EchoMessageDAO dao = new EchoMessageDAO();
        // Step 2 - Create a new entity
        EchoMessage message = new EchoMessage(new Long(3));
        // Step 3 - Set the message field
        message.setMsg("Hello Hibernate, from MyEclipse!");

        Transaction tx = null;
        try {
            // Step 4 - Get a Hibernate Session
            Session session = dao.getSession();
            tx = session.beginTransaction();
            // Step 5 - Save the entity
            dao.save(message);
            tx.commit();
            System.out.println("Save successful.");
        catch (HibernateException e) {
            tx.rollback();
            System.out.println("Save failed.");
            e.printStackTrace();
        finally {
            try {
                dao.getSession().close();
            catch (Exception e) {
                // do nothing
            }
        }
    }

}
评论
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

kenter1643
搜索本博客
博客分类
最近加入圈子
存档
最新评论