Mybatis实现CRUD操作

2022-03-23 16:51:11 浏览数 (1)

1.dao层接口编写

代码语言:javascript复制
public interface IUserDao {
    /**
     * 查询所有
     * @return
     */
    List<User> findAll();
    /**
     * 查询一条
     * @return
     */
    User findById(Integer id);
    /**
     * 保存
     * @return
     */
    void saveUser(User user);
    /**
     * 根据id删除
     * @return
     */
    void deleteUser(Integer id);
    /**
     * 修改
     * @return
     */
    void updateUser(User user);
    /**
     * 模糊查询
     * @return
     */
    List<User> findName(String name);

}

**

2.映射文件编写

代码语言:javascript复制
<mapper namespace="com.rpf.dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="com.rpf.domain.User">
        select * from user
    </select>
    <!--保存数据-->
    <insert id="saveUser" parameterType="com.rpf.domain.User">
        insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>
    <!--根据id删除-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id};
    </delete>
      <!--修改-->
    <update id="updateUser" parameterType="com.rpf.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id={uid};
    </update>
      <!--查询一条-->
    <select id="findById" parameterType="Integer" resultType="com.rpf.domain.User">
        select * from user where id=#{id}
    </select>
      <!--模糊查询-->
    <select id="findName" parameterType="String" resultType="com.rpf.domain.User">
        select * from user where username like #{name};
    </select>
    <!--显示刚插入的id-->
     <insert id="saveUser" parameterType="com.rpf.domain.User">
       <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
           select last_insert_id();
       </selectKey>
    insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>
</mapper>

3.测试方法

代码语言:javascript复制
 public static void main(String[] args)throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        UserDao userDao = session.getMapper(UserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();

        @Test
        public void testFindName(){
            List<User> users = userDao.findName("%王%");
            for (User user:users){
                System.out.println(user);
            }
        }
}

0 人点赞