逆向工程中,添加一条记录时的insert和insertSelective方法

使用逆向工程生成的代码做一个添加时通常都会给出两个答案,如题目想要增加一条数据会让你选择insert或者insertSelective

 

两者的区别在于如果选择insert 那么所有的字段都会添加一遍即使没有值

1

2

3

4

5

6

7

8

<insert id="insert" parameterType="com.ego.pojo.TbContentCategory" >

insert into tb_content_category (id, parent_id, name,

status, sort_order, is_parent,

created, updated)

values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR},

#{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT},

#{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})

</insert>

  


但是如果使用inserSelective就会只给有值的字段赋值(会对传进来的值做非空判断)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

<insert id="insertSelective" parameterType="com.ego.pojo.TbContentCategory" >

insert into tb_content_category

<trim prefix="(" suffix=")" suffixOverrides="," >

<if test="id != null" >

id,

</if>

<if test="parentId != null" >

parent_id,

</if>

<if test="name != null" >

name,

</if>

<if test="status != null" >

status,

</if>

<if test="sortOrder != null" >

sort_order,

</if>

<if test="isParent != null" >

is_parent,

</if>

<if test="created != null" >

created,

</if>

<if test="updated != null" >

updated,

</if>

</trim>

<trim prefix="values (" suffix=")" suffixOverrides="," >

<if test="id != null" >

#{id,jdbcType=BIGINT},

</if>

<if test="parentId != null" >

#{parentId,jdbcType=BIGINT},

</if>

<if test="name != null" >

#{name,jdbcType=VARCHAR},

</if>

<if test="status != null" >

#{status,jdbcType=INTEGER},

</if>

<if test="sortOrder != null" >

#{sortOrder,jdbcType=INTEGER},

</if>

<if test="isParent != null" >

#{isParent,jdbcType=BIT},

</if>

<if test="created != null" >

#{created,jdbcType=TIMESTAMP},

</if>

<if test="updated != null" >

#{updated,jdbcType=TIMESTAMP},

</if>

</trim>

  


</insert>
如果不明白的话提供一个简单的例子,再结合上面的源码体会一下

前提Goods商品表里面有三个字段:id,name,price 
1.此时我只设置了一个字段名字: 
Goods g = new Goods(); 
g.setName("手机");
insertSelective(g);
insertSelective执行对应的sql语句的时候,只插入对应的name字段;
(主键是自动添加的,默认插入为空)insert into tb_goods (id,name) value (null,"手机");
注意:此时是没有price什么事的
2、如果使用insert则是不论你设置多少个字段,统一都要添加一遍,不论你设置几个字段,即使是一个。
Goods g=new Goods();
g.setName("冰箱");
insert(g)
insert执行对应的sql语句的时候,统一都要添加一遍;
insert into tb_goods (id,name,price) value (null,"冰箱",null);

注意:price也在哦!!

作者:风泊月 
来源:CSDN 
原文:https://blog.csdn.net/hello_word2/article/details/80560725 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值