How to adapt Hibernate to the DAO standard?

3

I'm starting to study Hibernate and wanted to "start right". The doubt is as follows:

For the entire transaction I need to use the following code:

Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();

and to save

    Empregado emp = new Empregado();
    emp.setEmail("[email protected]");
    emp.setNome("Jose");
    emp.setSobenome("Alves");

    session.save(emp);

    session.getTransaction().commit();

I am already accustomed to the DAO pattern but using JDBC . I'd like to know how best to use Sessions along with the DAO pattern. If, for example, I would have to open Session and close in all DAO methods, or if I would have some other way not to allocate unnecessary resources. If you can paste an example I would appreciate it.

    
asked by anonymous 18.02.2016 / 14:19

1 answer

2

The DAO Standard is nothing more than isolating all database access on a single layer. In Java we use the packages to isolate access.

JDBC is nothing more than the API provided by JAVA that allows you access to the databases, but this depends on the implementation you will use, in this case the drive you are going to add to your project.

update

Here is a very basic example of a layered system model, DAO, and Service. It is possible to see that each class performs only one activity. For a more complete example, only the VIEW layer of information presentation is missing.

public class Pessoa{

    private Int id;
    private String nome;
    private Int idade;
    //...outro metodos
}

public class PessoaDao{

    public Boolean salvar(Pessoa pessoa){

        Boolean resultado = false;
        try{
            Connection con = Factory.getConnection();
            String insertComand = "insert into tb_pessoa values(?,?,?)";
            PreparedStatement cmd=con.preparedStatement(insertComand);
            cmd.setInt(1,pessoa.getId());
            cmd.setString(2,pessoa.getNome());
            cmd.setInt(3,pessoa.getIdade());
            cmd.execute();
            resultado=true;
        }catch(Exception ex){
            resultado=false;
        }

        return resultado;
    }

}

public class PessoaService{

    private PessoaDao pessoaDao;

    public boolean salvarPessoa(Pessoa pessoa){
        pessoaDao = new PessoaDao();
        return pessoaDao.salvar(pessoa);
    }
}
    
18.02.2016 / 16:23