简单的记录下哈~~~~~~
1. 使用注解的方式如下,很简洁。
@Mapper
public interface QuestionDAO {
String TABLE_NAME = " question ";
String INSERT_FIELDS = " title, content, created_date, user_id, comment_count ";
String SELECT_FIELDS = " id, " + INSERT_FIELDS;
@Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
") values (#{title},#{content},#{createdDate},#{userId},#{commentCount})"})
int addQuestion(Question question);
List<Question> selectLatestQuestions(@Param("userId") int userId, @Param("offset") int offset,
@Param("limit") int limit);
@Select({"select ", SELECT_FIELDS, " from ", TABLE_NAME, " where id=#{id}"})
Question getById(int id);
2. 使用XML的方式
2.1 映射文件中的namespace是用于绑定Dao接口的,即面向接口编程。
当你的namespace绑定接口后,你可以不用写接口实现类,mybatis会通过该绑定自动帮你找到对应要执行的SQL语句
2.2 注意接口中的方法与映射文件中的SQL语句的ID一一对应
2.3 这里的if是使用了动态sql的方法,如果 “userID”为空的话,那么就搜索所有满足where条件的内容;如果 “userID”不为空的话,搜索出对应 id 的那个条目。
<mapper namespace="com.nowcoder.dao.QuestionDAO">
<sql id="table">question</sql>
<sql id="selectFields">id, title, content, comment_count,created_date,user_id
</sql>
<select id="selectLatestQuestions" resultType="com.nowcoder.model.Question">
SELECT
<include refid="selectFields"/>
FROM
<include refid="table"/>
<if test="userId != 0">
WHERE user_id = #{userId}
</if>
ORDER BY id DESC
LIMIT #{offset},#{limit}
</select>
</mapper>