Java SpringJDBCTemplate:在RowMapper中调用DAO方法可以吗?
假设我们在一个对象中有一个对象。假设我们有一个数据库表car,它引用了一个owner\u id和owner表 我们的域对象car引用人:Java SpringJDBCTemplate:在RowMapper中调用DAO方法可以吗?,java,spring,dao,Java,Spring,Dao,假设我们在一个对象中有一个对象。假设我们有一个数据库表car,它引用了一个owner\u id和owner表 我们的域对象car引用人: public class Car { public class Person person; } 因此,假设我们有一个车用DAO和一个人用DAO,可以在CarDao内部自动连接PersonDao,并从CarDao的RowMapper中查询人并将其添加到Car对象中吗?我对此进行了测试,它确实有效,但我想问的是,它是否被认为是糟糕的形式或做法,以及原因
public class Car {
public class Person person;
}
因此,假设我们有一个车用DAO和一个人用DAO,可以在CarDao内部自动连接PersonDao,并从CarDao的RowMapper中查询人并将其添加到Car对象中吗?我对此进行了测试,它确实有效,但我想问的是,它是否被认为是糟糕的形式或做法,以及原因。我肯定会将其归类为糟糕的形式,因为数据库调用应该是单数形式 您可以尝试单独调用DAO,并从两个调用中组合Car实例
List<Car> cars = carDao.getCars();
List<Person> people = personDao.getPeople();
for (int i=0; i<cars.size(); i++){
cars.get(i).setPerson(people.get(i));
}
List cars=carDao.getCars();
List people=personDao.getPeople();
对于(int i=0;iIMO),这不是一个好的做法。如果要从数据库中提取一对多关系,可以使用ResultSetExtractor
public class MasterDetailResultSetExtractor implements ResultSetExtractor {
@Override
public Object extractData(ResultSet rs) throws SQLException {
Master m = new Master();
m.setFirstName(rs.getString(1));
m.setLastName(rs.getString(2));
//put the master in a map
Detail d = new Detail();
d.setSomeProp(rs.getString(3));
//check if the master is in the map
//if yes - add the detail to the master
//if no - add the master first
return m;
}
}
结果集是表连接的结果。哪种方法更好…您的还是Gabriel的。使用ResultSet-Mapper,我们提取了大量冗余数据,但只访问了数据库一次。RowMapper只提供结果集的一行。使用Gabriel的方法,如果一个人有两辆或更多的车,您将得到一个人obj对他/她拥有的每辆车进行ect,即使数据相同。+对于ResultsTextRactor,您只能使用一次对DB的调用(与另一个答案中的sql相同)。我投票支持我的方法:)
public class MasterDetailResultSetExtractor implements ResultSetExtractor {
@Override
public Object extractData(ResultSet rs) throws SQLException {
Master m = new Master();
m.setFirstName(rs.getString(1));
m.setLastName(rs.getString(2));
//put the master in a map
Detail d = new Detail();
d.setSomeProp(rs.getString(3));
//check if the master is in the map
//if yes - add the detail to the master
//if no - add the master first
return m;
}
}