本文介绍了本人在学习Mybatis时使用IntelliJ IDEA创建的第一个Mybatis入门程序,程序主要实现了对用户表中的信息进行增删改查操作。
CREATE TABLE `user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`pwd` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `user`(`name`, `pwd`) VALUES ('CSDN', '123456')
INSERT INTO `user`(`name`, `pwd`) VALUES ('C搜索', '123456')
INSERT INTO `user`(`name`, `pwd`) VALUES ('慢热型网友', '123456')
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>mybatistestartifactId>
<packaging>pompackaging>
<version>1.0-SNAPSHOTversion>
<modules>
<module>mybatismodule>
modules>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
project>
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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useEncoding=false&characterEncoding=UTF-8&serverTimezone=GMT"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/richard/pojo/UserMapper.xml"/>
mappers>
configuration>
package com.richard.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;
//sqlSessionFactory用来构建sqlSession
public class MybatisUtils {
//提升SqlSessionFactory的作用域
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 使用Mybatis第一步获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
com/richard/pojo/User.java
package com.richard.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* (User)实体类
*
* @author makejava
* @since 2022-11-04 14:09:54
*/
//在这里使用了Lombok插件的@Data注解,编写实体类更方便
@Data
public class User implements Serializable {
private static final long serialVersionUID = -76233651672372585L;
//用户id
private Integer id;
//用户名
private String name;
//用户密码
private String pwd;
}
com/richard/pojo/UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.richard.pojo.User">
<select id="UserList" resultType="com.richard.pojo.User">
select * from user
select>
<select id="findUserById" parameterType="Integer" resultType="com.richard.pojo.User">
select *
from user
where id = #{id};
select>
<select id="findUserByName" parameterType="String" resultType="com.richard.pojo.User">
-- select * from user where name like '%${value}%'
select *
from user
where name like concat('%', #{name}, '%')
select>
<insert id="addUser" parameterType="com.richard.pojo.User">
insert into user(id, name, pwd)
values (#{id}, #{name}, #{pwd})
insert>
<update id="updateUser" parameterType="com.richard.pojo.User">
update user
set id=#{id},
name=#{name},
pwd=#{pwd}
where id = #{id}
update>
<delete id="deleteUserById" parameterType="Integer">
delete
from user
where id = #{id}
delete>
mapper>
src/test/java/com/richard/pojo/UserTest.java
package com.richard.pojo;
import com.richard.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserTest {
@Test
public void UserList(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<User> users = sqlSession.selectList("UserList");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void userFindByIdTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
User user = sqlSession.selectOne("findUserById", 1);
System.out.println(user.toString());
sqlSession.close();
}
@Test
public void userFindByNameTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
List<User> users = sqlSession.selectList("findUserByName", "C");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void addUserTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
//创建User对象
User user = new User();
user.setId(4);
user.setName("add测试");
user.setPwd("123456");
//执行sqlsession
int rows = sqlSession.insert("addUser", user);
if (rows > 0) {
System.out.println("您成功添加了" + rows + "插入了一条数据");
} else {
System.out.println("插入失败!!!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUserTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
//创建User对象
User user = new User();
user.setId(4);
user.setName("add测试123");
user.setPwd("修改密码");
//执行sqlsession
int rows = sqlSession.insert("updateUser", user);
if (rows > 0) {
System.out.println("您成功修改了" + rows + "条数据");
} else {
System.out.println("修改失败!!!");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUserTest() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sqlsession
int rows = sqlSession.insert("deleteUserById", 4);
if (rows > 0) {
System.out.println("您成功删除了" + rows + "条数据");
} else {
System.out.println("删除失败!!!");
}
sqlSession.commit();
sqlSession.close();
}
}