我试图为两个对象调整两个RowMappers,它们之间存在@OneToMany关系。
假设,我有两种方法:
public Account findAccount(long id) {
SQL = "SELECT * FROM accounts WHERE id = ?";
Account account = template.queryForObject(SQL, new Object[] { id }, MAP_ACCOUNT);
return account;
}
public Card findCard(String number) {
SQL = "SELECT * FROM cards WHERE number = ?";
Card card = template.queryForObject(SQL, new Object[] { number }, MAP_CARD);
return card;
}两排地图绘制者:
private final RowMapper<Card> MAP_CARD = new RowMapper<Card>() {
public Card mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = findAccount(rs.getLong("account_id"));
Card card = new DefaultCard(rs.getString("number"), account);
return card;
}
};
private final RowMapper<Account> MAP_ACCOUNT = new RowMapper<Account>() {
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
SQL = "SELECT * FROM cards where account_id = " + rs.getLong("id");
List<Card> cards = template.query(SQL, MAP_CARD);
Account account = new DefaultAccount(rs.getLong("id"), rs.getString("username"), cards);
return account;
}
};运行findAccount或findCard方法将引发一个异常,说明“连接太多了!”。这是因为它们之间的行映射器具有循环依赖性。我知道我这样做是错误的,我想知道如何正确地重写行映射器。非常感谢。
发布于 2014-11-05 15:30:14
首先,java对象构造函数是“递归”紧密耦合的。Account和Card构造函数相互期望对方作为参数。你可以有一个没有信用卡的账户,对吗?因此,删除帐户构造函数的卡片列表。
现在转到查询,当加载帐户卡时,有两种情况:
1-加载卡从帐户:您已经有帐户,这是不必要的查询帐户为每一张卡。因此,您可以有一个MAP_CARD_FROM_ACCOUNT行映射程序,它通过参数接收帐户。
2- 加载单张卡:在这个场景中,您只需要卡及其帐户,因此对于MAP_CARD映射程序,您可以查询返回卡和帐户信息:SELECT * FROM cards C, accounts a WHERE c.account_id=a.id and number = ?
下面是映射程序代码的外观示例:
private final RowMapper<Card> MAP_CARD_FROM_ACCOUNT = new RowMapper<Card>() {
public void setAccount(Account account){
this.account = account;
}
public Card mapRow(ResultSet rs, int rowNum) throws SQLException {
Card card = new DefaultCard(rs.getString("number"), account);
return card;
}
};
private final RowMapper<Card> MAP_CARD = new RowMapper<Card>() {
public Card mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account(rs.getLong("a.account_id"), rs.getString("a.username");
Card card = new DefaultCard(rs.getString("c.number"), account);
return card;
}
};
private final RowMapper<Account> MAP_ACCOUNT = new RowMapper<Account>() {
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
SQL = "SELECT * FROM cards where account_id = " + rs.getLong("id");
Account account = new DefaultAccount(rs.getLong("id"), rs.getString("username"));
MAP_CARD_FROM_ACCOUNT.setAccount(account)
List<Card> cards = template.query(SQL, MAP_CARD_FROM_ACCOUNT);
account.setCards(cards);
return account;
}
};https://stackoverflow.com/questions/26759834
复制相似问题