MyBatis 介绍
- MyBatis 是一个优秀的基于Java 的特久层框架,它内部封装了JDBC,使开发者只需要关注SQL语句本身, 而不需要花费精力去处理加载驱动、创建连接、创建执行者等复杂的操作。
- MyBatis通过xml 或注解的方式将要执行的各种Statement 配置起来,并通过Java对象和 Statement中 SQL 的动态参数进行映射生成最终要执行的SQL 语句。
- 最后MyBatis 框架执行完 SQL 并将结果映射为 Java 对象并返回。采用ORM 思想解决了实体和数据库映射的问题,对JDBC 进行了封装,屏蔽了 JDBC API 底层访问细节,使我们不用与JDBC API打交道,就可以 完成对数据库的持久化操作。
MyBatis 使用示例
导入mariadb-java-client-2.7.4.jar和mybatis-3.5.7.jar
CREATE DATABASE db1;
use db1;
create table student(
id int auto_increment primary key ,
NAME VARCHAR(20),
age int
);
INSERT INTO student VALUES
(null,'张三',23),(null,'李四',24),(null,'王五',25);
public class Student {
private Integer id;
private String name;
private Integer age;
...略
}
package com.lizicai.dao;
import com.lizicai.bean.Student;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StudentTest01 {
/**
* 查询全部
*/
public static void main(String[] args) throws IOException {
StudentTest01 s = new StudentTest01();
s.selectAll() ;
}
public void selectAll() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4. 获取执行结果
List<Student> list = sqlSession.selectList("StudentMapper.selectAll");
// 5.打印结果
for(Student stu : list){
System.out.println(stu);
}
// 6. 关闭资源
sqlSession.close();
is.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTA Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="mariadb">
<environment id="mariadb">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://192.168.0.100:3306/db1"/>
<property name="username" value="root"/>
<property name="password" value="rootPassword"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="StudentMapper.xml" />
</mappers>
</configuration>
MyBatis 相关API
- Resources: org.apache.ibatis.io.Resources
- 核心方法
返回值 方法名 说明
InputStream getResourceAsStream(String.fileName) 通过类加载器返回指定资源的字节输入流
- SqlSessionFactoryBuilder: org.apache.ibatis.session.SqlSessionFactoryBuilder 获取SqlSessionFactory工厂对象的功能类
- 核心方法
返回值 方法名 说明
SqlSessionFactory build(InputStream.is) 通过指定资源字节输入流获取SqlSession工厂对象
- SqlSessionFactory: org.apache.ibatis.session.SqlSessionFactory: 获取SqlSession构建者对象的工厂接口
- 核心方法
返回值 方法名 说明
SqlSession openSession() 获取SqlSession构建对象,并开户手动提交事务
SqlSession openSession(boolean.autoCommit) 获取SqlSession构建者对象,如果参数为true,则开户自动提交事务
- SqlSession: org.apache.ibatis.session.SqlSession 构建者对象接口. 用于执行SQL, 管理事务, 接口代理.
返回值 方法名 说明
List<E> selectList(String.statement,Object.paramter) 执行查询语句,返回List集合
T selectOne(String.statement,Object.paramter) 执行查询语句,返回一个结果对象
int insert(String.statement,Object.paramter) 执行新增语句,返回影响行数
int update(String.statement,Object.paramter) 执行修改语句,返回影响行数
int delete(String.statement,Object.paramter) 执行删除语句,返回影响行数
void commit() 提交事务
void rollback() 回滚事务
T getMapper(Class<T>.cls) 获取指定接口的代理实现类对象
void close() 释放资源
public class Student { private Integer id; private String name; private Integer age;
public Student(){}
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
...get set略...
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTA Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
mapper: 核心根标签
namespace属性: 名称空间
-->
<mapper namespace="StudentMapper">
<!--
select: 查询功能的标签
id属性: 唯一标识
resultType属性: 指定结果映射对象类型
parameterType属性: 指定参数映射对象类型
-->
<select id="selectAll" resultType="com.lizicai.bean.Student">
SELECT * FROM student
</select>
<select id="selectById" resultType="com.lizicai.bean.Student" parameterType="java.lang.Integer">
SELECT * FROM student WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.lizicai.bean.Student">
INSERT INTO student VALUES (#{id},#{name},#{age})
</insert>
<update id="updateById" parameterType="com.lizicai.bean.Student">
UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}
</update>
<delete id="deleteById" parameterType="java.lang.Integer">
DELETE FROM student WHERE id=#{id};
</delete>
</mapper>
package com.lizicai.dao;
import com.lizicai.bean.Student;
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.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.SwitchPoint;
import java.util.List;
public class StudentTest01 {
/**
* id查询
*/
@Test
public void selectById() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
Student stu = sqlSession.selectOne("StudentMapper.selectById",1);
System.out.println(stu);
sqlSession.close();
is.close();
}
/**
* 更新用户信息
*/
@Test
public void updateById() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4. 获取执行结果
Student stu = new Student(2,"张三",24);
int update = sqlSession.update("StudentMapper.updateById", stu);
sqlSession.commit();
System.out.println(update);
sqlSession.close();
is.close();
}
/**
* 插入数据
* @throws IOException
*/
@Test
public void insert() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
Student stu = new Student(4,"赵六",26);
int insert = sqlSession.insert("StudentMapper.insert", stu);
sqlSession.commit();
System.out.println(insert);
// 6. 关闭资源
sqlSession.close();
is.close();
}
/**
* 删除数据
*/
@Test
public void delete() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
int delete = sqlSession.delete("StudentMapper.deleteById", 4);
System.out.println(delete);
sqlSession.commit();
sqlSession.close();
is.close();
}
/**
* 查询全部
*/
@Test
public void selectAll() throws IOException {
// 1. 加载核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.获取sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4. 获取执行结果
List<Student> list = sqlSession.selectList("StudentMapper.selectAll");
// 5.打印结果
for(Student stu : list){
System.out.println(stu);
}
// 6. 关闭资源
sqlSession.close();
is.close();
}
}
引入数据库连接配置
jdbc.properties
driver=org.mariadb.jdbc.Driver
url=jdbc:mariadb://192.168.0.100:3306/db1
username=root
password=rootPassword
MyBatisConfig.xml
<configuration>
<properties resource="jdbc.properties"></properties>
<environments default="mariadb">
<environment id="mariadb">
<!-- 事务管理, 默认采用JDBC默认的事务-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource数据源信息 type属性 连接池-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<mappers>
<!-- 引入指定的映射配置文件 resource属性指定映射配置文件的名称-->
<mapper resource="StudentMapper.xml" />
</mappers>
</configuration>
起别名
<configuration>
<properties resource="jdbc.properties"></properties>
<!-- 起别名 -->
<typeAliases>
<typeAlias type="com.lizicai.bean.Student" alias="student"></typeAlias>
<package name="com.lizicai.bean"/>
</typeAliases>
<environments default="mariadb">
<environment id="mariadb">
<!-- 事务管理, 默认采用JDBC默认的事务-->
<transactionManager type="JDBC"></transactionManager>
<!-- dataSource数据源信息 type属性 连接池-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
<mappers>
<!-- 引入指定的映射配置文件 resource属性指定映射配置文件的名称-->
<mapper resource="StudentMapper.xml" />
</mappers>
</configuration>
<select id="selectAll" resultType="student">
SELECT * FROM student
</select>
<select id="selectById" resultType="com.lizicai.bean.Student" parameterType="int">
SELECT * FROM student WHERE id = #{id}
</select>
常见别名
别名 数据类型
string java.lang.String
long java.lang.Long
int java.lang.Integer
double java.lang.Double
boolean java.lang.Boolean
dao层实现
package com.lizicai.mapper;
import com.lizicai.bean.Student;
import java.util.List;
public interface StudentMapper {
// 查询全部
public abstract List<Student> selectAll();
// 根据id查询
public abstract Student selectById(Integer id);
// 新增数据
public abstract Integer insert(Student stu);
// 修改数据
public abstract Integer update(Student stu);
// 删除数据
public abstract Integer delete(Integer id);
}
package com.lizicai.mapper.impl;
import com.lizicai.bean.Student;
import com.lizicai.mapper.StudentMapper;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class StudentMapperImpl implements StudentMapper {
// 查询所有学生
@Override
public List<Student> selectAll() {
List<Student> list =null;
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
list = sqlSession.selectList("StudentMapper.selectAll");
} catch (IOException e) {
e.printStackTrace();
} finally {
if( is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( sqlSession != null){
sqlSession.close();
}
}
return list;
}
// 根据id查询
@Override
public Student selectById(Integer id) {
Student stu = null;
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
stu = sqlSession.selectOne("StudentMapper.selectById",id);
} catch (IOException e) {
e.printStackTrace();
}finally {
if( is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( sqlSession != null){
sqlSession.close();
}
}
return stu;
}
// 新增数据
@Override
public Integer insert(Student stu) {
Integer result = null;
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
result = sqlSession.insert("StudentMapper.insert", stu);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
if( is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( sqlSession != null){
sqlSession.close();
}
}
return result;
}
// 新增数据
@Override
public Integer update(Student stu) {
Integer result = null;
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
result = sqlSession.update("StudentMapper.updateById", stu);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
if( is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( sqlSession != null){
sqlSession.close();
}
}
return result;
}
// 删除数据
@Override
public Integer delete(Integer id) {
Integer result = null;
InputStream is = null;
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("MyBatisConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 默认提交事务提交
sqlSession = sqlSessionFactory.openSession(true);
result = sqlSession.delete("StudentMapper.deleteById", id);
} catch (IOException e) {
e.printStackTrace();
} finally {
if( is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( sqlSession != null){
sqlSession.close();
}
}
return result;
}
}
package com.lizicai.service;
import com.lizicai.bean.Student;
import java.util.List;
public interface StudentService {
List<Student> selectAll();
// 根据id查询
Student selectById(Integer id);
// 新增数据
Integer insert(Student stu);
// 修改数据
Integer update(Student stu);
// 删除数据
Integer delete(Integer id);
}
package com.lizicai.service.impl;
import com.lizicai.bean.Student;
import com.lizicai.mapper.StudentMapper;
import com.lizicai.mapper.impl.StudentMapperImpl;
import com.lizicai.service.StudentService;
import java.util.List;
public class StudentServiceImpl implements StudentService {
private StudentMapper mapper = new StudentMapperImpl();
// 查询全部
@Override
public List<Student> selectAll() {
return mapper.selectAll();
}
// 根据id查询
@Override
public Student selectById(Integer id) {
return mapper.selectById(id);
}
@Override
public Integer insert(Student stu) {
return mapper.insert(stu);
}
@Override
public Integer update(Student stu) {
return mapper.update(stu);
}
@Override
public Integer delete(Integer id) {
return mapper.delete(id);
}
}
package com.lizicai.controller;
import com.lizicai.bean.Student;
import com.lizicai.service.StudentService;
import com.lizicai.service.impl.StudentServiceImpl;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
public class StudentController {
// 创建业务层对象
private StudentService service = new StudentServiceImpl();
// 查询全部功能测试
@Test
public void selectAll(){
List<Student> list = service.selectAll();
for(Student stu : list){
System.out.println(stu);
}
}
// 根据id查询学生
@Test
public void selectById(){
Student stu = service.selectById(1);
System.out.println(stu);
}
// 新增学生
@Test
public void insert(){
Student stu = new Student(4,"赵六",26);
Integer insert = service.insert(stu);
System.out.println(insert);
}
// 更新学生信息
@Test
public void update(){
Student stu = new Student(3,"王五五",25);
int update = service.update(stu);
System.out.println(update );
}
//删除学生信息
@Test
public void delete(){
int delete = service.delete(4);
System.out.println(delete);
}
}
LOG4J
下载log4j-1.2.17.jar版本
加入libs中
在MyBatisConfig.xml中引用log4j
<configuration>
<!-- 数据库账号配置-->
<properties resource="jdbc.properties"></properties>
<!-- 配置log4j-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<configuration>
log4j.properties
# Global logging configuration
# ERROR WARN INFO DEBUG
log4j.rootLogger=DEBUG, stdout
#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