gpt4 book ai didi

java - 用于 OneToMany 的 Spring RowMapper?

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:22 24 4
gpt4 key购买 nike

我正在尝试为两个对象调整两个 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 方法将引发异常,指出“连接过多!”。这是因为它们之间的行映射器存在循环依赖性。我知道我以错误的方式完成了此操作,我想知道如何正确重写行映射器。非常感谢。

最佳答案

首先,您的 java 对象构造函数是“递归”紧密耦合的。 AccountCard 构造函数期望彼此作为参数。没有卡也可以有账户,对吗?因此删除 Account 构造函数的卡片列表。

现在进入查询,加载帐户卡时有两种情况:

1 - 从账户加载卡牌:您已经拥有该账户,无需为每张卡查询账户。因此,您可以拥有一个通过参数接收帐户的 MAP_CARD_FROM_ACCOUNT 行映射器。

2- 加载单张卡:在这种情况下,您只需要卡及其帐户,因此对于 MAP_CARD 映射器,您可以进行查询以返回卡和帐户信息:SELECT * FROM 卡 C, 帐户 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;
}
};

关于java - 用于 OneToMany 的 Spring RowMapper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com