java - JDBC Template - One-To-Many -
i have class looks this. need populate 2 database tables, shown below. there preferred way this?
my thought have service class select list<>
via resultsetextractor
dao. foreach
on list, , select list<>
of emails individual person via resultsetextractor
, , attach foreach
loop.
is there better way, or gets?
public class person { private string personid; private string name; private arraylist<string> emails; } create table person ( person_id varchar2(10), name varchar2(30) ); create table email ( person_id varchar2(10), email varchar2(30) );
this best solved orm. jdbc, have hand orm you. executing n + 1 queries inefficient. should execute single query, , build objects manually. cumbersome, not hard:
select person.id, person.name, email.email person person left join email on person.id = email.person_id ... map<long, person> personsbyid = new hashmap<>(); while (rs.next()) { long id = rs.getlong("id"); string name = rs.getstring("name"); string email = rs.getstring("email"); person person = personsbyid.get(id); if (person == null) { person = new person(id, name); personsbyid.put(person.getid(), person); } person.addemail(email); } collection<person> persons = personsbyid.values();
Comments
Post a Comment