Opa 
Existe algum metodo do hibernate que eu descubra o proximo ID valido antes de salvar um registro no banco de dados?
[]'s
Opa 
Existe algum metodo do hibernate que eu descubra o proximo ID valido antes de salvar um registro no banco de dados?
[]'s
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
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.
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.
Eu ja dei uma olhada no link e a unica que funcionou foio nextval. O currval nao funcionou aqui.
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:
[code]
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 usuarioCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = âpessoaâ)
private Collection 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 + "]";
}
}[/code]
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();
}
}[/code]
Mas na contrução da Query apresenta o seguinte erro:
[code]... 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!