MyBatis 入门

MyBatis 笔记

项目地址:https://github.com/code-flying/mybatis

一、mybatis 入门

1. 引入jar包

<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>
</dependencies>

2. 配置数据库信息

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.0.102:3306/gp-mybatis?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=****

3. 配置全局mybatis文件

<?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 resource="db.properties" />

	<settings>
		<!-- 开启日志 -->
		<setting name="logImpl" value="STDOUT_LOGGING" />
	</settings>
	
	<typeAliases>
		<!-- 别名 -->
		<typeAlias alias="blog" type="com.mybatis.learn.domain.Blog" />
	</typeAliases>

	<!-- 配置数据库环境 -->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>

	<!-- 配置映射器 -->
	<mappers>
		<mapper resource="BlogMapper.xml" />
	</mappers>

</configuration>

4.数据库脚本

CREATE TABLE `blog` (
  `bid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `author_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`bid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `author` (
  `author_id` int(16) NOT NULL AUTO_INCREMENT,
  `author_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1002 DEFAULT CHARSET=utf8;

CREATE TABLE `comment` (
  `comment_id` int(16) NOT NULL AUTO_INCREMENT,
  `content` varchar(255) DEFAULT NULL,
  `bid` int(16) DEFAULT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `blog` (`bid`, `name`, `author_id`) VALUES (1, 'RabbitMQ延时消息', 1001);
INSERT INTO `blog` (`bid`, `name`, `author_id`) VALUES (2, 'MyBatis源码分析', 1008);
INSERT INTO `author` (`author_id`, `author_name`) VALUES (1001, '青山');
INSERT INTO `comment` (`comment_id`, `content`, `bid`) VALUES (1, '写得真好,学习了', 1);
INSERT INTO `comment` (`comment_id`, `content`, `bid`) VALUES (2, '刚好碰到这个问题,谢谢', 1);

5. 编写domain类

/**
 * @author dingding
 *
 */
public class Blog {

	private Integer bid;// 文章ID
	private String name; // 文章标题
	private Integer authorId; // 文章作者ID

	public Integer getBid() {
		return bid;
	}

	public void setBid(Integer bid) {
		this.bid = bid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAuthorId() {
		return authorId;
	}

	public void setAuthorId(Integer authorId) {
		this.authorId = authorId;
	}

	@Override
	public String toString() {
		return "Blog [bid=" + bid + ", name=" + name + ", authorId=" + authorId
				+ "]";
	}

}

6. 编写 mapper

6.1 mapper接口

/**
 * @author dingding
 *
 */
public interface BlogMapper {
	
	/**
     * 根据主键查询文章
     * @param bid
     * @return
     */
    public Blog selectBlogById(Integer bid);

}

6.2 mapper接口对应的xml文件

<?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="com.mybatis.learn.mapper.BlogMapper">

	<resultMap type="blog" id="BaseResultMap">
		<id column="bid" property="bid" jdbcType="INTEGER" />
		<result column="name" property="name" jdbcType="VARCHAR" />
		<result column="author_id" property="authorId" jdbcType="INTEGER" />
	</resultMap>

	<select id="selectBlogById" resultMap="BaseResultMap" >
		select * from blog where bid = #{bid}
	</select>

</mapper>

7. 测试

import java.io.IOException;
import java.io.InputStream;

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 org.junit.Test;

import com.mybatis.learn.domain.Blog;
import com.mybatis.learn.mapper.BlogMapper;

/**
 * @author dingding
 *
 */
public class MyBatisTest {
	
	/**
     * 使用MyBatis API方式
     * ibatis 原生方式
     * @throws IOException
     */
	@Test
	public void testStatement() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		try {
			Blog blog = session.selectOne("com.mybatis.learn.mapper.BlogMapper.selectBlogById", 1);
			System.out.println(blog);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(session != null){
				session.close();
			}
		}
	}
	
	/**
     * 通过 SqlSession.getMapper(XXXMapper.class)  接口方式
     * @throws IOException
     */
	@Test
	public void testSelect() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
		Blog blog = blogMapper.selectBlogById(1);
		System.out.println(blog);
		
		if(sqlSession != null){
			sqlSession.close();
		}
		
	}

}

原文地址:https://www.cnblogs.com/lfdingye/p/11638490.html