简体   繁体   中英

Spring hibernate - handling exceptions per row in table

We have limited control over the values in our database for a given table that we have an Entity for. When a single row is inserted with invalid data, an exception ends up being thrown during the query. This exception prevents all rows from being deserialized. Is there a way to handle exceptions like this in a manner that doesn't effect all rows?

I'm afraid that is not possible, because there is some collateral effects if it was possible.

Per example, if you try to paginate using your idea the count result will be different from the number of entity results returned:

// all rows will be count, with problem or not
select count (*) from Person 

// will ignore the problematic rows and bring less results than the count
select p From Person p 

The best alternative seems be more flexible and bring to your code the complexity, being more flexible in your entity mapping.

Per example, if you are having problems with your Enumerator because there are invalid values for enumerator in the database, it's better map the column as String instead of Enumerator and deal with the problem in your code.

So, if you have something like this:

@Column(name = "status", nullable = false, length = 30)
@Enumerated(EnumType.STRING)
private Status status;

Change to:

@Column(name = "status", nullable = false, length = 30)
private String status;

And ignore the results on your code. With this flexibility you can also ignore the problematic results on the query. Like:

SELECT p FROM Person p WHERE status NOT IN (:validStatusAsString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM