Mysql:
- useGeneratedKeys和keyProperty配置即可,前者是指设置是否使用jdbc的getGenereatedKeys方法获取主键并赋值到keyProperty设置的属性中,后者即实体类主键字段
e.g: xml文件
<insert id="insert2ReturnId" useGeneratedKeys="true" keyProperty="id" parameterType="com.yaoxx.OA.vacation.entity.VacationPlan">
insert into t_vacation_plan (
c_id,
c_dept_id,
c_create_time,
c_creater_id,
c_status)
values (
#{id,jdbcType=INTEGER},
#{deptId,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
#{createrId,jdbcType=INTEGER},
#{status,jdbcType=INTEGER})
</insert>
使用时并不是直接获取mapper接口中方法的返回值,而是从方法参数那个实体中获取:
@Transactional
@Service
public class VacationPlanServiceImpl implements VacationPlanService{
@Autowired
private VacationPlanMapper planDao;
@Override
public Integer addOne(VacationPlan plan) {
planDao.insert2ReturnId(plan);//此方法对应上面的.xml
return plan.getId();//执行xml后会对此实体添加id
}
}
- 使用注解的方式(- -没测试- -)
@Mapper
public interface UserMapper
{
@Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
@Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
void insertUser(User user);//通过user.getId();获取
}
Orcle
其中common_sequence是一个专门给表提供自增主键的序列
<!-- 创建序列sql -->
CREATE SEQUENCE common_sequence
INCREMENT BY 1 -- 每次递增1
START WITH 1 -- 从1开始
MINVALUE 1 -- 最小值=1
NOCYCLE; -- 不循环
<insert id="addOne" parameterType="com.dd.work.workaudit.entity.WtspStatus" useGeneratedKeys="true" keyProperty="id" >
<!-- 返回查询并将id添加进实体参数 -->
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select common_sequence.nextval from dual
</selectKey>
insert into T_WTSP_STATUS
(
C_ID,
C_STATION_NAME
)
values
(
#{id, jdbcType=INTEGER},
#{stationName, jdbcType=VARCHAR}
)
</insert>