1、dao层:
package com.admin.dao.mapper.linkage;
@MyBatisDao
public interface StrategyMapper {
int insert(Strategy record);
}
2、实现层
package com.admin.dao.mapper.linkage;
@Service
public class StrategyService {
@Autowired
private StrategyMapper strategyDao;
public int insert(Strategy strategy){
this.strategyDao.insert(strategy);
int id = strategy.getId();
System.out.println(id);
}
}
3、mapper.xml
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.shengtong.smartlamppost.admin.dao.entity.linkage.Strategy" >
insert into linkage_strategy (id, strategy_name, priority,
status, create_by, create_date,
update_by, update_date, remarks
)
values (#{id,jdbcType=INTEGER}, #{strategyName,jdbcType=VARCHAR}, #{priority,jdbcType=INTEGER},
#{status,jdbcType=CHAR}, #{createBy.id,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP},
#{updateBy.id,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, #{remarks,jdbcType=VARCHAR}
)
</insert>
总结:
- 想要获取自增主键id,应该通过对象的getId()方法,而并不是insert的返回值,insert的返回值表示的是影响行数
2.在mapper.xml中:useGeneratedKeys=“true”、keyProperty=“id”,这两个属性的作用:
共同决定了sql执行后,会将主键封装到id属性上;
自增主键封装到了对象的id属性上了,那么想要获取,直接调用对象的getId()方法就可以了