创建项目MyBatis_01,然后创建源码包config用来存放项目所用到的配置文件并首先创建日志文件log4j.xml。创建lib文件夹用来存放所需用到的Jar。
其中log4j.xml的内容如下:
<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>
CREATE TABLE tbl_employee (
id int(11) PRIMARY KEY AUTO_INCREMENT,
last_name varchar(255) ,
gender char(1) ,
email varchar(255)
);
package com.atguigu.mybatis.bean;
public class Employee {
private Integer id;
private String lastName; //该属性和数据库表的对应字段名last_name不同
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 + "]";
}
}
mybatis-config.xml主要是配置一些最基本的上下文参数和运行环境。内容如下:
<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>
映射器实现将SQL查询到的结果映射为一个POJO,或者将POJO的数据插入到数据库中,并定义一些关于缓存等的重要内容。
首先先编写映射器接口:
package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.bean.Employee;
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
第二步则是编写XML映射文件EmployeeMapper.xml,内容如下所示:
<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>
package com.atguigu.mybatis.test;
public class MyBatisTest {
@Test
public void test() throws IOException {
//1.根据MyBatis的配置文件,即mybatis-config.xml创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2.获取session实例开启会话,其能直接执行*已经映射的SQL语句*
SqlSession session = sqlSessionFactory.openSession();
try {
//3.获取接口的实现类对象
EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
//4.执行查询操作
Employee employee = employeeMapper.getEmpById(1);
System.out.println(employee);
} finally {
//4.关闭会话session
session.close();
}
}
//根据MyBatis的配置文件,即mybatis-config.xml创建SqlSessionFactory
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语句为:
select id,last_name lastName, gender, email from tbl_employee where id = #{id}
后面讲到配置文件时可以用标签属性的设置来更为方便地处理这个问题。
补充:我们也可以使用注解来实现映射器
使用注解的方式只需要一个接口就可以注入SQL。首先编写EmployeeMapperAnnoation接口文件。
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);
}
在基本配置文件中引入映射器:
<mapper class="com.atguigu.mybatis.mapper.EmployeeMapperAnnoation"/>
测试代码:
@Test
public void test01() throws IOException {
//1.根据MyBatis的配置文件,即mybatis-config.xml创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2.获取session实例,能直接执行*已经映射的SQL语句*
SqlSession session = sqlSessionFactory.openSession();
try {
//3.获取接口的实现类对象
EmployeeMapperAnnoation employeeMapper = session.getMapper(EmployeeMapperAnnoation.class);
//4.执行查询操作
Employee employee = employeeMapper.getEmpById(1);
System.out.println(employee);
} finally {
//4.关闭会话session
session.close();
}
}