上一篇文章,我们使用Docker安装好MySQL,从今天开始我们开启MyBatis的学习,说到MyBatis,我们不得不提起的一个概念就是ORM,所谓的ORM就是对象关系映射(Object Relational Mapping),它的优点就是开发人员通过操作Java中对象来操作数据库,实现数据的持久化,MyBatis就是基于ORM概念的框架之一,我相信现在JavaWeb项目,80%公司都在使用,实际项目结构中,Mabatis用在Dao层,有些项目称之为Mapper层,将SQL写入Mapper.xml文件中,提供namespace+sqlId的方式,供开发人员调用,好吧,开启我们今天的内容,MyBatis之环境搭建以及实现最基础的增删改查。
上一篇文章我们已经学习了Docker安装以及启动MySQL,使用docker ps -a确认MySQL数据已经启动
[root@localhost vagrant]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cac5b454bfe2 mysql:5.7 "docker-entrypoint.s…" 3 days ago Up 4 seconds 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql
STATUS是Up状态,说明,MySQL数据库已经正常启动
使用下边的建表语句创建一个Person表,来实现对该表的增删改查
Person表有三个项目(id,name,age)
CREATE TABLE person
(
id INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄'
PRIMARY KEY (id)
);
Mybatis的jar包和代码被托管在github上,通过github下载MyBatis的jar包,我们这里使用3.4.6版本
https://github.com/mybatis/mybatis-3/releases
我们使用MySQL数据库,通过MySQL网站,下载JDBC驱动
我们使用8.0.11版本
https://dev.mysql.com/downloads/connector/j/
JDK我们使用1.8创建Java工程
到这里,如下图所示,我们就完成了MyBatis的开发环境的搭建
定义三个变量(id,name,age),对应Person表的项目,用于SQL语句中where条件的设定以及接收查询结果。
package xxx.xxx.xxx.entry;
public class Person {
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
SQL语句都是编写在Mapper.xml文件中,像外提供一个调用接口(namespace+id),在service层,我们调用Mapper的id,传入参数,接收返回结果。
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xxx.entry.personMapper">
<select id="queryAllPerson" resultType="xxx.xxx.entry.Person">
select * from person
select>
<select id="queryPersonById" resultType="xxx.xxx.entry.Person" parameterType="int">
select * from person where id = #{id}
select>
<insert id="addPerson" parameterType="xxx.xxx.entry.Person">
insert into person values(#{id}, #{name}, #{age})
insert>
<update id="updatePersonById" parameterType="xxx.xxx.entry.Person">
update person set name = #{name}, age = #{age} where id = #{id}
update>
<delete id="deletePersonById" parameterType="int">
delete from person where id = #{id}
delete>
mapper>
该文件是MyBatis的配置文件,它包括数据库信息,Mapper文件的路径,Entity类的别名等等,我们会单开一篇文章来讲解配置文件,通过下边的代码,配置数据库信息以及将编写好的personMapper.xml文件通过< mappers>< mapper>标签注册到该配置文件中。
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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.56.88:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="jp/co/iosoft/entry/personMapper.xml"/>
mappers>
configuration>
完成对Person表的增删改查
package xxx.xxx.entry;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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 TestMyBatis {
public static void main(String[] args) throws IOException {
deletePersonById(1);
deletePersonById(2);
Person person = new Person(1, "zs", 23);
System.err.println("登录前");
queryPersonById(1);
addPerson(person);
System.err.println("登录后");
queryPersonById(1);
person = new Person(1, "li", 24);
System.err.println("更新前");
queryAllPerson();
updatePersonById(person);
System.err.println("更新后");
queryPersonById(1);
System.err.println("删除前");
queryPersonById(1);
deletePersonById(1);
System.err.println("删除后");
queryPersonById(1);
}
public static void queryAllPerson() throws IOException {
// 1.读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.实例化SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.实例化SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4.调用Mapperid(namespace+sqlid),执行SQL
List<Person> persons = session.selectList("xxx.xxx.entry.personMapper.queryAllPerson");
persons.forEach(System.err::println);
}
}
public static void queryPersonById(int id) throws IOException {
// 1.读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.实例化SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.实例化SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4.调用Mapperid(namespace+sqlid),执行SQL
Person person = session.selectOne("xxx.xxx.entry.personMapper.queryPersonById", id);
System.err.println(person);
}
}
public static void addPerson(Person person) throws IOException {
// 1.读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.实例化SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.实例化SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4.调用Mapperid(namespace+sqlid),执行SQL
int count = session.insert("xxx.xxx.entry.personMapper.addPerson", person);
System.err.println("登陆件数:" + count);
// 5.增删改的场合,完成数据提交
session.commit();
}
}
public static void updatePersonById(Person person) throws IOException {
// 1.读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.实例化SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.实例化SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4.调用Mapperid(namespace+sqlid),执行SQL
int count = session.update("xxx.xxx.entry.personMapper.updatePersonById", person);
System.err.println("更新件数:" + count);
// 5.增删改的场合,完成数据提交
session.commit();
}
}
public static void deletePersonById(int id) throws IOException {
// 1.读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 2.实例化SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 3.实例化SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// 4.调用Mapperid(namespace+sqlid),执行SQL
int count = session.delete("xxx.xxx.entry.personMapper.deletePersonById", id);
System.err.println("删除件数:" + count);
// 5.增删改的场合,完成数据提交
session.commit();
}
}
}
通过下边的运行log可以看出,完成对Person表的增删改查
登录前
null
登陆件数:1
登录后
Person [id=1, name=zs, age=23]
更新前
Person [id=1, name=zs, age=23]
更新件数:1
更新后
Person [id=1, name=li, age=24]
删除前
Person [id=1, name=li, age=24]
删除件数:1
删除后
null
到这里,我们就完成了MyBatis之环境搭建以及实现最基础的增删改查,大家可以动手试试,欢迎留言交流,下篇见。