Update HIBERNATE[RESOLVIDO]

PESSOAL, estou desenvolvendo uma tela bem simples, que é o seguinte:

SE NAO ENCONTRAR O CPF CADASTRADO NO BANCO DE DADOS, REALIZA O INSERT
(ISSO ESTA FUNCIONANDO )

			System.out.println("insert");
			bdc.salvar(cliente);

SE EMCONTRAR O CPF NO BANCO DE DADOS , REALIZA O UPDATE :

			System.out.println("Editar");
			bdc.alterar(cliente);

(ESTA DANDO O PROBLEMA ABAIXO)

26/09/2012 11:08:47 org.hibernate.util.JDBCExceptionReporter logExceptions
AVISO: SQL Error: 1, SQLState: 23000
26/09/2012 11:08:47 org.hibernate.util.JDBCExceptionReporter logExceptions
GRAVE: ORA-00001: restrição exclusiva (EVANDRO.SYS_C004761) violada

26/09/2012 11:08:47 org.hibernate.util.JDBCExceptionReporter logExceptions
AVISO: SQL Error: 1, SQLState: 23000
26/09/2012 11:08:47 org.hibernate.util.JDBCExceptionReporter logExceptions
GRAVE: ORA-00001: restrição exclusiva (EVANDRO.SYS_C004761) violada

sei que esta dizendo que ja existe esta chave , mas estou dando um UPDATE,

segue meu código:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<title>eTest</title>
</h:head>
<h:body>


<p:growl id="avisos" showDetail="true" life="3000"/>
<p:fieldset legend="Meu Cadastro" toggleable="true">

	<h:form>
		<h1 align="center">HOME PAGE</h1>
		<h:panelGrid columns="2">
		        <h:outputLabel value="Nome"/>
				<p:inputText id="nome" value="#{BeanCliente.cliente.nome}"/>
				
		        <h:outputLabel value="Observações"/>
				<p:inputTextarea value="#{BeanCliente.cliente.observacao}"/>
				
				<h:outputLabel value="Data Cadastro"/>
				<p:calendar value="#{BeanCliente.cliente.datacadastro}"/>
				
				<h:outputLabel value="Telefone:"/>
				<p:inputMask mask="(999)9999-9999" value="#{BeanCliente.cliente.telefone}"/>
						
				<h:outputLabel value="Cpf:"/>
				<p:inputMask mask="999.999.999-99" value="#{BeanCliente.cliente.CPF}"/>
				
    			<h:outputLabel value="Descrição:"/>
    			<p:keyboard layout="qwertyBasic" value="#{BeanCliente.cliente.descricao}"/>
    			
    			<h:outputLabel value="Senha:"/>
    			<p:keyboard password="true" keypadOnly="true" value="#{BeanCliente.cliente.senha}"/>

    			
				
		
		<p:commandButton id="Salvar" value="Salvar" action="#{BeanCliente.Salvar}">
		</p:commandButton>		
		</h:panelGrid>
	</h:form>
</p:fieldset>	
	
</h:body>
</html>

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import banco.HibernateUtil;
import modelo.Cliente;
public class ClienteDao {
	Session session = HibernateUtil.getSession();

	public String mostracliente(String cpf) {
		Query q = session.createQuery("FROM Cliente where CPF=:pnro");
		q.setParameter("pnro", cpf);
		List<Cliente> r = q.list();
		String vnome = null;
		for (Cliente e: r) {
			 vnome = e.getNome();		
		}	
		
		System.out.println("mostracliente "+vnome);
		return  vnome;
	}
}


package bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import dao.ClienteDao;
import banco.BancoDeClientes;
import modelo.Cliente;

@ManagedBean(name = "BeanCliente")
@SessionScoped
public class ClienteBean {
	BancoDeClientes bdc = new BancoDeClientes();
	Cliente cliente = new Cliente();
	ClienteDao clientedao = new ClienteDao();	
	
    public Cliente getCliente(){
        return cliente;
     }

     public void setCliente (Cliente cliente){
        this.cliente = cliente;
     }     
	
	
	public String Salvar(){
		
		System.out.println(cliente.getCPF());     
		String vcpf = cliente.getCPF();
		String vcliente = clientedao.mostracliente(vcpf);
		System.out.println("vcliente "+vcliente);
		if (vcliente == null) {
			System.out.println("insert");
			bdc.salvar(cliente);
		} else{
			System.out.println("Editar");
			bdc.alterar(cliente);
		}
			

//		bdc.salvar(cliente);
		return "sucesso";
		
	}

}


package banco;

import modelo.Cliente;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class BancoDeClientes {

	public void salvar(Cliente u) {
		Session sessao = null;
		Transaction tx = null;
		try {
			sessao = HibernateUtil.getSession();
			tx = sessao.beginTransaction();
			sessao.save(u);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			ex.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	public void alterar(Cliente u) {
		Session sessao = null;
		Transaction tx = null;
		try {
			sessao = HibernateUtil.getSession();
			tx = sessao.beginTransaction();
			sessao.update(u);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			ex.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}


package banco;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory;

	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			AnnotationConfiguration cfg = new AnnotationConfiguration();
			Configuration config = cfg.configure("hibernate.cfg.xml");
			sessionFactory = config.buildSessionFactory();
		}
		return sessionFactory;
	}

	public static Session getSession() {
		Session sessao = getSessionFactory().openSession();
		return sessao;
	}
}


Gostaria mais um vez de uma ajuda de vocÊs

Obrigado

Parece que voce ta tentanto setar um valor nulo em alguma coluna que não pode.

Qual a chave primaria da sua tabela? Ela esta preenchida no momento que vc tenta dar o update?

minha chave primaria é o cpf…lembrando que o insert esta correto …o erro esta na alteração

O conteúdo de uma primary key não pode ser alterado e não pode existir outra igual.

O que eu devo fazer???

Criar uma primary key com nome “id” e a coluna CPF como campo varchar, aceitando null ou não.

Percebi um detalhe , o id é gerado automaticamente, fiz os seguintes passos.
1 - se for inserir um novo registro o ID será : 1
2 - se tentar alterar esse registro IRÁ DAR O ERRO ABAIXO.
3 - se for inserir um novo registro o ID será : 3

Obs. nao estou entendendo pq ele esta pulando essa numeracao sendo que é alteração.

Fiz assim e continua o mesmo erro :

GRAVE: ORA-00001: restrição exclusiva (EVANDRO.SYS_C004761) violada

26/09/2012 19:02:54 org.hibernate.event.def.AbstractFlushingEventListener performExecutions
GRAVE: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)


package modelo;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import banco.BancoDeClientes;


@Entity
@Table (name="TB_CLIENTE")


public class Cliente {
	@Id
	@GeneratedValue
	private Integer id;
	private String CPF;
	private String nome;
	private String descricao;
	private String telefone;
	private Date datacadastro;
	private String observacao;
	private String senha;

Refaz isso igual eu estou passando para você.

Sabe o que acho estranho, é que você pega o objeto cliente direto do form, so que voce da um new Cliente() toda vez, eu não trabalho com JSF, trabalho com JPA, e quando vou alterar algo, eu pego o objeto do form e verifico se ele em um ID no banco, se tiver, eu mando alterar esse MESMO objeto que peguei no form, se nao, aí sim eu do 1 new, o que no seu caso, sempre voce da um new. Voce esta usando que IDE ? sabe usar o modo debug ? se souber, fica mais fácil saber o momento exato onde é gerada a exception.

public String Salvar(){

    Cliente client = getCliente();
    System.out.println(client.getCPF());       
    String vcliente = clientedao.mostracliente(client.getCpf());  
    System.out.println("vcliente "+vcliente);  
    if (vcliente == null) {  
        System.out.println("insert");  
        bdc.salvar(client);  
    } else{  
        System.out.println("Editar");  
        bdc.alterar(client);  
    }  

// bdc.salvar(cliente);
return “sucesso”;

}

Resolvi dessa forma :

	public String Salvar(){
		
		System.out.println(cliente.getCPF());     
		String vcpf = cliente.getCPF();
		String vcliente = clientedao.mostracliente(vcpf);
		System.out.println("vcliente "+vcliente);
		if (vcliente == null) {
			System.out.println("insert");
			bdc.salvar(cliente);
		} else{
			
			cliente.setCPF(cliente.getCPF());
			System.out.println("Editar");
			bdc.alterar(cliente);
		}
		return "sucesso";
		
	}