hibernate - how to map a joined ResultSet to an object in java? -
i took example here map resultset
object
, , works great, realized problem can't map resultset
join query. example have 2 tables, usr
, vehicle
. select
query , join two.
public class usr { public int id; public vehicle vehicle; } public class vehicle { public int id; public int year; public string model; public int user_id; }
how can map resultset
usr
object? googled bit , found sqlresultsetmapping
might solution, seems lot of work adopt hibernate, , i'm familiar pure java
. example here, looks need rewrite query statements , put db structure in java
.
is there other ways can map joined resultset
object without mess on current code?
edited
the query this;
select * usr join vehicle on usr.id = vehicle.user_id;
and want map usr
object
lets break whole thing in new way. approach following kind of handy comes limitations. handles primitive types of field. classes having association other objects or tables in db foreign key mapping ? case having usr
class in have vehicle
associated relation.
rather doing mapping thing in generic way, write mapping logic in class reuse when necessary.
write rowmapper
abstract class
public abstract class rowmapper<e> { public list<e> processresultset(resultset rs) throws sqlexception { list<e> objectlist = new arraylist<>(); while(rs.next()) { objectlist.add(maprow(rs)); } return objectlist; } abstract e maprow(resultset rs) throws sqlexception;
}
now write row mapping logic theusr
class
public class usrmapper extends rowmapper<usr> { @override public state maprow(resultset rs, int rownum) throws sqlexception { usr usr = new usr(); vehicle vehicle = new vehicle(); usr.setid(rs.getint("usr.id")); vehicle.setid(rs.getint("vehicle.id")); vehicle.setyear(rs.getint("vehicle.year")); vehicle.setmodel(rs.getstring("vehicle.model")); usr.setvehicle(vehicle); return usr; } }
you can have implement rowmapper vehicle
well. way go using this.
say got resultset following join query
select usr.id, vehicle.id, vehicle.year, vehicle.model usr join vehicle on usr.id = vehicle.user_id;
now
usrmapper usrmapper = new usrmapper(); list<usr> usrlist = usrmapper.processresultset(resultset);
wiki
Comments
Post a Comment