Ibatis is not a full ORM framework, so it doesnt know about objects relationships.
So yes, you must write something like your INSERT if you want to work directly with domain objects that do not fully correspond to a record in your table; that is, if the User object you are mapping in Ibatis does not have a getUsertypeId()
method (that returns the value corresponding to the table column usertype_id ) but instead a getUserType()
method.
(Of course you can also write a getUsertypeId()
method which internally calls getUserType().getId()
... but just stop here and don't pretend to make also a setUserTypeId(int id
) which internally tries to load the UsertypeId from the Db, etc, etc... that calls for trouble. You'll end reinventing JPA/Hibernate.)
I don't think a TypeHandler is the right approach, that feature is more oriented to converting non-trivial types, not so much for handling relationships.
Another valid approach is to have a layer of relatively low-level-dumb POJOs with properties that map to your table columns (i.e., a UserDb
object with a userTypeId
property and no getUserType()
method, and no bussiness intelligence, dependencies on upper layers or persistence knowledge), and then, on top of that, a layer of "real" domain objects, each of which wraps a (usually small) graph of those "dumb" objects, and has the intelligence necessary for calling the DAO to load/save the graph (perhaps lazily).
One advantage of this approach is that the core of actual ibatis mappings (the SQL coding) can be done fairly automatically with Ibator - it even creates the code of the Java classes from the DB schema.
For massive reads of data which involves many tables (reports), you can use ad-hoc POJO (which corresponds directly to the columns of your SELECT)... or even HashMaps.
PS: You might want to read about DDD (and concepts like "Entities", "Value objects", "Views", "contexts" "rich domain object" vs "anemic domain objects" eg). Ibatis gives you much flexibility to learn and implement along this lines.