我使用的是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;
}
}
答案 0 :(得分:0)
假设市场定义如下:
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
将能够取消引用相应的值并将其用作查询的参数。