Descobrir ID antes de salvar no Hibernate e PostgreSQL

5 respostas
D

Opa :smiley:

Existe algum metodo do hibernate que eu descubra o proximo ID valido antes de salvar um registro no banco de dados?

[]'s

5 Respostas

P

vai depender da politica de geração de ID que vc esta usando e o banco de dados tb. Se vc usar um MySql, por exemplo, com autoincrement vc pode fazer um max(id). Se vc usar o oracle, por exemplo, com sequence, vc pode usar sequence.curval. Enfim… qual a politica e o banco de dados que vc usa?

abraços

D

PostgreSQL e os id sao gerados pela sequencia:

nextval('carga_id_carga_seq'::regclass)

No Hibernate esta mapeada da seguinte maneira:

@Entity
@Table(name="carga", schema="public")
@SequenceGenerator(sequenceName="carga_id_carga_seq", name="carga_id_carga_seq", allocationSize=1)
public class CargaBean implements Carga, Serializable{

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="carga_id_carga_seq")
	@Column(name="id_carga")
	private Integer id;

Se eu der um comando:

Ele retorna a proxima chave livre, mas ele nao usa ela qdo vai gravar e usa a proxima pq ele entende que a chave retornada, ja foi usada.

P

tenta essa documentação.

http://www.postgresql.org/docs/8.1/interactive/functions-sequence.html

parece que postgres tem uma função que retorna o curval.

veja se te ajuda.

D

Eu ja dei uma olhada no link e a unica que funcionou foio nextval. O currval nao funcionou aqui.

A

Pessoal,

Também estou com um problema parecido, que está me dando uma canceira e sem solução...
se alguém puder me ajudar!!!

Preciso descobrir o id da tabela antes de salvar o objeto, mas não estou usando Hibernate e sim EclipseLink(JPA 2.0) + banco é postgreSQL + EJB 3.0 + JSF.

A classe anotada é a seguinte:
package persistencia;

import persistencia.Paciente;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "Pessoa")
//estratégia para gerar PK atraves das sequences
@SequenceGenerator(name = "pessoa_idpess_seq", sequenceName = "pessoa_idpess_seq", allocationSize = 1)
@NamedQueries({
    @NamedQuery(name = "Pessoa.findAll", query = "SELECT p FROM Pessoa p"),
    @NamedQuery(name = "Pessoa.findByIdPess", query = "SELECT p FROM Pessoa p WHERE p.idPess = :idPess"),
    @NamedQuery(name = "Pessoa.findByNomePess", query = "SELECT p FROM Pessoa p WHERE p.nomePess = :nomePess"),
    @NamedQuery(name = "Pessoa.findBySexoPess", query = "SELECT p FROM Pessoa p WHERE p.sexoPess = :sexoPess"),
    @NamedQuery(name = "Pessoa.findByCorPess", query = "SELECT p FROM Pessoa p WHERE p.corPess = :corPess"),
    @NamedQuery(name = "Pessoa.findByDtnascPess", query = "SELECT p FROM Pessoa p WHERE p.dtnascPess = :dtnascPess"),
    @NamedQuery(name = "Pessoa.findByRgPess", query = "SELECT p FROM Pessoa p WHERE p.rgPess = :rgPess"),
    @NamedQuery(name = "Pessoa.findByCpfPess", query = "SELECT p FROM Pessoa p WHERE p.cpfPess = :cpfPess"),
    @NamedQuery(name = "Pessoa.findByEstadocivilPess", query = "SELECT p FROM Pessoa p WHERE p.estadocivilPess = :estadocivilPess"),
    @NamedQuery(name = "Pessoa.findByEnderecoPess", query = "SELECT p FROM Pessoa p WHERE p.enderecoPess = :enderecoPess"),
    @NamedQuery(name = "Pessoa.findByBairroPess", query = "SELECT p FROM Pessoa p WHERE p.bairroPess = :bairroPess"),
    @NamedQuery(name = "Pessoa.findByCidadePess", query = "SELECT p FROM Pessoa p WHERE p.cidadePess = :cidadePess"),
    @NamedQuery(name = "Pessoa.findByUfPess", query = "SELECT p FROM Pessoa p WHERE p.ufPess = :ufPess"),
    @NamedQuery(name = "Pessoa.findByPaisPess", query = "SELECT p FROM Pessoa p WHERE p.paisPess = :paisPess"),
    @NamedQuery(name = "Pessoa.findByMaePess", query = "SELECT p FROM Pessoa p WHERE p.maePess = :maePess"),
    @NamedQuery(name = "Pessoa.findByPaiPess", query = "SELECT p FROM Pessoa p WHERE p.paiPess = :paiPess"),
    @NamedQuery(name = "Pessoa.findByEmailPess", query = "SELECT p FROM Pessoa p WHERE p.emailPess = :emailPess"),
    @NamedQuery(name = "Pessoa.findByTelPess", query = "SELECT p FROM Pessoa p WHERE p.telPess = :telPess")})
public class Pessoa implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    //estratégia para gerar PK
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pessoa_idpess_seq")
    @Column(name = "IdPess")
    private Integer idPess;
    @Basic(optional = false)
    @Column(name = "nomePess")
    private String nomePess;
    @Basic(optional = false)
    @Column(name = "sexoPess")
    private String sexoPess;
    @Basic(optional = false)
    @Column(name = "corPess")
    private String corPess;
    @Basic(optional = false)
    @Column(name = "dtnascPess")
    @Temporal(TemporalType.DATE)
    private Date dtnascPess;
    @Column(name = "rgPess")
    private String rgPess;
    @Column(name = "cpfPess")
    private String cpfPess;
    @Basic(optional = false)
    @Column(name = "estadocivilPess")
    private String estadocivilPess;
    @Basic(optional = false)
    @Column(name = "enderecoPess")
    private String enderecoPess;
    @Basic(optional = false)
    @Column(name = "bairroPess")
    private String bairroPess;
    @Basic(optional = false)
    @Column(name = "cidadePess")
    private String cidadePess;
    @Basic(optional = false)
    @Column(name = "ufPess")
    private String ufPess;
    @Basic(optional = false)
    @Column(name = "paisPess")
    private String paisPess;
    @Basic(optional = false)
    @Column(name = "maePess")
    private String maePess;
    @Column(name = "paiPess")
    private String paiPess;
    @Column(name = "emailPess")
    private String emailPess;
    @Column(name = "telPess")
    private String telPess;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "pessoa")
    private Collection<Usuario> usuarioCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "pessoa")
    private Collection<Paciente> pacienteCollection;

    public Pessoa() {
    }

    public Pessoa(Integer idPess) {
        this.idPess = idPess;
    }

    public Pessoa(Integer idPess, String nomePess, String sexoPess, String corPess, Date dtnascPess, String estadocivilPess, String enderecoPess, String bairroPess, String cidadePess, String ufPess, String paisPess, String maePess) {
        this.idPess = idPess;
        this.nomePess = nomePess;
        this.sexoPess = sexoPess;
        this.corPess = corPess;
        this.dtnascPess = dtnascPess;
        this.estadocivilPess = estadocivilPess;
        this.enderecoPess = enderecoPess;
        this.bairroPess = bairroPess;
        this.cidadePess = cidadePess;
        this.ufPess = ufPess;
        this.paisPess = paisPess;
        this.maePess = maePess;
    }

    public Integer getIdPess() {
        return idPess;
    }

    public void setIdPess(Integer idPess) {
        this.idPess = idPess;
    }

    public String getNomePess() {
        return nomePess;
    }

    public void setNomePess(String nomePess) {
        this.nomePess = nomePess;
    }

    public String getSexoPess() {
        return sexoPess;
    }

    public void setSexoPess(String sexoPess) {
        this.sexoPess = sexoPess;
    }

    public String getCorPess() {
        return corPess;
    }

    public void setCorPess(String corPess) {
        this.corPess = corPess;
    }

    public Date getDtnascPess() {
        return dtnascPess;
    }

    public void setDtnascPess(Date dtnascPess) {
        this.dtnascPess = dtnascPess;
    }

    public String getRgPess() {
        return rgPess;
    }

    public void setRgPess(String rgPess) {
        this.rgPess = rgPess;
    }

    public String getCpfPess() {
        return cpfPess;
    }

    public void setCpfPess(String cpfPess) {
        this.cpfPess = cpfPess;
    }

    public String getEstadocivilPess() {
        return estadocivilPess;
    }

    public void setEstadocivilPess(String estadocivilPess) {
        this.estadocivilPess = estadocivilPess;
    }

    public String getEnderecoPess() {
        return enderecoPess;
    }

    public void setEnderecoPess(String enderecoPess) {
        this.enderecoPess = enderecoPess;
    }

    public String getBairroPess() {
        return bairroPess;
    }

    public void setBairroPess(String bairroPess) {
        this.bairroPess = bairroPess;
    }

    public String getCidadePess() {
        return cidadePess;
    }

    public void setCidadePess(String cidadePess) {
        this.cidadePess = cidadePess;
    }

    public String getUfPess() {
        return ufPess;
    }

    public void setUfPess(String ufPess) {
        this.ufPess = ufPess;
    }

    public String getPaisPess() {
        return paisPess;
    }

    public void setPaisPess(String paisPess) {
        this.paisPess = paisPess;
    }

    public String getMaePess() {
        return maePess;
    }

    public void setMaePess(String maePess) {
        this.maePess = maePess;
    }

    public String getPaiPess() {
        return paiPess;
    }

    public void setPaiPess(String paiPess) {
        this.paiPess = paiPess;
    }

    public String getEmailPess() {
        return emailPess;
    }

    public void setEmailPess(String emailPess) {
        this.emailPess = emailPess;
    }

    public String getTelPess() {
        return telPess;
    }

    public void setTelPess(String telPess) {
        this.telPess = telPess;
    }

    public Collection<Usuario> getUsuarioCollection() {
        return usuarioCollection;
    }

    public void setUsuarioCollection(Collection<Usuario> usuarioCollection) {
        this.usuarioCollection = usuarioCollection;
    }

    public Collection<Paciente> getPacienteCollection() {
        return pacienteCollection;
    }

    public void setPacienteCollection(Collection<Paciente> pacienteCollection) {
        this.pacienteCollection = pacienteCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idPess != null ? idPess.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 Pessoa)) {
            return false;
        }
        Pessoa other = (Pessoa) object;
        if ((this.idPess == null && other.idPess != null) || (this.idPess != null && !this.idPess.equals(other.idPess))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "persistencia.Pessoa[idPess=" + idPess + "]";
    }

}

Na classe PessoaFacade faço o select para pegar o id, como segue:

package logica;

import logica.AbstractFacade;
import persistencia.Pessoa;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class PessoaFacade extends AbstractFacade<Pessoa> implements PessoaFacadeLocal {
    @PersistenceContext(unitName = "GestaoSaude2-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public PessoaFacade() {
        super(Pessoa.class);
    }
    
    public Integer getIdPessNextval(){
        Query q = getEntityManager().createQuery("select nextval('pessoa_idpess_seq');");
        return (Integer) q.getSingleResult();
    }

}
Mas na contrução da Query apresenta o seguinte erro:
... 32 more
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing the query [select nextval('pessoa_idpess_seq');], line 1, column 14: syntax error at [(].
Internal Exception: MismatchedTokenException(81!=32)

A principio, parece que a sintaxe está correta, mas está dando este erro...
Alguém pode ajudar por favor???

Grato a todos!

Criado 23 de setembro de 2008
Ultima resposta 17 de mar. de 2011
Respostas 5
Participantes 3