环境准备
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;}@Overridepublic 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 configurationPUBLIC "-//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 mapperPUBLIC "-//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学习笔记大纲