Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate JPA : ignore wrong sql foreign key values

I have a project to maintain, The persistance layer of this project uses JPA and Hibernate and it is running on a MySQL server, the database is not relational and the engine is MyISAM on all tables.

I have some foreignkey relationshps mapped as @ManyToOne relationship on my entities.

Now the problem is that some of those columns are supposed to be foreignkeys in order to be mapped right, but they aren't (since the engine is MyISAM, and the DB is only relational on theory), some of these columns have wrong values like (negative ones -1 , 0 , inexistant dead parents).

@Entity
public class EntityA {

   @ManyToOne
   @JoinColumn(name="COL_FK")
   private EntityB b;

}

In the DB, Possible values for COL_FK are : 0,-1,DEAD PARENTS

I can't neither change the db structure nor edit the the data within the columns.All I can do is change the code.

How can I tell Hibernate to ignore those values and not throw a RuntimeException while I'm getting list just because one of its element contains a wrong foreingkey value.

Thanks.

UPDATE:

@Embeddable
public class EntityA {
    @ManyToOne()
    @JoinColumn(name = "idClient")
    @NotFound(action = NotFoundAction.IGNORE)
    private ClientBO idClient;

}

StackTrace :

AVERTISSEMENT: org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find xx.xxx.xx.xxx.ClientBO with id 210; nested exception is javax.persistence.EntityNotFoundException: Unable to find xx.xx.xx.xxx.ClientBO with id 210
like image 340
Rafik BELDI Avatar asked Aug 06 '15 15:08

Rafik BELDI


1 Answers

Annotate your association with

@NotFound(action=NotFoundAction.IGNORE)

Note that this is one more hack on top of an already ugly solution though. Hibernate heavily relies on transactions (as it should) and MyISAM, AFAIK, doesn't support transactions. I guess you already knows it, but fixing the database would be a much better choice.

like image 171
JB Nizet Avatar answered Sep 18 '22 19:09

JB Nizet