我将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中有效地映射这个?
答案 0 :(得分:0)
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父类,看看是否可以简化这个。我再次不确定这是否是你所追求的方法,但我想分享我的想法。感谢