Roberto de Santis
Roberto de Santis

Reputation: 858

DataAccessException doesn't work

i have set in my applicationContext

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

and I try to catch the DataAccessException in ManagedBean. I have BusinessDelegate where i set @Transactonal.

The problem is:

    try
    {
        operazioneOk = businessDelegate.insertAuto(newAuto);
    }
    catch (DataAccessException e)
    {
        System.out.println("autoBean");
    }

the catch, work even if i don't set
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

but the strange thing is that in the console i have this exception:

AVVERTENZA: SQL Error: 0, SQLState: null
GRAVE: L'operazione «batch» 0 insert into public.auto (marca, modello, anno, km, cilindrata, optional, prezzo, occasione, id) values (w, ww, w, w, w, w, w, 0, 12) è stata interrotta. Chiamare «getNextException» per scoprirne il motivo.
AVVERTENZA: SQL Error: 0, SQLState: 23505
GRAVE: ERROR: duplicate key value violates unique constraint "auto_marca_key"
  Dettaglio: Key (marca)=(w) already exists.
GRAVE: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

In the both case. I think that something doesn't working. Help me!

Upvotes: 1

Views: 2520

Answers (2)

Roberto de Santis
Roberto de Santis

Reputation: 858

Ok, i have solved the problem myself.

The solution is setting the @Transactional propagation. This is the method in my BusinessDelegate(SessionFacade):

@Override
@Transactional
public boolean insertAuto(Auto auto)
{
    try
    {
        return (autoDao.create(auto) != null);
    }
    catch (DataAccessException e)
    {
        System.out.println("aa");
    }
    return false;
}

while in DAO i must set:

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public PK create(T istance) throws DataAccessException
{
    return (PK) sessionFactory.getCurrentSession().save(istance);
}

now everything work fine. If someone see any problem in this approach please advice me.

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120198

the error from the stack trace is

duplicate key value violates unique constraint "auto_marca_key"
  Dettaglio: Key (marca)=(w) already exists.

you are inserting a row that contains a column value that violates a unique constraint.

Upvotes: 2

Related Questions