天天看点

MyBatis之单表查询

因最近会用到mybatis相关,好久木有用了, 赶紧来回顾以及记录并分享下:

这一章先来分享一下单表查询是如何实现的:

一、添加mybatis依赖

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>
           

二、添加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="${driver}"/>
        <!-- 配置数据库地址-->
        <property name="url" value="${url}"/>
        <!-- 配置数据库用户名-->
        <property name="username" value="${username}"/>
        <!-- 配置数据库密码-->
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
  	<!-- 配置实体类对应xml文件-->
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
           

三、读取xml文件创建SqlSessionFactory对象

//配置文件路径
String resource = "org/mybatis/example/mybatis-config.xml";
//获取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过配置文件获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory =
  new SqlSessionFactoryBuilder().build(inputStream);
           

四、创建sql语句以及创建SqlSession对象

1)配置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="org.mybatis.example.BlogMapper">
<!-- 以id为参数查询结果-->
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
           

2)创建SqlSession对象

try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = session.selectOne(
    "org.mybatis.example.BlogMapper.selectBlog", 101);
}
           

继续阅读