02-Mybatis的Dao层开发代理方式实现

注意点:

1 namespace必须与接口的全限定名一致

2 接口方法方法名必须与映射文件statement的id一致

3 参数类型和返回值一致

1.开发Dao层接口

package com.itheima.dao;

import com.itheima.domain.User;

import java.io.IOException;
import java.util.List;

public interface UserMapper {

    public List<User> findAll() throws IOException;

    public User findById(int id);


}

2.映射文件

<?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">
<!--namespace必须与接口的全限定名一致-->
<mapper namespace="com.itheima.dao.UserMapper">

    <!--使用了别名配置-->
    <select id="findAll" resultType="user">
        select * from user
    </select>

    <!--根据id查询-->
    <select id="findById" resultType="user" parameterType="int">
        select * from user where id=#{id}
    </select>


</mapper>

3.测试类

package com.itheima.service;

import com.itheima.dao.UserMapper;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ServiceDemo {

    public static void main(String[] args) throws IOException {

        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 使用getMapper方式获取代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // List<User> all = mapper.findAll();
        // System.out.println(all);
        User byId = mapper.findById(1);
        System.out.println(byId);

    }
}

上一篇:轻松拥有属于自己的包


下一篇:Nginx的启动、停止与重启