我正在使用Spring-boot和Oracle,我想使用NamedParameterJdbcTemplate
insertbatch
方法插入到我的数据库表新记录。
但是我的object(ProductMarket)
有内部的object(Market)
与我需要的值(getMarket().getId())
如何告诉SqlParameterSource
从内部Object
获取市场id ?
package x.dao.productMarket;
import java.util.List;
import x.model.base.ProductMarket;
public interface IProductMarketDao {
public static final String INSERT_PRODUCT_MARKETS =
" INSERT " +
" INTO PRODUCT_MARKETS" +
" (" +
" product_id ," +
" market_id" +
" )" +
" VALUES" +
" (" +
" :productId ," +
" :marketId " +
" ) ";
void insert(List < ProductMarket > productMarkets);
}
package x.dao.productMarket;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;
import x.model.base.ProductMarket;
@
Repository
public class ProductMarketDao implements IProductMarketDao {
@
Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@
Override
public void insert(List < ProductMarket > productMarkets) {
SqlParameterSource[] batch =
SqlParameterSourceUtils.createBatch(productMarkets.toArray());
namedParameterJdbcTemplate.batchUpdate(INSERT_PRODUCT_MARKETS,
batch);
}
}
package x.model.base;
public class ProductMarket implements Serializable {
private static final long serialVersionUID = 421870753189756693 L;
private long productId;
private Market market;
/**
* @return the productId
*/
public long getProductId() {
return productId;
}
/**
* @param productId the productId to set
*/
public void setProductId(long productId) {
this.productId = productId;
}
public Market getMarket() {
return market;
}
public void setMarket(Market market) {
this.market = market;
}
}
假设市场定义如下:
class Market {
private final int id;
private final String name;
public Market(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
然后你可以改变你的SQL模板如下:
static final String INSERT_PRODUCT_MARKETS =
" INSERT " +
" INTO product_markets" +
" (" +
" product_id ," +
" market_id" +
" )" +
" VALUES" +
" (" +
" :productId ," +
" :market.id " +
" ) ";
请注意,我是如何使用路径来表示形式:market.id
中的命名参数的,其中market
是ProductMarket
中的字段名,id
是Market
中的字段名。
一旦以这种方式定义,NamedParameterJdbcTemplate
将能够解引用相应的值并将其用作查询的参数。