1. 环境搭建 创建项目MyBatis_01,然后创建源码包config用来存放项目所用到的配置文件并首先创建日志文件log4j.xml。创建lib文件夹用来存放所需用到的Jar。
其中log4j.xml的内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?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 >
2. 数据库表创建 使用MySQL创建如下数据库表
1 2 3 4 5 6 CREATE TABLE tbl_employee ( id int(11) PRIMARY KEY AUTO_INCREMENT, last_name varchar(255) , gender char(1) , email varchar(255) );
3. POJO编写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 package com.atguigu.mybatis.bean;public class Employee { private Integer id; private String lastName; private String gender; private String email; public Employee () { super (); } public Employee (Integer id, String lastName, String gender, String email) { super (); this .id = id; this .lastName = lastName; this .gender = gender; this .email = email; } 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 getGender () { return gender; } public void setGender (String gender) { this .gender = gender; } public String getEmail () { return email; } public void setEmail (String email) { this .email = email; } @Override public String toString () { return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", email=" + email + "]" ; } }
4. MyBatis全局配置文件创建 mybatis-config.xml主要是配置一些最基本的上下文参数和运行环境。内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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 ="abc123!" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="EmployeeMapper.xml" /> </mappers > </configuration >
5. 映射器创建 映射器实现将SQL查询到的结果映射为一个POJO,或者将POJO的数据插入到数据库中,并定义一些关于缓存等的重要内容。
首先先编写映射器接口:
1 2 3 4 5 6 7 package com.atguigu.mybatis.mapper;import com.atguigu.mybatis.bean.Employee;public interface EmployeeMapper { public Employee getEmpById (Integer id) ; }
第二步则是编写XML映射文件EmployeeMapper.xml,内容如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?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.mapper.EmployeeMapper" > <select id ="getEmpById" resultType ="com.atguigu.mybatis.bean.Employee" > select id,lastName, gender, email from tbl_employee where id = #{id} </select > </mapper >
6. 测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package com.atguigu.mybatis.test;public class MyBatisTest { @Test public void test () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class); Employee employee = employeeMapper.getEmpById(1 ); System.out.println(employee); } finally { session.close(); } } public SqlSessionFactory getSqlSessionFactory () throws IOException { String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); return sqlSessionFactory; } }
运行结果: 注意:运行后lastName的值为空,这是因为我们在Employee类中的lastName属性和数据库的last_name字段名称不同,这里我们可以更改EmployeeMapper文件中的select语句为:
1 select id,last_name lastName, gender, email from tbl_employee where id = #{id}
后面讲到配置文件时可以用标签属性的设置来更为方便地处理这个问题。
补充:我们也可以使用注解 来实现映射器 使用注解的方式只需要一个接口就可以注入SQL。首先编写EmployeeMapperAnnoation接口文件。
1 2 3 4 5 6 package com.atguigu.mybatis.mapper;public interface EmployeeMapperAnnoation { @Select ("select id,last_name lastName, gender, email from tbl_employee where id = #{id}" ) public Employee selectEmp (Integer id) ; }
在基本配置文件中引入映射器:
1 <mapper class ="com.atguigu.mybatis.mapper.EmployeeMapperAnnoation" />
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Test public void test01 () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(); try { EmployeeMapperAnnoation employeeMapper = session.getMapper(EmployeeMapperAnnoation.class); Employee employee = employeeMapper.getEmpById(1 ); System.out.println(employee); } finally { session.close(); } }