mybatis使用注解配置SQL语句

mybatis使用注解配置SQL语句

添加 Insert

@Insert("insert into stu_info(stu_name,stu_age) values (#{stuName}, #{age})")
//使用@Options注解来获取自增长的主键
@Options(useGeneratedKeys = true, keyProperty = "uid")
void save(Student student);

删除

@Delete("delete from stu_info where stu_id = #{uid}")
void delete(int uid);

修改

@Update("update stu_info set stu_name = #{stuName}, " +
        "stu_age = #{age} where stu_id = #{uid}")
void update(Student student);

查询

@Select("select stu_id as uid, stu_name as stuName, stu_age as age " +
        "from stu_info where stu_id = #{uid}")
@ResultType(Student.class)
Student getStuById(int uid);

@Select("select s.stu_id, s.stu_name, s.stu_age, c.class_name from " +
        "stu_info s left join class_info c on s.c_id = c.c_id")
//如果使用@ResultMap注解,映射配置还是放在xml中
//注解的value指定为“dao接口的完整类名.resultMap的id”
@ResultMap("edu.nf.ch06.dao.StuDao.stuMap")
List<Student> listStudents();

配置文件

<mappers>
    <!-- 映射配置文件, 当如果使用了mapper映射,里面会指定namespace的dao完整类名
         下面的dao接口就不需要再指定-->
    <mapper resource="mappers/StudentMapper.xml"/>

    <!-- 当在Dao接口上使用注解映射sql时,
         这里就使用class属性指定dao接口的完整类名 -->
    <!--<mapper class="edu.nf.ch06.dao.StuDao"/>-->

    <!-- 也可以使用package标签指定dao接口的包即可 -->
    <!--<package name="edu.nf.ch06.dao"/>-->
</mappers>
<mapper namespace="edu.nf.ch06.dao.StuDao">
<resultMap id="stuMap" type="edu.nf.ch06.entity.Student">
    <id property="uid" column="stu_id"/>
    <result property="stuName" column="stu_name"/>
    <result property="age" column="stu_age"/>
    <association property="classInfo">
        <id property="cid" column="c_id"/>
        <result property="className" column="class_name"/>
    </association>
</resultMap>
</mapper>