MyBatis 学习笔记(1)

MyBatis 的基本构成

SqlSessionFactoryBuilder(构造器):它会根据配置信息或者代码来生成 SqlSessionFactory(工厂接口)

SqlSessionFactory:生成 SqlSession(会话)

SqlSession:是一个既可以发送 SQL 去执行并返回结果,也可以获取 Mapper 的接口

SQL Mapper:是由一个 Java 接口和 XML 文件(或注解)构成的,需要给出对应的 SQL 和映射规则。它负责发送 SQL 去执行,并返回结果

下面列举一个使用的小例子:

配置文件如下:

<?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>
  <properties>
    <property name="driver" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/demo" />
    <property name="username" value="root" />
    <property name="password" value="root" />
  </properties>
  <settings>
    <setting name="logImpl" value="LOG4J"/>
  </settings>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <package name="study.mybatis.mapper" />
  </mappers>
</configuration>

SQL Mapper :

public interface BlogMapper {
    Blog selectBlog(int id);
}
<?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="study.mybatis.mapper.BlogMapper">
  <select id="selectBlog" resultType="study.mybatis.po.Blog">
    select * from t_blog where id = #{id}
  </select>
</mapper>

Demo :

public class Demo {
  
public static void main(String[] args) throws IOException{ InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(1); System.out.println(blog);
     // 关闭session等 } }

 

posted on 2017-12-03 10:00  _路上  阅读(118)  评论(0编辑  收藏  举报

导航