使用Hibernate从数据库保存/恢复数据(postgresql)

时间:2014-03-15 01:47:23

标签: java hibernate postgresql

在我的项目中,我只使用hibernate生成pojo和dao类。但是Hibernate生成的dao类都是这种风格:

package com.ligadesportiva.data;

// Generated 14/03/2014 22:39:34 by Hibernate Tools 3.4.0.CR1

import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.ligadesportiva.core.Jogador;

/**
 * Home object for domain model class Jogador.
 * @see com.ligadesportiva.data.Jogador
 * @author Hibernate Tools
 */
public class JogadorHome {

    private static final Log log = LogFactory.getLog(JogadorHome.class);

    private final SessionFactory sessionFactory = getSessionFactory();

    protected SessionFactory getSessionFactory() {
        try {
            return (SessionFactory) new InitialContext()
                    .lookup("SessionFactory");
        } catch (Exception e) {
            log.error("Could not locate SessionFactory in JNDI", e);
            throw new IllegalStateException(
                    "Could not locate SessionFactory in JNDI");
        }
    }

    public void persist(Jogador transientInstance) {
        log.debug("persisting Jogador instance");
        try {
            sessionFactory.getCurrentSession().persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(Jogador instance) {
        log.debug("attaching dirty Jogador instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Jogador instance) {
        log.debug("attaching clean Jogador instance");
        try {
            sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void delete(Jogador persistentInstance) {
        log.debug("deleting Jogador instance");
        try {
            sessionFactory.getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Jogador merge(Jogador detachedInstance) {
        log.debug("merging Jogador instance");
        try {
            Jogador result = (Jogador) sessionFactory.getCurrentSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Jogador findById(int id) {
        log.debug("getting Jogador instance with id: " + id);
        try {
            Jogador instance = (Jogador) sessionFactory.getCurrentSession()
                    .get("com.ligadesportiva.data.Jogador", id);
            if (instance == null) {
                log.debug("get successful, no instance found");
            } else {
                log.debug("get successful, instance found");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Jogador instance) {
        log.debug("finding Jogador instance by example");
        try {
            List results = sessionFactory.getCurrentSession()
                    .createCriteria("com.ligadesportiva.data.Jogador")
                    .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }
}

但是我希望从postgresql数据库中保存/读取数据。是否有任何代码我应该添加到这个项目中以使这个dao类与我的DB交互?

1 个答案:

答案 0 :(得分:1)

仅仅是为了记录,我在这里有一些关于这个主题的考虑因素我几天都在那里学习:

首先,除了Hibernate(DAO和POJO)生成的两组类之外,我在此示例中创建了另一个类:

http://www.baeldung.com/hibernate-4-spring

我在其中配置了Hibernate的一些选项和方法,并指向我放置用于连接数据库的选项的文件( database.properties )。

之后,我对生成的类进行了一些更改:

1)在POJO类中,我为类添加了注释@Entity和@Table(第二个注释带有de参数值="?",其中?是表的名称与这个课程相关联)。对于属性,我为所有属性添加注释@Column,并为与主键相关的属性添加注释@Id。

2)在DAO类中,我为类添加了注释@Repository,为所有方法添加了注释@Transactional。由于这个注释,我可以在我的* -servlet.xml文件中插入以下行:

<tx:annotation-driven transaction-manager="transactionManager"/>

并在标题中,这个选项:

xmlns:tx="http://www.springframework.org/schema/tx"

和xsi:schemaLocation:

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd.

此外,使用@Autowired注释了atribute sessionFactory,删除了关联,并添加了这个方法:

protected Session getCurrentSession() {
    return sessionFactory.getCurrentSession();
}

为了使用此类来处理对数据库的查询,我将它们添加为控制器的属性,始终通知注释@Autowired。

在控制器的每个方法中,我使用类作为这个例子:

读取数据

Usuario novo = usuario.findById(this.getId_usuario());

保存数据

Sessao nova = new Sessao(novo, 0);
sessao.persist(nova);