java - How to not crash if a foreign key refers to a null row while the key is not nullable? -
i have table "regions":
id | name | parent_id
1 | whatever | 100000
where parent_id should self referencing id, meaning row geographically belongs 100000.
however due data being imported @ beginning dirty, row id 100000 doesn't exist.
therefore in given entity:
@entity("regions") public class region { private int id; private string name; private region parent; ... @manytoone() @joincolumn(name = "parent_id") public region getparent() { return parent; } public void setparent(region parent) { this.parent = parent; } } when list hibernate:
session session = sessionhandler.getsession(); //gets current session transaction tx = session.begintransaction(); try { return (list<t>)session.createquery("from regions").list(); } catch(hibernateexception ex) { ex.printstacktrace(); if (tx!=null) tx.rollback(); throw ex; }finally { sessionhandler.close(); } it throw exception:
org.hibernate.objectnotfoundexception: no row given identifier exists: [whatever.entities.region#6046193] which indicates region of id 6046193 doesn't exist. explained before, expect happen.
my questions, given can't edit parent_id column nullable, way handle exception system ignores exception , keeps program going?
you try set fetch type of many 1 relationship lazy.
... @manytoone(fetch = fetchtype.lazy) @joincolumn(name = "parent_id") public region getparent() { return parent; } ... i guess hibernate not throw error during "select all", , can handle error when first call getter, if that.
but not 100% sure if works, , i don't think solution. think should sanitize data during/after import.
if not sanitize data, you'll have keep workarounds problems in code forever. if, in future, removes fetch = fetchtype.lazy, because think lead better performance? application break in unexpected way, because entities not reflect correctly in database.
you said cannot set parent_id null since column not nullable. creating dummy entries missing ids? right after importing dirty data, before start application first time.
also, changing column nullable (assuming can that, moment) won't work anyway. still have sanitize data - in case, have set parent_ids null when row referenced id not exist.
Comments
Post a Comment