个人编写 MyBatis项目实战—仅供小白学习参考
一、搭建数据库
#建数据库
CREATE DATABASE `li`;
#用数据库
USE `li`;
#建表
CREATE TABLE `student`(
`id` INT(10) NOT NULL,
`name`VARCHAR(30) DEFAULT NULL,
`tid`INT(10)DEFAULT NULL,
`grade`INT(10) DEFAULT NULL,
`sex` VARCHAR(30)DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
二、创建项目
2.1 创建父项目
1、创建一个maven项目
填写相关信息 作为【父工程】
2、选择 maven环境本地仓库和地址
3、删掉 该【父工程】
的src
文件夹
2.2 创建子模块
查看父子项目模块
2.3 编写配置文件
1、编写pom.xml
在【父工程】的pom.xml
文件中导入依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
在【父工程】的pom.xml
文件中设置resources,防止资源导出失败
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2、【子模块】resources
文件下 创建mybatis-config.xml
添加下面内容
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>
<!--引入外部文件-->
<properties resource="db.properties"/>
<settings>
<!--开启驼峰命名转换-->
<setting name="mapUnderscoreToCamelCase" value="true"></setting>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
<!--开启默认的日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.li.pojo.Student" alias="student"/>
</typeAliases>
<!--配置环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/><!--事务管理——jdbc-->
<!--连接数据库 这里通过引入外部文件的方式-->
<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>
</environments>
<!--mapper映射-->
<mappers>
<mapper resource="com/li/dao/StudentMapper.xml"/>
</mappers>
</configuration>
3、【子模块】resources
文件下 创建db.properties
添加下面内容
#连接数据库信息 根据自己情况改写
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
三、编写代码
3.1 实体类
pojo层编写实体类
Student.java
其中 get/set/有参/无参方法 的编写
方法一:
- 如下图所示,传统的编写get/set/有参/无参方法
package com.li.pojo;
public class Student {
private int id;
private String name;
private int tid;
private String sex;
private int grade;
public Student(int id, String name, int tid, String sex, int grade) {
this.id = id;
this.name = name;
this.tid = tid;
this.sex = sex;
this.grade = grade;
}
public Student() {
}
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 getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
方法二:
- 使用lombok插件 使用注解方式来直接插入
- lombok的安装使用可以参考:
https://blog.csdn.net/junR_980218/article/details/124059764
3.2 接口
dao层编写接口
StudentMapper.java
package com.li.dao;
import com.li.pojo.Student;
import java.util.List;
import java.util.Map;
public interface StudentMapper {
//查询全部学生的信息
List<Student> queryStudent ();
//根据id查询学生
Student queryStudentId(int i);
//动态查询语句
List<Student> queryStudentDong(Map map);
//添加学生信息
int addStudent(Student student);
//修改学生信息
int updateStudent(Student student);
//删除学生信息
int deleteStudentId(int id);
}
3.3 接口的实现—配置文件
最好跟接口在一个包下 即直接写dao层
StudentMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.li.dao.StudentMapper"><!--namespace指向 接口的配置文件***.xml-->
<!--添加二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"
/><!--添加全局缓存 采用FIFO方式清理缓存 flushInterval 每隔60秒清理缓存-->
<select id="queryStudent" resultType="student">
<!--id指的是 接口中该方法名
resultType 指的是实体类的com.li.pojo.Student
这里写student是因为在mybatis中给这个实体类起了个别名-->
select * from li.student
</select>
<select id="queryStudentId" parameterType="student" resultType="student">
<!--通过id来查询-->
select * from li.student
where id=#{id};
</select>
<!--动态查询-->
<select id="queryStudentDong" parameterType="map" resultType="student">
select *
from li.student
where 1=1
<if test="name != null">
and name = #{name}
</if>
</select>
<insert id="addStudent" parameterType="student">
<!--添加数据-->
insert into li.student(id,name,tid,grade,sex)
values(#{id},#{name},#{tid},#{grade},#{sex})
</insert>
<update id="updateStudent" parameterType="student">
<!--通过id来修改 更新数据-->
update li.student
set
name =#{name},
tid=#{tid},
grade=#{grade},
sex=#{sex}
where id=#{id};
</update>
<delete id="deleteStudentId" parameterType="_int">
<!--通过id删除数据-->
delete
from li.student
where id=#{id};
</delete>
</mapper>
3.4 工具类
utils层编写工具类
MybatisUtils.java
package com.li.utils;
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;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用mybatis的第一步:获取sqlSessionFactory的对象
String resource ="mybatis-configg.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (IOException e){
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
//你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
3.5 测试类
test层编写测试类
StudentTest.java
package com.li.dao;
import com.li.pojo.Student;
import com.li.utils.MybatisUtils;
import jdk.internal.org.objectweb.asm.Handle;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentTest {
@Test //查询全部学生信息
public void queryStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.queryStudent();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
@Test //通过id查询学生信息
public void queryStudentId(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.queryStudentId(1);
System.out.println(student);
sqlSession.close();
}
@Test
public void queryStudentDong(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("name","zmm");
List<Student> students = mapper.queryStudentDong(objectObjectHashMap);
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
@Test //插入学生信息
public void addStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student=new Student();
student.setId(1);
student.setName("lyp");
student.setTid(1);
student.setSex("女");
student.setGrade(1);
mapper.addStudent(student);
student.setId(2);
student.setName("zmm");
student.setTid(2);
student.setSex("女");
student.setGrade(2);
int i1 = mapper.addStudent(student);
if(i1>0){
System.out.println("i1添加成功");
}
student.setId(3);
student.setName("lzp");
student.setTid(3);
student.setSex("男");
student.setGrade(3);
int i2 = mapper.addStudent(student);
if(i2>0){
System.out.println("i2添加成功");
}
student.setId(4);
student.setName("wwp");
student.setTid(4);
student.setSex("男");
student.setGrade(4);
int i = mapper.addStudent(student);
if(i>0){
System.out.println("i添加成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test //通过查询id 来更新
public void updateStudent(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int i = mapper.updateStudent(new Student(3, "lsw", 3, "男", 4));
if (i>0){
System.out.println("更新成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test //通过id 删除信息
public void deleteStudentId(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int i = mapper.deleteStudentId(1);
if(i>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
}
注意:
测试的过程中,增删改必须提交事务才能提交到数据库,否则数据库中的数据是没有变化的,查询不需要提交事务!
四、源码地址
源码地址:
链接:https://pan.baidu.com/s/1gQQNKd03KFjNWEw6uF-CIQ
提取码:9802