MyBatis框架的基本使用
1 导包
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
2 配置mybatis.cfg.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=""/>
<property name="url" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource=""/>
</mappers>
</configuration>
3 写DTO 和 映射文件
映射文件的配置有两种方式
第一种
<select id="getAuthorById" parameterType="int" resultMap="authorResultMap">
select author_id,author_name from tb_author where author_id = #{author_id}
</select>
<resultMap type="mybatis.dto.AuthorDTO" id="authorResultMap">
<id column="author_id" property="author_id"/>
<result column="author_name" property="author_name"/>
<collection property="bookList" column="author_id" ofType="mybatis.dto.BookDTO" select="getBookById">
</collection>
</resultMap>
<select id="getBookById" parameterType="int" resultType="mybatis.dto.BookDTO">
select * from tb_book where book_author_id = #{author_id}
</select>
第二种
<!-- 第二种实现,和多对多的配置一样 -->
<select id="getAuthorById2" parameterType="int" resultMap="authorResultMap2">
select * from tb_author a join tb_book b on a.author_id = b.book_author_id and a.author_id = #{author_id}
</select>
<resultMap type="mybatis.dto.AuthorDTO" id="authorResultMap2">
<id column="author_id" property="author_id"/>
<result column="author_name" property="author_name"/>
<collection property="bookList" ofType="mybatis.dto.BookDTO" >
<id column="book_id" property="book_id"/>
<result column="book_name" property="book_name"/>
</collection>
</resultMap>
4 加载配置文件并获取sessionFactory和session
InputStream is = AppTest.class.getClassLoader().getResourceAsStream("mybatis.cfg.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
AuthorDTO author = session.selectOne("mybatis.dto.AuthorMapper.getAuthorById2", 1);
System.out.println(author.getAuthor_name());
List<BookDTO> bookList = author.getBookList();
for(BookDTO book:bookList){
System.out.println(book.getBook_name());
}
session.close();