JPA + TopLink organização das classes

5 respostas
M

Pessoal,

Fazendo minha aplicação com JPA cada pagina que for fazer persistir no banco eu tenho que incluir o código:

protected void persist(Object object) {
        try {
            Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

e mais os método para realizar as pesquisas todas… sendo assim vou ficar com muito código repetido em varias classes e sempre que isso acontece fico com a sensação de que tem algo “errado” ou que poderia ser feito de uma forma melhor, qual seria a dica de como fazer isso ?

5 Respostas

anderson.bonavides

Isso realmente ta estranho.

Eu faço assim, modelo a ser persistido:

package crudjsf.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.*;

@Entity
@Table(name = "contato")
public class Contato implements Serializable{
	private static final long serialVersionUID = -2669662161518699260L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", nullable = false)
	private Integer id;
	
	@Column(name = "nome")
	private String nome;
	
	@Column(name = "email")
	private String email;
	
	@Temporal(TemporalType.DATE)
	private Date nascimento;

	@Column(name = "telefone")
	private String telefone;

persistence.xml XML:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  
  <persistence-unit name="JPA" transaction-type="RESOURCE_LOCAL">
  <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
	<class>crudjsf.model.Contato</class>
    
    
    <properties>
      <property name="toplink.logging.level" value="INFO"/>
      <property name="toplink.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/ContatoBd"/>
      <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="toplink.jdbc.user" value="root"/>
   	 <property name="toplink.jdbc.password" value="222222"/>
   	 <!--<property name="toplink.ddl-generation" value="create-tables"/>-->
    </properties>
  </persistence-unit>
  
</persistence>

A linha do xml comentado serve para criar as classes. Caso comente novamente não vai ser criado nada. Já a tag informa qual classes vão ser persistidas no banco de dados.

Eu acho que é isso que vc ta querendo. Depois eu posso te passar um exemplo mais completo.

M

Vou tentar explicar melhor :lol:

Tenho a tabela Contato com 3 campos id, nome e fone

Tenho o meu bean Contato

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package guj;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author renata
 */
@Entity
@Table(name = "CONTATO")
@NamedQueries({@NamedQuery(name = "Contato.findById", query = "SELECT c FROM Contato c WHERE c.id = :id"), @NamedQuery(name = "Contato.findByNome", query = "SELECT c FROM Contato c WHERE c.nome = :nome"), @NamedQuery(name = "Contato.findByFone", query = "SELECT c FROM Contato c WHERE c.fone = :fone")})
public class Contato implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "ID", nullable = false)
    private Integer id;
    @Column(name = "NOME")
    private String nome;
    @Column(name = "FONE")
    private String fone;

    public Contato() {
    }

    public Contato(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getFone() {
        return fone;
    }

    public void setFone(String fone) {
        this.fone = fone;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Contato)) {
            return false;
        }
        Contato other = (Contato) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "guj.Contato[id=" + id + "]";
    }

}

O persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="GujPU" transaction-type="JTA">
    <jta-data-source>GujJNDI</jta-data-source>
    <properties/>
  </persistence-unit>
</persistence>

tenho o RequestBean1.java

/*
 * RequestBean1.java
 *
 * Created on 15/10/2008, 14:40:05
 */
 
package guj;

import com.sun.rave.web.ui.appbase.AbstractRequestBean;
import javax.faces.FacesException;

public class RequestBean1 extends AbstractRequestBean {
    
    private Contato contato = new Contato();
    
    private void _init() throws Exception {
    }
    public RequestBean1() {
    }

    @Override
    public void init() {
        super.init();
        try {
            _init();
        } catch (Exception e) {
            log("RequestBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
    }

    @Override
    public void destroy() {
    }
    
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public

    Contato getContato() {
        return contato;
    }

    public void setContato(Contato contato) {
        this.contato = contato;
    }

}

E finalmente a minha pagina que vai usar tudo isso :smiley:

package guj;

import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.TextField;
import javax.annotation.Resource;
import javax.faces.FacesException;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@PersistenceContext(name = "persistence/LogicalName", unitName = "GujPU")
public class Page1 extends AbstractPageBean {
    @Resource
    private javax.transaction.UserTransaction utx;
    private void _init() throws Exception {
    }


    public Page1() {
    }

    @Override
    public void init() {
        super.init();
        try {
            _init();
        } catch (Exception e) {
            log("Page1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
    }

    @Override
    public void preprocess() {
    }

    @Override
    public void prerender() {
    }

    @Override
    public void destroy() {
    }
    
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public String cadastrarBtn_action() {
        this.persist(this.getRequestBean1().getContato());
        return null;
    }

    protected void persist(Object object) {
        try {
            Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

}

Agora veja … imagine que queira fazer uma pagina2 que também persiste Contato. todo o metodo protected void persist(Object object) eu teria que ter na pagina2.

anderson.bonavides

Que tipo padrão você ta usando?

M

Não sei :shock:

by my self

qual seria a sugestão para este caso ?

Eh que comecei a fazer só para estudar o jpa + toplink e ai vem aparecendo as duvidas… este não eh nenhum projeto … eh apenas para testar/aprender

anderson.bonavides

Tenta por esse projeto pra rodar:

http://www.fabiosantiago.com.br/jpa/

Vc vai nescessitar do MYSQL para criar o banco. Quando compilar automaticamente é gerado as tabelas no banco.

Qualquer duvida pode perguntar.

Criado 15 de outubro de 2008
Ultima resposta 15 de out. de 2008
Respostas 5
Participantes 2