在某些场景下,需要将一组数据插入数据库中,如果已存在,则进行更新。如果数据库是mysql,我们可以使用on duplicate key update语句,而不需要分别处理insert和update。
之前看了好多帖子,表结构和实体类要么都是驼峰,要么都是小写,而我的项目里表结构是下划线命名的,导致我一开始用时候,总是搞混,所以我把表结构和DO的结构也贴上来,好做个对比。
一、表结构(下划线)
DROP TABLE IF EXISTS planflow;
CREATE TABLE planflow
(
plan_no int DEFAULT 0 NOT NULL ,
flow_no int DEFAULT 0 NOT NULL ,
plan_type char DEFAULT ' ' NOT NULL ,
plan_invest decimal(20,4) DEFAULT 0.0 NOT NULL ,
plan_profit decimal(20,4) DEFAULT 0.0 NOT NULL ,
plan_balance decimal(20,4) DEFAULT 0.0 NOT NULL
);
ALTER TABLE planflow ADD PRIMARY KEY(plan_no,flow_no);
二、DO(驼峰)
@EqualsAndHashCode
@ToString
@Table(name="planflow")
public class PlanFlowDO {
@Id
@Column(name = "plan_no")
private Integer planNo;
@Id
@Column(name = "flow_no")
private Integer flowNo;
@Column(name = "plan_type")
private String planType;
@Column(name = "plan_invest")
private BigDecimal planInvest;
@Column(name = "plan_profit")
private BigDecimal planProfit;
@Column(name = "plan_balance")
private BigDecimal planBalance;
/**
* get()和set()方法省略
*/
}
三、插入或更新(单条)
注意:on duplicate key update语句后面,等号前后两个值,均使用表字段,例:plan_type = values(plan_type)
<insert id="insertOrUpdatePlan" parameterType="com.happy.hhome.bean.plan.PlanFlowDO">
insert into planflow
(
plan_no ,
flow_no ,
plan_type ,
plan_invest ,
plan_profit ,
plan_balance
)
values (
#{planNo} ,
#{flowNo} ,
#{planType} ,
#{planInvest},
#{planProfit},
#{planBalance}
)
on duplicate key update
plan_type = values(plan_type) ,
plan_invest = values(plan_invest) ,
plan_profit = values(plan_profit) ,
plan_balance = values(plan_balance)
</insert>
四、插入或更新(批量)
使用<foreach>生成values()语句即可,同样的,on duplicate key update语句后面,等号前后两个值,均使用表字段,例:plan_type = values(plan_type)
<insert id="insertOrUpdatePlanList" parameterType="com.happy.hhome.bean.plan.PlanFlowDO">
insert into planflow
(
plan_no ,
flow_no ,
plan_type ,
plan_invest ,
plan_profit ,
plan_balance
)
values
<foreach collection="list" item="item" index= "index" separator="," >
(
#{item.planNo} ,
#{item.flowNo} ,
#{item.planType} ,
#{item.planInvest},
#{item.planProfit},
#{item.planBalance}
)
</foreach>
on duplicate key update
plan_type = values(plan_type) ,
plan_invest = values(plan_invest) ,
plan_profit = values(plan_profit) ,
plan_balance = values(plan_balance)
</insert>