参考书籍《JavaEE企业级开发技术》-黑马程序员
利用Mybatis框架实现客户(银行账户)信息(tb_cust:id\cname\csex\cbirth\cfavs\ctel\caddr)的查询,新增,更新及删除的功能。
pom.xml
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.itheima</groupId>
<artifactId>mybatistest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope>-->
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
db.properties
XML
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root
User.java
java
package com.itheima.pojo;
public class User {
private int uid; //用户id
private String uname; //用户姓名
private int uage; //用户年龄
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
}
UserMapper.xml
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为映射的根节点-->
<!-- mapper为映射的根节点,namespace指定Dao接口的完整类名
mybatis会依据这个接口动态创建一个实现类去实现这个接口,
而这个实现类是一个Mapper对象-->
<mapper namespace="com.itheima.pojo.User">
<!--id ="接口中的方法名"
parameterType="传入的参数类型"
resultType = "返回实体类对象,使用包.类名"-->
<select id="findById" parameterType="int"
resultType="com.itheima.pojo.User">
select * from users where uid = #{id}
</select>
</mapper>
mybatis-config.xml
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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<!-- mapping文件路径配置 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
UserTest.java
java
package Test;
import com.itheima.pojo.User;
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 java.io.IOException;
import java.io.Reader;
public class UserTest {
@Test
public void userFindByIdTest() {
//读取文件名
String resources = "mybatis-config.xml";
//创建流
Reader reader = null;
try {
//读取mybatis-config.xml文件内容到reader对象中
reader = Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
//初始化mybatis数据库,创建SqlSessionFactory类的实例
SqlSessionFactory sqlMapper = new
SqlSessionFactoryBuilder().build(reader);
//创建SqlSession实例
SqlSession session = sqlMapper.openSession();
//传入参数查询,返回结果
User user = session.selectOne("findById", 1);
//输出结果
System.out.println(user.getUname());
//关闭session
session.close();
}
}
现在已经有了一个基本的MyBatis配置,包括一个用户实体类User,一个映射文件UserMapper.xml,以及一个测试类UserTest用于测试查询功能。现在,增加更新、插入和删除的功能。以下是如何实现这些功能的步骤:
更新功能
在UserMapper.xml中添加一个update标签来定义更新操作:
XML
<update id="updateUser" parameterType="com.itheima.pojo.User">
update users
set uname = #{uname}, uage = #{uage}
where uid = #{uid}
</update>
插入功能
在UserMapper.xml中添加一个insert标签来定义插入操作:
XML
<insert id="insertUser" parameterType="com.itheima.pojo.User">
insert into users (uid, uname, uage) values (#{uid}, #{uname}, #{uage})
</insert>
删除功能
在UserMapper.xml中添加一个delete标签来定义删除操作:
XML
<delete id="deleteUser" parameterType="int">
delete from users where uid = #{uid}
</delete>
更新测试类
在UserTest类中添加测试方法来测试更新、插入和删除功能:
java
package Test;
import com.itheima.pojo.User;
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 java.io.IOException;
import java.io.Reader;
public class UserTest {
@Test
public void userFindByIdTest() {
// 已有的查询测试代码
}
@Test
public void userUpdateTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
User user = new User();
user.setUid(1);
user.setUname("Updated Name");
user.setUage(30);
session.update("updateUser", user);
session.commit();
System.out.println("User updated successfully");
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void userInsertTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
User user = new User();
user.setUid(3);
user.setUname("New User");
user.setUage(25);
session.insert("insertUser", user);
session.commit();
System.out.println("User inserted successfully");
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void userDeleteTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
session.delete("deleteUser", 3);
session.commit();
System.out.println("User deleted successfully");
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
确保您的数据库连接配置正确,并且数据库中有一个名为users
的表,其结构与您的User
实体类相匹配。
sql
use mybatis;
create table users(
uid int primary key auto_increment,
uname varchar(20) not null,
uage int not null
);
insert into users(uid,uname,uage) values(null,'张三',20),(null,'李四',18);
为了利用Mybatis框架实现实现客户(银行账户)信息(tb_cust:id\cname\csex\cbirth\cfavs\ctel\caddr)的查询,新增,更新及删除的功能。我们需要做以下几个步骤:
- 修改数据库,添加新的字段。
- 修改User类,或创建客户实体类Custommer。
- 修改建映射文件UserMapper.xml,或者新建映射文件CustoemerMapper.xml,添加相应的SQL语句。
- 修改测试类,或者添加CustomerTest,添加测试方法。