Question

Scenario: I have a JSF 2.1 webapp running on a tomcat server, with hibernate implementing the jpa interface and mysql database.
Users of the webapp are registered as an Entity on the database, and there are a group of data called Rooms, that have their own Entity, where users have access as proprietary or as external managers. To save the concept of "external management" on the database i have a proper Entity for every management; the external management are saved as a OneToMany relathionship on the User Entity.

Here you have the Hibernate dependencies as they were added to the pom.xml of the project:

  <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>4.3.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.0.Final</version>
    </dependency>

Problem: For some odd reason, adding the code for a foreign key to the managed room in the External Management Entity with a ManyToOne relationship, breaks up Hibernate: any update to the list of external management property on the User, when that foreign key is present, throws RollbackException - "Transaction marked as rollback only":

Caused by: it.katuiros.core.db.dao.DataAccessException: Data Access error while doing final commit.
at it.katuiros.core.db.dao.impl.GenericDaoImpl.closeDataAccess(GenericDaoImpl.java:222)
at it.katuiros.core.db.dao.impl.GenericDaoImpl.update(GenericDaoImpl.java:96)
at it.katuiros.appLogic.PersistenceTest.saveTestData(PersistenceTest.java:157)
at it.katuiros.beans.generics.TestBean.<init>(TestBean.java:44)
... 67 more

Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:74)
at it.katuiros.core.db.dao.impl.GenericDaoImpl.closeDataAccess(GenericDaoImpl.java:217)
... 70 more

As you probably know, the sad thing about those RollbackException in Hibernate is that they are UNDEBUGGABLE!

CODE
the User entity:

@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User extends DataModelEntity {
    /**
     * Serialization ID
     */
    private static final long serialVersionUID = -1154710247841840471L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    @Column(name = "ID")
    protected int id;

    @NotNull
    @Column(name = "USERNAME", unique = true)
    protected String username;

    @NotNull
    @Column(name = "PASSWORD")
    protected String password;

    @NotNull
    @Column(name = "EMAIL", unique = true)
    protected String email;

    @Column(name = "FIRST_NAME")
    protected String firstName;

    @Column(name = "LAST_NAME")
    protected String lastName;

    @Column(name = "PHONE")
    protected String telefono;

    @ManyToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    @Basic(optional = false)
    @JoinColumn(name = "FAVORITE_ROOMS", referencedColumnName = "ID", updatable = true)
    protected Set<Room> favoriteRooms;

    @OneToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    @Basic(optional = false)
    @JoinColumn(name = "REGISTERED_ROOMS", referencedColumnName = "ID", updatable = true)
    protected Set<Room> registeredRooms;

    @OneToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    @Basic(optional = true)
    @JoinColumn(name = "EXTERNAL_MANAGEMENTS", referencedColumnName = "ID", updatable = true)
    protected Set<ExternalRoomManagementPermissions> externalManagements;

    @OneToOne
    @JoinColumn(name = "AVATAR", referencedColumnName = "ID", updatable = true)
    protected Image avatar;

    ... constructors and getters/setters ...
}

The External Management Entity

@Entity
@Table(name = "EXTERNAL_ROOM_MANAGEMENT_PERMISSIONS")
@Access(AccessType.FIELD)
public class ExternalRoomManagementPermissions extends DataModelEntity {

    /**
     * Serialization ID
     */
    private static final long serialVersionUID = 7122195658297760351L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    @Column(name = "ID")
    private int id;

    /* CRIMINAL CODE */
    @ManyToOne
    @NotNull
    @JoinColumn(name = "MANAGED_ROOM", referencedColumnName = "ID")
    private Room managedRoom;
    /* END OF CRIMINAL CODE */

    ... constructors and getters/setters ...
}

I will not post the Room Entity code, as it is not so important.

This the Data Access Object that is used to update the Entity

public abstract class GenericDaoImpl<T> implements GenericDao<T> {

protected EntityManager em;

private Class<T> type;

public GenericDaoImpl() {
    Type t = getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) t;
    type = (Class) pt.getActualTypeArguments()[0];
    this.em=null;
}

protected void finalize() throws Throwable{
    this.closeDataAccess();
    super.finalize();
}

/* DATA ACCESS LOGICS */
/* BASIC CRUD OPERATIONS */ 

@Override
public void create(final T t)  throws DataAccessException  {
    try{
        this.startDataAccess();
        this.em.persist(t);
    }catch(Exception e){
        throw new DataAccessException("Data Access error while persisting Object.", e);
    }finally{
        this.closeDataAccess();
    }
}

@Override
public void delete(final Object id)  throws DataAccessException {
    try{
        this.startDataAccess();
        this.em.remove(this.em.getReference(type, id));
    }catch(Exception e){
        throw new DataAccessException("Data Access error while removing Object.", e);
    }finally{
        this.closeDataAccess();
    }
}

@Override
public T find(final Object id)  throws DataAccessException {
    T result = null;
    try{
        this.startDataAccess();
        result = (T) this.em.find(type, id);
    }catch(Exception e){
        throw new DataAccessException("Data Access error while finding Object.", e);
    }finally{
        this.closeDataAccess();
    }
    return result;
}

@Override
public T update(final T t) throws DataAccessException {
    T result = null;
    try{
        this.startDataAccess();
        result = (T) this.em.merge(t);
    }catch(Exception e){
        throw new DataAccessException("Data Access error while updating Object.", e);
    }finally{
        this.closeDataAccess();
    }
    return result;
}

/* MORE OPERATIONS */

/**
 * Method that returns the number of entries from a table that meet some
 * criteria (where clause params)
 *
 * @param params
 *            sql parameters
 * @return the number of records meeting the criteria
 */
@Override
public long countAll(final Map<String, Object> params) throws DataAccessException {
    long result = -1;

    try{
        this.startDataAccess();
        final StringBuffer queryString = new StringBuffer(
                "SELECT count(o) from ");

        queryString.append(type.getSimpleName()).append(" o ");
        queryString.append(this.getQueryClauses(params, null));

        final Query query = this.em.createQuery(queryString.toString());

        result = (Long) query.getSingleResult();
    }catch(Exception e){
        throw new DataAccessException("Data Access error while counting Object.", e);
    }finally{
        this.closeDataAccess();
    }

    return result;
}

/**
 * This method returns the whole list of all T entities available on the datasource.
 * 
 * @return the whole list of all T entities.
 */
@Override
public List<T> list()  throws DataAccessException {
    List<T> resultList = null;

    try{
        this.startDataAccess();
        final StringBuffer queryString = new StringBuffer("SELECT o from ");

        queryString.append(type.getSimpleName()).append(" o ");

        final Query query = this.em.createQuery(queryString.toString());

        resultList =(List<T>) query.getResultList();
    }catch(Exception e){
        throw new DataAccessException("Data Access error while retrieving list of Objects.", e);
    }finally{
        this.closeDataAccess();
    }

    return resultList;
}

/* MISCELLANEOUS UTILITY METHODS */

protected String getQueryClauses(final Map<String, Object> params,
        final Map<String, Object> orderParams) {
    final StringBuffer queryString = new StringBuffer();
    if ((params != null) && !params.isEmpty()) {
        queryString.append(" where ");
        for (final Iterator<Map.Entry<String, Object>> it = params
                .entrySet().iterator(); it.hasNext();) {
            final Map.Entry<String, Object> entry = it.next();
            if (entry.getValue() instanceof Boolean) {
                queryString.append(entry.getKey()).append(" is ")
                        .append(entry.getValue()).append(" ");
            } else {
                if (entry.getValue() instanceof Number) {
                    queryString.append(entry.getKey()).append(" = ")
                            .append(entry.getValue());
                } else {
                    // string equality
                    queryString.append(entry.getKey()).append(" = '")
                            .append(entry.getValue()).append("'");
                }
            }
            if (it.hasNext()) {
                queryString.append(" and ");
            }
        }
    }
    if ((orderParams != null) && !orderParams.isEmpty()) {
        queryString.append(" order by ");
        for (final Iterator<Map.Entry<String, Object>> it = orderParams
                .entrySet().iterator(); it.hasNext();) {
            final Map.Entry<String, Object> entry = it.next();
            queryString.append(entry.getKey()).append(" ");
            if (entry.getValue() != null) {
                queryString.append(entry.getValue());
            }
            if (it.hasNext()) {
                queryString.append(", ");
            }
        }
    }
    return queryString.toString();
}

protected void startDataAccess() throws DataAccessException{
    this.em = ContextEMF.createEntityManager();
    if (this.em==null) throw new DataAccessException("No Entity Manager was created! Check if ContextEMF is correctly working.");
    this.em.getTransaction().begin();
}

protected void closeDataAccess() throws DataAccessException{
    if (this.em!=null){
        try{
            if (this.em.isOpen()){
                this.em.getTransaction().commit();
                this.em.clear();
                this.em.close();
            }
        }catch(Exception e){
            throw new DataAccessException("Data Access error while doing final commit.", e);
        }           
        this.em=null;
    }
}

}

and this is the piece of code where the user with a set of external managements is updated on the database and the exception is thrown:

this.externalManagement1 = new ExternalRoomManagementPermissions(this.room4);
this.dbAccessor.saveData(this.externalManagement1);
this.externallyManagedRoomsForUser1.add(this.externalManagement1);
this.user1.setRegisteredRooms(this.registeredRoomsForUser1);
this.user2.setRegisteredRooms(this.registeredRoomsForUser2);
userDao.update(this.user1);
userDao.update(this.user2);
this.user1.setExternalManagements(this.externallyManagedRoomsForUser1);

userDao.update(this.user1);  // <---- EXPLODING LINE

The last two lines are the critical step: if the External Management Entity has that "criminal code" about the ManyToOne relationship to the managed room, the userDao.update(...) will throw the exception; if the "criminal code" is omitted, the userDao.update(...) will NOT throw the exception.

(The room has already been previously persisted to the database before i use it in that last code segment)

Sumptum: I have a many-to-one relationship on ExternalRoomManagementPermissions that has a single Room as child, and a one-to-many on the User that has a collection ExternalRoomManagementPermissions children. As i have explained the presence of the first relationship (external management to room) in the code - the "Criminal code"- makes the User unable to be updated with the collection of ExternalRoomManagementPermissions (the second relationship).

Question: sadly i need that ManyToOne relationship to the managed room, do you know why it breaks the persistence up?

Post-Scriptum: i tried to change the ManyToOne relationship to a OneToOne but it had no effect.

Was it helpful?

Solution

OK!

I think i've found the problem through intensive debug and extensive use of breakpoints... i've never went so much down in debugging in my whole life as a programmer! The causing error was incredibly stupid:

   "org.hibernate.InstantiationException: No default constructor for entity: : it.katuiros.model.entities.ExternalRoomManagementPermissions"

Somehow the exception was launched inside the Hibernate layer and swallowed in the same place, that's why the RollbackException did not bear any cause in itself. I will probably post a bug signalation on Hibernate forum/groups.

By adding the default empty constructor to the ExternalRoomManagementPermissions i've managed to make the code work:

public ExternalRoomManagementPermissions(){
    super();
}

Big thanks to Tim Holloway from coderanch, Mabi and James Massey from stackoverflow for the help!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top