Problema pra gravar com composite id - arquitetura mvc

3 respostas
C

olá

por favor, estou precisando bastante da ajuda de vcs… pesquisei e não achei situação q fosse parecida com a minha… então é o seguinte:

tenho a classe situacaoTributaria, com id_situacao_tributaria, cod e descricao;

tenho a classe estado, com id_estado, sigla e nome;

tenho a classe icms, com chaveComposta e porcentagem;

e a classe pk, com id_estado e id_situacao_tributaria

tenho os managers da situacaoTributaria e do icms, assim como os daos respectivos.

qdo vou cadastrar situacaoTributaria, mando tb gravar a lista de icms… é aí q está o problema…
se eu colocar os dados na mão (como teste) no serviço gravar , ele grava blz.
Mas qdo insiro a situacao e tento inserir os icms (dentro do mesmo serviço) - seja pelo manager ou pelo dao do icms dentro do manager da situacao tributaria, ele retorna este erro:

org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [XXXXX.ICMSEntity#XXXXXX.ICMSPK@7339be] at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:377) at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:223) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:187) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:815) at org.hibernate.event.def.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:229) at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:120) at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:53) at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:677) at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:661) at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:665)

estou trabalhando com swingbean, spring e hibernate annotations. Não sou experiente, então me perdoem qq coisa…
e desde já agradeço a colaboração.

3 Respostas

C

alooww.... alguém???

bom, estou mandando as classes em questão...

situacaoTributaria:
@Entity
@Table(name = "tb_situacao_tributaria")
@SequenceGenerator(name = "seqSituacao_Tributaria" , sequenceName="sq_id_situacao_tributaria", allocationSize=1)
public class SituacaoTributariaEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqSituacao_Tributaria")
    private Integer id_situacao_tributaria;
    
    @NotEmpty
    @Length(max=4)
    private String codigo;
    
    @Length(max=30)
    private String descricao;
    
    private String justificativa;
   //getters e setters
icms:
@Entity
@Table(name="tb_icms")
public class ICMSEntity implements Serializable {
    @EmbeddedId
    @NotNull
    private ICMSPK chaveComposta;

    private Double percentual;
    @Column(name="percentual_reducao")
    private Double percentualReducao;
   //getters e setters
icmspk:
@Embeddable
public class ICMSPK implements Serializable {

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="id_estado")
    private EstadoEntity estado; 
    
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="id_situacao_tributaria")
    private SituacaoTributariaEntity situacaoTributaria;
    //getters e setters
e o metodo para gravar/ alterar no manager da situacaoTributaria:
public SituacaoTributariaEntity atualizaSituacaoTributaria(SituacaoTributariaEntity situacaoTributaria, 
                                                               List<ICMSEntity> listaICMS) {
        SituacaoTributariaEntity aux = null;
        
        try {
            aux = this.inicializaSituacaoTributaria(situacaoTributaria);
        } catch (CpadiException e) { }
        
        if (aux == null) 
            aux = this.situacaoTributariaDAO.incluiSituacaoTributaria(situacaoTributaria);
        else
            aux = this.situacaoTributariaDAO.alteraSituacaoTributaria(situacaoTributaria);
        
        for (int i=0; i<listaICMS.size(); i++) {
            listaICMS.get(i).getChaveComposta().setSituacaoTributaria(aux);
            this.atualizaICMS(listaICMS.get(i));
        }
        
        return aux;
    }
    
    private void atualizaICMS(ICMSEntity icms) {
        ICMSEntity aux = null;
        if (icms != null && icms.getChaveComposta() != null)
        try {
            aux = icmsDAO.pesquisaICMSPorPK(icms);
        } catch (CpadiException ex) { }
        
        if (aux == null)
            icmsDAO.incluiICMS(icms);
        else
            icmsDAO.alteraICMS(icms);
    }
dao do icms:
public class ICMSDAOHBImpl implements ICMSDAO {

    private SessionFactory sf;

    public SessionFactory getSessionFactory() {
        return sf;
    }

    public void setSessionFactory(SessionFactory sf) {
        this.sf = sf;
    }
    
    public ICMSEntity incluiICMS(ICMSEntity icms) {
        ICMSEntity aux = new ICMSEntity();
        BeanUtils.copyProperties(icms, aux);
        sf.getCurrentSession().save(aux);
        return aux;
    }

    public ICMSEntity alteraICMS(ICMSEntity icms) {
        ICMSEntity aux = new ICMSEntity();
        BeanUtils.copyProperties(icms, aux);
        sf.getCurrentSession().merge(aux);
        return aux;
    }

    public ICMSEntity pesquisaICMSPorPK(ICMSEntity icms) {
       try {
           
            return (ICMSEntity) sf.getCurrentSession().load(ICMSEntity.class, icms.getChaveComposta());
           
        } catch (ObjectNotFoundException ex) {
            throw new CpadiObjectNotFoundException();
        }
    }
    
    public void excluiICMS(ICMSEntity icms) {
        sf.getCurrentSession().delete(icms);
    }
}

//dao da situacaoTributaria segue a mesma lógica...

C

fungou... segue as alterações:

no manager da situacaoTributaria
private void atualizaICMS(ICMSEntity icms) {
        ICMSEntity aux = null;
        if (icms != null && icms.getChaveComposta() != null) {
            try {
                aux = icmsDAO.pesquisaICMSPorPK(icms);
            } catch (CpadiException ex) { }
            
            icms.getChaveComposta().setEstado(this.inicializaEstado(icms.getChaveComposta().getEstado()));
            icms.getChaveComposta().setSituacaoTributaria(this.inicializaSituacaoTributaria(icms.getChaveComposta().getSituacaoTributaria()));
        }
        
        if (aux == null)
            icmsDAO.incluiICMS(icms);
        else
            icmsDAO.alteraICMS(icms);
    }
no dao do icms
public ICMSEntity pesquisaICMSPorPK(ICMSEntity icms) {
       Criteria criteria = sf.getCurrentSession().createCriteria(ICMSEntity.class);
       ICMSEntity aux = null;
        try {
            criteria.add(Restrictions.and(Restrictions.eq("chaveComposta.estado", icms.getChaveComposta().getEstado()),
                    Restrictions.eq("chaveComposta.situacaoTributaria", icms.getChaveComposta().getSituacaoTributaria())));
            aux = (ICMSEntity) criteria.uniqueResult();
            return aux;
        
      //      return (ICMSEntity) sf.getCurrentSession().load(ICMSEntity.class, icms.getChaveComposta());
           
        } catch (ObjectNotFoundException ex) {
            throw new CpadiObjectNotFoundException();
        }
    }
pimentaft

Fala ai, blz!
Eu estava vagando pelo google procurando uma solução pro meu problema e achei teu topico aqui no guj com um problema parecido com o meu.
Se vc puder e qdo puder vc pode me ajudar:

Vide o link:

http://www.guj.com.br/posts/list/112604.java

Vlw!

Criado 27 de junho de 2008
Ultima resposta 12 de dez. de 2008
Respostas 3
Participantes 2