MyBatis简单的CRUD操作

Dao接口

package com.ttpfx.dao;

import com.ttpfx.domain.User;

import java.util.List;

public interface UserDao {
    List<User> getAll();
    List<User> getUserListByName(String keyword);
    User getUserById(int id);
    int insertUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
    int getTotal();
}

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.ttpfx.dao.UserDao">
    <select id="getAll" resultType="com.ttpfx.domain.User">
        select id, username, birthday, sex, address from user
    </select>

    <insert id="insertUser" parameterType="com.ttpfx.domain.User">
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user (username, birthday, sex, address) values (#{username}, #{birthday}, #{sex}, #{address})
    </insert>

    <update id="updateUser" parameterType="com.ttpfx.domain.User">
        update user set username=#{username}, birthday=#{birthday}, sex=#{sex}, address=#{address} where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <select id="getUserById" parameterType="int" resultType="com.ttpfx.domain.User">
        select id, username, birthday, sex, address from user where id = #{id}
    </select>

    <select id="getUserListByName" parameterType="String" resultType="com.ttpfx.domain.User">
        select id, username, birthday, sex, address from user where username like #{keyword}
    </select>

    <select id="getTotal" resultType="int">
        select count(*) from user
    </select>
</mapper>
posted @ 2021-03-04 17:09  ttpfx  阅读(52)  评论(0)    收藏  举报