一、下载MyBatis
MyBatis将所有的项目托管到了github上,因此我们在github上搜索下载MyBatis下载
二、创建对应的数据库表和JavaBean类
创建数据表:
CREATE TABLE tab1_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255)
)
创建对应的JavaBean类
package com.atorg.mybatis.bean;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName; //注意此处与数据中的字段并不对应???
private String email;
private String gender;
public Employee() {
super();
}
public Employee(Integer id, String lastName, String email, String gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = 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 + "]";
}
}
三、根据官方文档(下文按照官方文档的步骤实现一个”HelloWorld”)
官方文档在一开始下载的依赖和文档中有,如果没有可以到以下地址下载
官方文档下载链接 提取码:hpaq 内附有Mybatis文档与依赖包
1.导入相关依赖
引入MyBatis的jar包,以及操作数据库驱动的jar包,为显示方便引入log4j日志包,引入log4j时必须要在类路径下放一个log4j.xml文件(在以上的链接中有这些jar包)
2.创建一个xml文件(全局配置文件)[ Building SqlSessionFactory from XML]
创建一个xml文件(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_plus"/>
<property name="username" value="root"/>
<property name="password" value="1234567890"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--sql映射文件一定要注册在全局配置文件中(就是此文件中)-->
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
3.根据xml文件创建一个SqlSessionFactory对象
public class MyBatisTest {
//此处的resource内容就是上面创建的xml文件的路径名
public void test() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
}
}
4.获取sqlSession实例,能直接执行已经映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
5.用获取的sqlSession调用增删改查的方法 [Acquiring a SqlSession from SqlSessionFactory]
//第一个参数值为sql映射文件中**namespace+具体增删改查对应的唯一id的值**
//第二个参数是执行sql时传入的参数
openSession.selectOne(arg0,arg1);//查询
openSession.delete(arg0,arg1);//删除
openSession.update(arg0,arg1);//更新
openSession.insert(arg0,arg1);//插入
//第一个参数 *statement是一个唯一标识:Unique identifier matching the statement to use.
//第二个参数*parameter是执行sql语句的一个参数:A parameter object to pass to the statement.
6.创建sql映射的xml文件 [Exploring Mapped SQL Statements]
<?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="org.mybatis.example.BlogMapper">
<select id="selectEmp" resultType="com.atorg.mybatis.bean.Employee">
select id,last_name lastName,gender,email from tab1_employee where id = #{id} <!--给数据库变量起别名解决字段不匹配问题-->
</select>
</mapper>
【namespace】:名称空间用来映射sql语句的类的全类名
【id】:为select的唯一标识,内容为具体方法的方法名
【resultType】:返回值类型,查询完成之后要返回的类型
【#{id}】:从传递过来的参数中取出id值
7.完整文件
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_plus"/>
<property name="username" value="root"/>
<property name="password" value="1234567890"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
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.atorg.mybatis.EmployeeMapper">
<!-- 查询数据 -->
<select id="selectEmp" resultType="com.atorg.mybatis.bean.Employee">
select * from tab1_emp where id = #{id}
</select>
<!-- 插入数据 -->
<insert id="addEmp" parameterType="com.atorg.mybatis.bean.Employee" useGeneratedKeys="true" keyProperty="id">
insert into tab1_emp(last_name,email,gender) values(#{lastName},#{email},#{gender})
</insert>
<!-- 更新数据 -->
<update id="updateEmp" parameterType="com.atorg.mybatis.bean.Employee">
update tab1_emp
set last_name=#{lastName},email=#{email},gender=#{gender}
where id =#{id}
</update>
<!-- 删除数据 -->
<!-- public void deleteEmpByTd(Integer id); -->
<delete id="deleteEmp" parameterType="com.atorg.mybatis.bean.Employee">
delete from tab1_emp where id=#{id}
</delete>
</mapper>
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>
四、进行测试
测试类
package com.atorg.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.atorg.mybatis.bean.Employee;
public class MyBatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlsession实例,能直接执行已经映射的sql语句
SqlSession session = sqlSessionFactory.openSession();
try {
// Object employee = session.selectOne("com.atorg.mybatis.EmployeeMapper.selectEmp", 5);
// System.out.println(employee);
// session.insert("com.atorg.mybatis.EmployeeMapper.addEmp", new Employee("Jack","Jack@qq.com","1"));
// session.commit();
// System.out.println("插入成功");
// session.delete("com.atorg.mybatis.EmployeeMapper.deleteEmp", 5);
// session.commit();
// System.out.println("删除成功");
session.update("com.atorg.mybatis.EmployeeMapper.updateEmp", new Employee(5,"lucy","lucy@qq.com","0"));
session.commit();
System.out.println("更新成功");
} finally {
session.close();
}
}
}
查看数据库原始状态
测试添加方法( “Bob”,”Bob@163.com“,”0” )
测试查询方法(查询5号)
测试删除方法(删除5号)
测试跟新方法(更新1号【”Jack”,”Jack@git.com“,”1”】)
五、升级[Using an interface (e.g. BlogMapper.class) that properly describes the parameter and return value for a given statement]
使用上述代码可以实现对数据库的增删改查操作,但是我们在测试类中传入参数很麻烦,因此我们引进了接口式编程,我们可以创建一个接口,接口来描述我们给定的sql语句的参数和返回值
1.创建一个接口
package com.atorg.mybatis.dao;
import com.atorg.mybatis.bean.Employee;
public interface EmployeeMapper {
public Employee getEmpByTd(Integer id);
public void addEmp(Employee employee);
public void updateEmp(Employee employee);
public void deleteEmpByTd(Integer id);
}
mybatis提供一个特殊的功能,接口可以与配置文件进行动态绑定
【namespce】:指定为接口的全类名
【id】:增删改查标签的id指定为接口对应的方法名
2.此时的测试类(以查询为例其他类似)
@Test
public void test02() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlsession实例,能直接执行已经映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper eMapper=openSession.getMapper(EmployeeMapper.class);
Employee employee=eMapper.getEmpByTd(1);//直接调用接口的查询员工方法
System.out.println(employee);
}finally{
openSession.close();
}
}
【getMapper】:会为接口自动创建一个代理对象,用得到的代理对象去调用接口的增删改查放方法
查询结果