Merge inserindo um novo registro
Pessoal, tudo blz,
é o seguinte, possuo algumas tabelas q suas chaves são atribuidas manualmente (eu sei q não é legal, mas é necessário), o problema é q quando mudo a chave e mando atualizar através do merge, ele faz é inserir um novo registro com os dados, o q eu posso fazer pra isso não acontecer?
Obrigado
José Filho
Curtidas 0
Respostas
Angelo Santos
19/05/2010
Olá fajo,
Quando vc altera a chave de um registro , o "merge" entende como um novo registro.
Tenta usar o update().
Até.
Quando vc altera a chave de um registro , o "merge" entende como um novo registro.
Tenta usar o update().
Até.
GOSTEI 0
José Filho
19/05/2010
Oi Angelo, blz cara,
bom, é o seguinte, o meu salvar tá assim:
e o atualizar:
[CODE[
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T atualizar(T object) {
getEntityManager().merge(object);
return object;
}
[/CODE]
esqueci de mencionar q estou usando Spring, JPA.
bom, é o seguinte, o meu salvar tá assim:
if (novoRegistro == true) {
empresaDao.salvar(empresa);
FacesUtils.mensErro("Registro Salvo com Sucesso!");
} else {
empresaDao.atualizar(empresa);
FacesUtils.mensErro("Registro Atualizado com Sucesso!");
}
return "sucesso";
e o atualizar:
[CODE[
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T atualizar(T object) {
getEntityManager().merge(object);
return object;
}
[/CODE]
esqueci de mencionar q estou usando Spring, JPA.
GOSTEI 0
José Filho
19/05/2010
Oi Angelo, blz cara,
bom, é o seguinte, o meu salvar tá assim:
e o atualizar:
[CODE[
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T atualizar(T object) {
getEntityManager().merge(object);
return object;
}
[/CODE]
esqueci de mencionar q estou usando Spring, JPA.
bom, é o seguinte, o meu salvar tá assim:
if (novoRegistro == true) {
empresaDao.salvar(empresa);
FacesUtils.mensErro("Registro Salvo com Sucesso!");
} else {
empresaDao.atualizar(empresa);
FacesUtils.mensErro("Registro Atualizado com Sucesso!");
}
return "sucesso";
e o atualizar:
[CODE[
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T atualizar(T object) {
getEntityManager().merge(object);
return object;
}
[/CODE]
esqueci de mencionar q estou usando Spring, JPA.
GOSTEI 0
José Filho
19/05/2010
Desculpe ter colocado 2 vezes, é q na 1ª tava aparecendo um erro estranho de asp, pensei q era o navegador, mas abri em outra e a mesma mensagem de erro era mostrada ai respondi de novo, então apareceu a anterior correta, super estranho.
GOSTEI 0
Dyego Carmo
19/05/2010
Realmente , voce nao vai conseguir fazer isto...
utilize o comando UPDATE mesmo... (o JPA suporta o comando UPDATE)
Trocar chaves de tabela alem de nao ser comum não é algo indicado..
utilize o comando UPDATE mesmo... (o JPA suporta o comando UPDATE)
Trocar chaves de tabela alem de nao ser comum não é algo indicado..
GOSTEI 0
José Filho
19/05/2010
Dyego, tentei fazer o q vc disse, trocar o merge por update, mas não deu certo:
The method update(T) is undefined for the type EntityManager.
E agora?
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T atualizar(T object) {
getEntityManager().update(object);
return object;
}
The method update(T) is undefined for the type EntityManager.
E agora?
GOSTEI 0
Dyego Carmo
19/05/2010
troque:
public T atualizar(T object) {
getEntityManager().update(object);
return object;
}
para:
public <T> T atualizar(T object) {
getEntityManager().update(object);
return object;
}
e teste
public T atualizar(T object) {
getEntityManager().update(object);
return object;
}
para:
public <T> T atualizar(T object) {
getEntityManager().update(object);
return object;
}
e teste
GOSTEI 0
José Filho
19/05/2010
Dyego, quando coloquei o q vc disse deu erro, vou colocar a classe toda:
e o erro:
@Transactional(readOnly=true,propagation=Propagation.REQUIRED)
public class DaoGenericoImp<T,ID extends Serializable> implements DaoGenerico<T, ID> {
private EntityManager entityManager;
private final Class<T> oClass;
@SuppressWarnings("unchecked")
public DaoGenericoImp(){
this.oClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public <T> T atualizar(T object) {
getEntityManager().update(object);
return object;
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public void excluir(T object) {
object = getEntityManager().merge(object);
getEntityManager().remove(object);
}
@Override
public Class<T> getObjectClass() {
return this.oClass;
}
@SuppressWarnings("unchecked")
@Override
public List<T> listPesq(String query) {
Query q = getEntityManager().createQuery(query);
return q.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<T> listPesqParam(String query, Map<String, Object> params) {
Query q = getEntityManager().createQuery(query);
for(String chave:params.keySet()){
q.setParameter(chave, params.get(chave));
}
return q.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<T> listPesqParam(String query, Map<String, Object> params,
int maximo, int atual) {
Query q = getEntityManager().createQuery(query).setMaxResults(maximo).setFirstResult(atual);
for(String chave:params.keySet()){
q.setParameter(chave, params.get(chave));
}
return q.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public T pesqParam(String query, Map<String, Object> params) {
Query q = getEntityManager().createQuery(query);
for(String chave : params.keySet()){
q.setParameter(chave, params.get(chave));
}
try{
return (T)q.getSingleResult();
}catch(NoResultException nre){
return null;
}
}
@Override
public T pesquisarPorId(ID id) {
return (T)getEntityManager().find(oClass, id);
}
@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public T salvar(T object) {
getEntityManager().clear();
getEntityManager().persist(object);
return object;
}
@SuppressWarnings("unchecked")
@Override
public List<T> todos() {
String queryS = "SELECT obj FROM "+oClass.getSimpleName();
Query query = getEntityManager().createQuery(queryS);
return query.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<T> todos(int ordem) {
String queryS = "SELECT obj FROM "+oClass.getSimpleName()+" obj ORDER BY "+ordem;
Query query = getEntityManager().createQuery(queryS);
return query.getResultList();
}
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.entityManager = em;
}
public EntityManager getEntityManager() {
if (entityManager == null)
throw new IllegalStateException("Erro");
return entityManager;
}
}
e o erro:
Multiple markers at this line - The method atualizar(T) of type DaoGenericoImp<T,ID> must override or implement a supertype method - Name clash: The method atualizar(T) of type DaoGenericoImp<T,ID> has the same erasure as atualizar(T) of type DaoGenerico<T,ID> but does not override it - The type parameter T is hiding the type T
GOSTEI 0
Dyego Carmo
19/05/2010
Voce não esta repetindo os SUPERCAT METHODS ?
GOSTEI 0
José Filho
19/05/2010
Só entendi a parte do repetindo, hehehe, não entendi o q são os SUPERCAT METHODS.
Mas não, não repeti nenhum metodo de salvamento.
GOSTEI 0
Carlos Mazzi
19/05/2010
Dyego, tbm desconheco esse termo SUPERCAT method...o que é?
GOSTEI 0
Dyego Carmo
19/05/2010
Troque:
public <T> T atualizar(T object) {
getEntityManager().update(object);
return object;
}
por:
public <T> T atualizar(T object) {
return getEntityManager().update(object);
}
e teste por favor :)
SUPERCAT METHODS = Uma implementação de superclasse.
public <T> T atualizar(T object) {
getEntityManager().update(object);
return object;
}
por:
public <T> T atualizar(T object) {
return getEntityManager().update(object);
}
e teste por favor :)
SUPERCAT METHODS = Uma implementação de superclasse.
GOSTEI 0