Mybatis获取mysql自增主键

注意点:

  1. interface中不要传入@Param
  2. xml中不要使用对象前缀,直接使用默认属性就好
  3. insert标签中添加两个属性
<insert id="saveUserQuestion" parameterType="com.lonelyzhe.springboot.bean.Question"  useGeneratedKeys="true" keyProperty="id" >

QuestionMapper.java文件

@Mapper
public interface QuestionMapper {
    // 保存用户原创试题试题
    void saveUserQuestion(Question question); //为了返回自增主键,此处不能使用@Param
    // 保存题目的标签
    void saveQuestionTags(@Param("tags") List<QuestionAndTagId> tags);
}

QuestionMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lonelyzhe.springboot.mapper.QuestionMapper">
    <resultMap id="questionResult" type="com.lonelyzhe.springboot.bean.Question">
        <id property="id" column="id" />
        <result property="questionContent" column="question_content" />
        <result property="questionAnalyse" column="question_analyse" />
        <result property="questionAnswer" column="question_answer" />
        <result property="goodNumber" column="good_number"/>
        <association property="hardness" javaType="com.lonelyzhe.springboot.bean.Hardness" >
            <id property="id" column="hardness_id" />
            <result property="hardness" column="hardness" />
        </association>
        <association property="student" javaType="com.lonelyzhe.springboot.bean.Student" >
            <id property="id" column="student_id" />
            <result property="student" column="student" />
        </association>
        <!--要使用ofType,千万不要用resultMap-->
        <collection property="tags" column="id" ofType="com.lonelyzhe.springboot.bean.QuestionTag"
            javaType="ArrayList" select="getTagsByQuestionId"/>
    </resultMap>
    <!--此处使用useGeneratedKeys="true" keyProperty="id",将自增主键保存起来-->
    <insert id="saveUserQuestion" parameterType="com.lonelyzhe.springboot.bean.Question"  useGeneratedKeys="true" keyProperty="id" >
        insert into
          cepc_question(owner_id,question_content,question_analyse,question_answer,hardness_id,student_id)
        values (
          #{owner.id},  <!--此处一定得直接利用bean中的属性,千万不要想@Param里面一样带一个对象前缀-->
          #{questionContent},
          #{questionAnalyse},
          #{questionAnswer},
          #{hardness.id},
          #{student.id}
        )
    </insert>
</mapper>

你可能感兴趣的:(Mybatis)