Data deletion via Hibernate

2

In the database used by my application I have a table that I defined as temporary that I write some data but at the end of the process I no longer need the information registered in that table, how should I make this table be cleaner would it be more useful to carry out a process via the database or the application itself should take care of it.?

I use Hibernate and tried some situations but I can do em.remove(temp); from a defined object, not all content.

An example of how I search the bank:

 public EntityManager getEntityManager() {
    return ConexaoJPA.getEntityManager();
}

public List find(int id) {

    EntityManager em = getEntityManager();
    try {

        Query q = em.createQuery("from Temp where cod=" + id + "");

        return (List<Temp>) q.getResultList();

    } finally {
        em.close();
    }
}
    
asked by anonymous 29.12.2015 / 12:05

3 answers

2

If you want to use remove , you can use something like this:

Temp temp = new Temp();
temp.setId(1);
getEntityManager().remove(temp);

In this case the object must be in the session, otherwise a org.hibernate.PersistentObjectException: detached entity will be raised, something like this, I do not remember right now:)

Using JPQL you can use something like this:

getEntityManager()
    .createQuery("delete from Temp t where t.id = :id")
    .setParameter("id", id)
    .executeUpdate();
    
29.12.2015 / 14:32
1

Try this:

public int truncate(String nomeTabela){
    Query query = session.createSQLQuery('truncate table ' + nomeTabela);
    return query.executeUpdate();
}

'

    
29.12.2015 / 12:23
1
@Resource
UserTransaction utc;

@PersistenceContext(unitName = "xyz")
EntityManager em;

try {
    utx.begin();

    Query q1 = em.createNativeQuery("DELETE FROM tabela");

    q1.executeUpdate();

    utc.commit();
} catch (NotSupportedException | SystemException | SecurityException | IllegalStateException | RollbackException | HeuristicMixedException | HeuristicRollbackException e) {
    e.printStackTrace();
}
    
29.12.2015 / 12:52