环境准备

1.创建数据库表

create table tbl_employee (
id int(11) primary key AUTO_INCREMENT comment "ID",
last_name varchar(20) default null comment "姓名",
email varchar(20) default null comment "邮件",
gender varchar(1) default null comment "性别"
)

2.准备依赖的jar包

  • log4j.jar
  • mybatis-3.4.1.jar
  • mysql-connector-java-5.1.37-bin.jar

如果是maven项目,加入以下依赖:

<!-- 1.mybatis必须依赖包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 2.mysql数据库连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- 3.日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

3.创建项目:MyBatis_01_HelloWorld

项目结构如下:

Employee.java源码如下:

package com.atguigu.mybatis.bean;

public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} @Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + "]";
} }

EmployeeMapper.java源码如下:

package com.atguigu.mybatis.dao;
import com.atguigu.mybatis.bean.Employee; /**
* mybatis接口式編程
* @author kancy
*/
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}

配置文件,在下面添加。

4.加入配置文件(Mybatis全局配置文件,Mybatis SQL Mapper映射配置文件,log4j配置文件)

1) Mybatis全局配置文件:mybatis-config.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="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
<mappers>
<mapper resource="mappers/EmployeeMapper.xml" />
</mappers>
</configuration>

2) sql mapper映射文件:EmployeeMapper.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.atguigu.mybatis.dao.EmployeeMapper">
<!--
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值
-->
<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
select id,last_name lastName,email,gender from tbl_employee where id = #{id}
</select>
</mapper>

3) log4j日志配置文件:log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

5.编写测试

1)硬编码编程的调用方式

public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} /**
* 1、根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
* 2、sql映射文件;配置了每一个sql,以及sql的封装规则等。
* 3、将sql映射文件注册在全局配置文件中
* 4、写代码:
* 1)、根据全局配置文件得到SqlSessionFactory;
* 2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
* 一个sqlSession就是代表和数据库的一次会话,用完关闭
* 3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。
* @throws IOException
*/
@Test
public void test01() throws IOException {
// 2、获取sqlSession实例,能直接执行已经映射的sql语句
// sql的唯一标识:statement Unique identifier matching the statement to use.
// 执行sql要用的参数:parameter A parameter object to pass to the statement.
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
Employee employee = openSession.selectOne(
"com.atguigu.mybatis.dao.EmployeeMapper.getEmpById", 1);
System.out.println(employee);
} finally {
openSession.close();
}
}

2)接口式编程的调用方式

public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void test02() throws IOException {
// 1、获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
// 2、获取sqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
try {
// 3、获取接口的实现类对象
//会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
System.out.println(mapper.getClass());
System.out.println(employee);
} finally {
openSession.close();
}
}

6.整体项目结构如下:

7.总结

1)mybatis根据全局配置文件来创建SqlSessionFactory工厂对象,再通过工厂对象创建SqlSession会话对象(一次会话,一次连接),SqlSession再sql方法Id获取对应的sql语句并且执行改语句,sql语句配置在SQL Mapper映射文件中,每一个SQL都会有一个唯一ID。

2)SqlSession 的实例和connection一样 不是线程安全的,因此是不能被共享的。SqlSession每次 使用完成后需要正确关闭,这个关闭操作是必须的。SqlSession可以直接调用方法的id进行数据库操作,但是我们一般还是推荐使用SqlSession获取到Dao接口的代理类,执行代理对象的方法,可以更安全的进行类型检查操作。

返回到Mybatis学习笔记大纲

最新文章

  1. GJM : C#设计模式汇总整理——导航 【原创】
  2. .NET Core全面扫盲贴
  3. MMORPG大型游戏设计与开发(服务器 游戏场景 地图和区域)
  4. thinkphp中的setInc、setDec方法
  5. dispatch_set_target_queue 说明
  6. ASP.Net上传大文件解决方案之IIS7.0下的配置
  7. 第18/24周 乐观并发控制(Optimistic Concurrency)
  8. swift邮箱手机验证
  9. javascript document.compatMode属性
  10. 谈谈分布式事务之二:基于DTC的分布式事务管理模型[下篇]
  11. JavaScript 客户端JavaScript之事件(DOM API 提供模块之一)
  12. sql server 存储过程分隔split
  13. Creating beautiful charts in chinese with ggplot2
  14. 大白话Vue源码系列目录
  15. ●洛谷 P3616 富金森林公园
  16. ACM Piggy Bank
  17. javaScript设计模式之面向对象编程(object-oriented programming,OOP)(二)
  18. Segment 李超线段树
  19. python 回溯法 子集树模板 系列 —— 19、野人与传教士问题
  20. hdu 1175 bfs+priority_queue

热门文章

  1. Why Use the Widget Factory?
  2. HDU2602 Bone Collector(01背包)
  3. Linux驱动开发6——DDR内存分配
  4. php对bom的处理
  5. 去掉IE浏览器里的脚本控件提示
  6. 测开之路一百零八:bootstrap表格
  7. UI自动化之特殊处理二(弹框\下拉框\选项\文件上传)
  8. UI自动化之8种基础定位
  9. vue-methods方法与computed计算属性的差别
  10. 刷题——一道全排列的题目(Permutations)