学习MyBatis之简单入门HelloWorld
转:https://blog.csdn.net/gaomb_1990/article/details/78299784
一、准备
Eclipse:Luna Service Release 1 (4.4.1)
MyBatis:org.mybatis.mybatis-3.2.8
JDK:1.7.0_79
MyBatis:org.mybatis.mybatis-3.2.8
JDK:1.7.0_79
二、步骤
♦搭建一个Maven工程MyBatisDemo
♦POM文件导入相关依赖
- <span style="font-family:'KaiTi_GB2312';"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.queen.mybatis</groupId>
- <artifactId>MyBatisDemo</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>war</packaging>
- <dependencies>
- <!-- 单元测试 -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.10</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.2.8</version>
- </dependency>
- <!-- MySql -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.32</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.6.4</version>
- </dependency>
- </dependencies>
- </project></span>
♦配置MyBatis的核心文件mybatis-config.xml
- <span style="font-family:'KaiTi_GB2312';"><?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/mybatis" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="UserMapper.xml" />
- </mappers>
- </configuration></span>
♦配置log4j.properties
- <span style="font-family:'KaiTi_GB2312';">log4j.rootLogger=DEBUG,A1
- log4j.logger.com.queen = DEBUG
- log4j.logger.org.mybatis = DEBUG
- log4j.appender.A1=org.apache.log4j.ConsoleAppender
- log4j.appender.A1.layout=org.apache.log4j.PatternLayout
- log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n</span>
♦编写接口类UserMapper
- <span style="font-family:'KaiTi_GB2312';">/**
- * @since 2017-07-15
- * @author queen
- * 定义一个UserMapper接口
- *
- */
- public interface UserMapper {
- /**
- * 根据ID查找用户
- * @param id
- * @return
- */
- public User findUserById(int id);
- }</span>
♦编写接口映射文件UserMapper.xml
- <span style="font-family:'KaiTi_GB2312';"><?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.queen.mybatis.mapper.UserMapper">
- <select id="findUserById" resultType="com.queen.mybatis.bean.User">
- select id, loginId, userName, role, note from t_user where id = #{id}
- </select>
- </mapper></span>
♦编写JavaBean类User
- <span style="font-family:'KaiTi_GB2312';">/**
- * @since 2017-07-15
- * @author queen
- * 定义一个Java类
- *
- */
- public class User {
- // ID,唯一性
- private String id;
- // 登录ID
- private String loginId;
- // 用户名
- private String userName;
- // 角色
- private String role;
- // 备注
- private String note;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getLoginId() {
- return loginId;
- }
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
- public String getNote() {
- return note;
- }
- public void setNote(String note) {
- this.note = note;
- }
- @Override
- public String toString() {
- return "User [id=" + id + ", loginId=" + loginId + ", userName="
- + userName + ", role=" + role + ", note=" + note + "]";
- }
- }</span>
♦最后编写测试类
- <span style="font-family:'KaiTi_GB2312';">/**
- * @since 2017-07-15
- * @author queen
- * 编写测试Java类
- *
- */
- public class MyBatisTest {
- public SqlSessionFactory getSqlSessionFactory() throws IOException {
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- return new SqlSessionFactoryBuilder().build(inputStream);
- }
- @Test
- public void test() throws IOException {
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- SqlSession openSession = sqlSessionFactory.openSession();
- try {
- User user = openSession.selectOne(
- "com.queen.mybatis.mapper.UserMapper.findUserById", "1");
- System.out.println(user);
- } finally {
- openSession.close();
- }
- }
- }</span>
♦测试运行一下,查找ID是1的数据,日志详细过程完美的打印在控制台
- <span style="font-family:'KaiTi_GB2312';">2017-07-15 16:52:43,862 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Opening JDBC Connection
- 2017-07-15 16:52:44,305 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Created connection 706757729.
- 2017-07-15 16:52:44,305 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2a204461]
- 2017-07-15 16:52:44,309 [main] [com.queen.mybatis.mapper.UserMapper.findUserById]-[DEBUG] ==> Preparing: select id, loginId, userName, role, note from t_user where id = ?
- 2017-07-15 16:52:44,372 [main] [com.queen.mybatis.mapper.UserMapper.findUserById]-[DEBUG] ==> Parameters: 1(String)
- 2017-07-15 16:52:44,419 [main] [com.queen.mybatis.mapper.UserMapper.findUserById]-[DEBUG] <== Total: 1
- User [id=1, loginId=Sabot, userName=萨博, role=革命军, note=革命军的二号人物,同艾斯一样,为蒙奇·D·路飞的哥哥(义兄)。]
- 2017-07-15 16:52:44,420 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2a204461]
- 2017-07-15 16:52:44,421 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2a204461]
- 2017-07-15 16:52:44,421 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Returned connection 706757729 to pool.</span>
三、总结
MyBatis整个调用过程:
根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象有数据源一些运行环境信息
sql映射文件;配置了每一个sql,以及sql的封装规则等。
将sql映射文件注册在全局配置文件中
写代码:
①根据全局配置文件,SqlSessionFactoryBuilder得到SqlSessionFactory
②使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象有数据源一些运行环境信息
sql映射文件;配置了每一个sql,以及sql的封装规则等。
将sql映射文件注册在全局配置文件中
写代码:
①根据全局配置文件,SqlSessionFactoryBuilder得到SqlSessionFactory
- <span style="font-family:'KaiTi_GB2312';">public SqlSessionFactory getSqlSessionFactory() throws IOException {
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- return new SqlSessionFactoryBuilder().build(inputStream);
- }</span>
- <span style="font-family:'KaiTi_GB2312';">SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();</span>
④使用sql的唯一标志来告诉MyBatis执行哪个sql,sql都是保存在sql映射文件中的。
至此,我们关于MyBatis教程之简单的入门介绍完毕。只做了简单的查询动作。
为测试3.0奋斗吧!