前言:MyBatis是一个支持普通SQL查询,存储过程以及高级映射的持久层框架,也被称为ORM(Object/Relational Mapping,即对象关系映射)框架。以面向对象的方式来操作持久化对象
student.java
package com.xhh.po;
public class Student {
private Integer id;
private String name;
private String age;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
<mapper namespace="com.xhh.mapper.StudentMapper">
<select id="selectStudentById" parameterType="Integer" resultType="com.xhh.po.Student">
select * from t_student where id = #{id}
select>
mapper>
namespace
该属性为这个
指定了唯一的命名空间,通常会设置成包名+SQL映射文件名
中的信息用于执行查询操作的配置,id属性是
元素在映射文件中的唯一标识,parameterType属性用于指定传入的参数的类型,resultType属性用于指定返回结果的类型#{id}
表示该占位符待接收参数的名称为idmybatis-config.xml
<configuration>
<properties resource="db.properties">properties>
<environments default="mariadb">
<environment id="mariadb">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/xhh/mapper/StudentMapper.xml" />
mappers>
configuration>
如上所示,可以创建在src目录下db.properties,将连接数据库的信息写在db.properties中,然后通过${}
使用,它可以让我们更灵活的修改信息。
db.properties
jdbc.driver=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
package com.xhh.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.xhh.po.Student;
public class DBTest {
// id查找一个学生
@Test
public void findStudentById() throws IOException {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
// 3.构建会话
SqlSession sqlSession = build.openSession();
Student student = sqlSession.selectOne("com.xhh.mapper.StudentMapper.selectStudentById",1);
System.out.println(student.toString());
sqlSession.close();
}
}
创建的配置文件如下:
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.xhh=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
其中log4j.logger.com.xhh=DEBUG用于将com.xhh包下所有类的日志级别设置为DEBUG
在入门程序的基础上
在MyBatis的映射文件中,添加操作是通过
元素来实现的,向t_student中插入一条数据,在StudentMapper.xml添加如下配置
<insert id="addStudent" parameterType="com.xhh.po.Student">
insert into t_student(name,age,sex)
values(#{name},#{age},#{sex})
insert>
在测试类DBTest中,添加测试方法
@Test
public void addStudent() throws Exception {
// 1.读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.根据配置文件构建SqlSessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
// 3.构建会话
SqlSession sqlSession = build.openSession();
Student student = new Student();
student.setName("赵五");
student.setSex("男");
student.setAge("20");
int row = sqlSession.insert("com.xhh.mapper.StudentMapper.addStudent", student);
if (row > 0) {
System.out.println("添加" + row + "个学生成功");
} else {
System.out.println("添加失败");
}
sqlSession.commit();
sqlSession.close();
}
可以使用@Ignore
添加在之前的测试方法上,这样就不会执行之前的测试方法。
发现这两个方法前3个步骤基本相同,所以可以写一个工具类,减少代码量
MyBatisUtils.java
package com.xhh.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
把前3个步骤改成: SqlSession sqlSession = MyBatisUtils.getSession();
在MyBatis的映射文件中,删除操作是通过
元素来实现的,在StudentMapper.xml添加如下配置
<delete id="deleteStudent" parameterType="Integer">
delete from t_student where id = #{id}
delete>
在测试类DBTest中,添加测试方法
@Test
public void deleteStudentById() {
SqlSession sqlSession = MyBatisUtils.getSession();
int row = sqlSession.delete("com.xhh.mapper.StudentMapper.deleteStudent", 3);
if (row > 0) {
System.out.println("删除一个学生成功");
} else {
System.out.println("删除失败");
}
sqlSession.commit();
sqlSession.close();
}
跟查询一个学生信息基本相同,在StudentMapper.xml添加如下配置
<select id="selectStudentAll" resultType="com.xhh.po.Student">
select * from t_student
select>
编写测试方法
@Test
public void findStudentAll() {
SqlSession sqlSession = MyBatisUtils.getSession();
List<Student> students = sqlSession.selectList("com.xhh.mapper.StudentMapper.selectStudentAll");
for (Student student : students) {
System.out.println(student.toString());
}
sqlSession.close();
}
在MyBatis的映射文件中,更新操作是通过
元素来实现的,在StudentMapper.xml添加如下配置
<update id="updateStudent" parameterType="com.xhh.po.Student">
update t_student set
name = #{name},age = #{age},sex = #{sex}
where id = #{id}
update>
编写测试方法
@Test
// 更新学生信息
public void updateStudent() {
SqlSession sqlSession = MyBatisUtils.getSession();
Student student = new Student();
student.setId(3);
student.setName("赵五");
student.setSex("女");
student.setAge("17");
int row = sqlSession.update("com.xhh.mapper.StudentMapper.updateStudent", student);
if (row > 0) {
System.out.println("更新学生信息成功");
} else {
System.out.println("更新学生信息失败");
}
sqlSession.close();
}
完成。