我有ClientDetails作为bean,具有以下结构:
public class ClientDetails{
protected String id;
protected String type;
protected AddressDetails;
protected PhoneDetails;
//getters and setters follows...
}
public class AddressDetails{
protected List<Address> address
//getters and setters follows...
}
public Address{
protected String addressType;
protected String line1;
protected String line2;
protected String line3;
//getters and setters follows...
}
public PhoneDetails{
protected List<PhoneDetail> phoneDetail;
//getters and setters follows...
}
public class PhoneDetail {
protected String type;
protected String phoneNumber;
//getters and setters follows...
}
数据库中的表:ClientDetails、AddressDetails、PhoneDetails。
我将在服务层接收ClientDetails列表,并且必须始终更新ClientDetails表。AddressDetails,PhoneDetails将被选择性地更新(如果不是null)。如何在ibatis中有效地绘制此图?
Akhilesh这是我想到的一种方式(见下文)。我也在学习Ibatis/MyBatis,并逐渐掌握它。我想你想在一个交易中包含几个插入/更新(考虑性能)吗?与批处理更新类似,将批处理封装在单个事务中。本例基于IBatis 2.3.4
在你的DAO类中,你可以有
final SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
sqlMap.startBatch();
for (final ClientDetails clientXXX : clientDetailsList) {
createOrUpdateClientDetails(sqlMapClient, clientXXX);
createOrUpdateClientAddressDetails(sqlMapClient, clientXXX.getAddressDetails());
createOrUpdateOtherXXXDetails(clientXXX.getXXXXX); //have similar private method
}
sqlMap.executeBatch();
sqlMap.commitTransaction();
} catch (final SQLException e) {
throw new XXXException(e);
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
throw new XXXException(e);
}
}
private void createOrUpdateClientDetails(final SqlMapClient sqlMap, final List<ClientDetails> clientDetails) {
for (final ClientDetails client: clientDetails) {
if (client.getId() != null) {
sqlMap.update("updateClientXXX", client); //your sqlmap method
} else {
sqlMap.insert("createClientXXX", client); //your sqlmap method
}
}
}
但是,请注意,无论何时使用一组批处理语句,都不会生成数据库生成的键,直到调用executeBatch()方法。这意味着,如果使用selectKey
使用生成的密钥更新对象,则它们将返回null如果有任何对象需要新生成的键作为另一个依赖插入的一部分,则可以在startBatch()之前插入此插入/父插入。例如,AddressDetails和PhoneDetails的customer_id是否为FK?
我还会再次查看ClientDetails父类,看看是否可以在可能的情况下简化它。同样,我不确定这是否是你想要的方法,但我想分享我的想法。感谢