Mybatis快速入门

2019-04-29  本文已影响0人  topshi

1.配置mybatis-config.xml文件,文件配置了数据源的一些参数和指定sql的mapper文件(mapper.xml注册到全局配置文件)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/runoob"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

2.编写mapper.xml文件,该文件是各种sql语句的集合

<?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="dao.StudentSelecter">
    <select id="getStudentById" resultType="bean.Student">
        select * from student where id = #{id}
    </select>
</mapper>

查询一条数据

public static void main(String[] args) throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory =
            new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Student student =sqlSession.selectOne("dao.StudentSelecter.getStudentById", 1);
    sqlSession.close();
    System.out.println(student);
}

首先获取配置文件的流,通过文件流构建sqlSession工厂对象,工厂对象获取sqlSession,sqlSession对象执行sql操作获取数据。
但是通过这种形式查询selectOne方法的第一个参数太长太麻烦,因此产生一种接口式编程。
先写一个接口

public interface StudentSelecter {
    public Student getStudentById(int id);
}

上面我们的mapper.xml有个mapper是通过Id获取student对象的,因此这里写一个getStudentId方法即可。
测试方法不再通过sqlSession.selectOne的方式进行执行sql语句。

public static void main(String[] args) throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory =
            new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //Student student =sqlSession.selectOne("StudentMapper.selectStudent", 1);
    StudentSelecter mapper = sqlSession.getMapper(StudentSelecter.class);
    Student student = mapper.getStudentById(2);
    sqlSession.close();
    System.out.println(student);
}

使用sqlSession.getMapper()获取接口实例化对象(代理对象),该对象执行接口相应的方法执行sql操作。

上一篇下一篇

猜你喜欢

热点阅读