在操作系统的基础上,将原生 JDBC 引入 MyBatis 框架
对 MyBatis 的理解不深刻,感觉比原生更麻烦了,估计还需要后续的进一步学习才能体会到 MyBatis 的优势吧
项目结构
|warship-demo // 模块
|--|src // 源代码和测试代码目录
|--|--|main // 源代码目录
|--|--|--|java // 源代码Java文件目录
|--|--|--|resources // 源代码配置文件目录
|--|--|test // 测试代码目录
|--|--|--|java // 测试Java文件目录
|--|pom.xml // 项目核心配置文件
源代码和测试代码
按照编写顺序
pom.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cookies</groupId>
<artifactId>warship-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
<!-- logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>
</project>
mybatis-config.xml
src/main/resources/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>
<typeAliases>
<package name="com.cookies.pojo"/>
</typeAliases>
<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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载SQL映射文件 -->
<mapper resource="com/cookies/mapper/WarshipMapper.xml"/>
</mappers>
</configuration>
logback.xml
src/main/resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.cookies" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
Warship.java
src/main/java/com/cookies/pojo/Warship.java
package com.cookies.pojo;
public class Warship {
private int id;
private String englishName;
private String chineseName;
private String camp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEnglishName() {
return englishName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public String getChineseName() {
return chineseName;
}
public void setChineseName(String chineseName) {
this.chineseName = chineseName;
}
public String getCamp() {
return camp;
}
public void setCamp(String camp) {
this.camp = camp;
}
@Override
public String toString() {
return "Warship{" +
"id=" + id +
", englishName='" + englishName + '\'' +
", chineseName='" + chineseName + '\'' +
", camp='" + camp + '\'' +
'}';
}
}
WarshipMapper.java
src/main/java/com/cookies/mapper/WarshipMapper.java
package com.cookies.mapper;
import com.cookies.pojo.Warship;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface WarshipMapper {
// 查询所有舰娘数据
List<Warship> selectAll();
// 按照条件进行查询
List<Warship> selectByConditions(
@Param("id") int id,
@Param("englishName") String englishName,
@Param("chineseName") String chineseName,
@Param("camp") String camp
);
// 增加舰娘数据
void add(Warship warship);
// 删除舰娘数据
void deleteById(int id);
// 修改舰娘数据
void update(
@Param("id") int id,
@Param("englishName") String englishName,
@Param("chineseName") String chineseName,
@Param("camp") String camp
);
}
WarshipMapper.xml
src/main/resources/com/cookies/mapper/WarshipMapper.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.cookies.mapper.WarshipMapper">
<resultMap id="warshipResultMap" type="warship">
<result column="english_name" property="englishName"/>
<result column="chinese_name" property="chineseName"/>
</resultMap>
<!-- 查询所有舰娘数据 -->
<select id="selectAll" resultMap="warshipResultMap">
select * from tb_warship;
</select>
<!-- 按照中文名进行查询 -->
<select id="selectByConditions" resultMap="warshipResultMap">
select * from tb_warship
<where>
<if test="id != null and id != 0">
and id = #{id}
</if>
<if test="englishName != null and englishName != '未知'">
and english_name = #{englishName}
</if>
<if test="chineseName != null and chineseName != '未知'">
and chinese_name = #{chineseName}
</if>
<if test="camp != null and camp != '未知'">
and camp = #{camp}
</if>
</where>
</select>
<!-- 增加舰娘数据 -->
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_warship(english_name, chinese_name, camp)
values(#{englishName}, #{chineseName}, #{camp})
</insert>
<!-- 删除舰娘数据 -->
<delete id="deleteById">
delete from tb_warship
where id = #{id}
</delete>
<!-- 修改舰娘数据 -->
<update id="update">
update tb_warship
set english_name = #{englishName}, chinese_name = #{chineseName}, camp = #{camp}
where id = #{id}
</update>
</mapper>
MyBatisTest.java
src/test/java/com/cookies/test/MyBatisTest.java
package com.cookies.test;
import com.cookies.mapper.WarshipMapper;
import com.cookies.pojo.Warship;
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;
import java.util.Scanner;
public class MyBatisTest {
public static void main(String[] args) throws IOException {
// 1.加载MyBatis的配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 3.获取Mapper接口
WarshipMapper warshipMapper = sqlSession.getMapper(WarshipMapper.class);
// 4.执行方法
warshipManagementSystem(sqlSession, warshipMapper);
}
private static void warshipManagementSystem(SqlSession sqlSession, WarshipMapper warshipMapper) {
Scanner sc = new Scanner(System.in);
System.out.println("---------------------");
System.out.println("---------------------");
System.out.println("欢迎进入管理系统,指挥官");
System.out.println("1.增加舰娘数据");
System.out.println("2.删除舰娘数据");
System.out.println("3.修改舰娘数据");
System.out.println("4.查询舰娘数据");
System.out.println("5.退出");
System.out.println("请输入下一步操作");
int chooseNumber = sc.nextInt();
switch (chooseNumber) {
case 1 -> createWarship(sqlSession, warshipMapper);
case 2 -> deleteWarship(sqlSession, warshipMapper);
case 3 -> updateWarship(sqlSession, warshipMapper);
case 4 -> readWarship(sqlSession, warshipMapper);
case 5 -> {
// 5.释放资源
sqlSession.close();
System.exit(0);
}
}
}
private static void readWarship(SqlSession sqlSession, WarshipMapper warshipMapper) {
Scanner sc = new Scanner(System.in);
System.out.println("---------------------");
System.out.println("查询舰娘数据");
System.out.println("1.查询所有舰娘数据");
System.out.println("2.按照条件进行查询");
System.out.println("请输入下一步操作");
int chooseNumber = sc.nextInt();
switch (chooseNumber) {
case 1 -> {
System.out.println("---------------------");
System.out.println("所有舰娘数据:");
List<Warship> warships = warshipMapper.selectAll();
System.out.println(warships);
warshipManagementSystem(sqlSession, warshipMapper);
}
case 2 -> {
System.out.println("---------------------");
System.out.println("按照条件进行查询(如果不知道该条件,数值可填0,字符串可填未知)");
System.out.print("舰娘的编号:");
int id = sc.nextInt();
System.out.print("舰娘的英文名:");
String englishName = sc.next();
System.out.print("舰娘的中文名:");
String chineseName = sc.next();
System.out.print("舰娘的阵营:");
String camp = sc.next();
List<Warship> warships = warshipMapper.selectByConditions(id,englishName,chineseName,camp);
System.out.println(warships);
warshipManagementSystem(sqlSession, warshipMapper);
}
}
}
private static void updateWarship(SqlSession sqlSession, WarshipMapper warshipMapper) {
System.out.println("---------------------");
System.out.println("修改舰娘数据");
Scanner sc = new Scanner(System.in);
System.out.print("需要修改的id:");
int id = sc.nextInt();
System.out.print("舰娘的英文名:");
String englishName = sc.next();
System.out.print("舰娘的中文名:");
String chineseName = sc.next();
System.out.print("舰娘的阵营:");
String camp = sc.next();
warshipMapper.update(id, englishName, chineseName, camp);
warshipManagementSystem(sqlSession, warshipMapper);
}
private static void deleteWarship(SqlSession sqlSession, WarshipMapper warshipMapper) {
System.out.println("---------------------");
System.out.println("删除舰娘数据");
Scanner sc = new Scanner(System.in);
System.out.print("需要删除的id:");
int id = sc.nextInt();
warshipMapper.deleteById(id);
warshipManagementSystem(sqlSession, warshipMapper);
}
private static void createWarship(SqlSession sqlSession, WarshipMapper warshipMapper) {
Scanner sc = new Scanner(System.in);
System.out.println("---------------------");
System.out.println("增加舰娘数据");
System.out.print("舰娘的英文名:");
String englishName = sc.next();
System.out.print("舰娘的中文名:");
String chineseName = sc.next();
System.out.print("舰娘的阵营:");
String camp = sc.next();
Warship warship = new Warship();
warship.setEnglishName(englishName);
warship.setChineseName(chineseName);
warship.setCamp(camp);
warshipMapper.add(warship);
warshipManagementSystem(sqlSession, warshipMapper);
}
}