Postgree select de uma sequence

2 respostas
S

Ola
tenho uma sequence em oracle e consigo recuperar a sequencia com o seguinte select :
SELECT seq_cadcli.nextval from dual

Gostaria de saber como faco com postgree?

Grato

Silva

2 Respostas

M

select nextval((‘gpa.seq_cod_projetos’))

gpa -> nome da minha database.
.seq_cod_projetos nome da sequence.

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...
Estou usando 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"),
    })
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;
    @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) {
        this.idPess = idPess;
        this.nomePess = nomePess;
        this.sexoPess = sexoPess;
    }

    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 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 1 de novembro de 2006
Ultima resposta 17 de mar. de 2011
Respostas 2
Participantes 3