MyBatis01基于配置的CRUD操作
Posted elaina
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis01基于配置的CRUD操作相关的知识,希望对你有一定的参考价值。
- 创建Maven工程
- 导入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 创建数据库
CREATE TABLE `user` (
`id` int NOT NULL,
`username` varchar(32) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
)
- 编写实体类
package blog.mybatis.domain;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username=‘" + username + ‘‘‘ +
", password=‘" + password + ‘‘‘ +
‘}‘;
}
}
- 创建数据库配置文件db.properties
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&serverTimezone=GMT%2B8
username = root
password = 123456
- 创建MyBatis主配置文件SqlMapConfig.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境 -->
<environment id="mysql">
<!-- 配置事务类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置 -->
<mappers>
<package name="blog.mybatis.dao"/>
</mappers>
</configuration>
- 编写UserDao
package blog.mybatis.dao;
import blog.mybatis.domain.User;
import java.util.List;
/**
* 用户持久层接口
*/
public interface UserDao {
/**
* 查询所有
* @return
*/
List<User> findAll();
/**
* 添加用户
*/
void saveUser(User user);
/**
* 更新用户
* @param user
*/
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
void deleteUser(Integer userId);
/**
* 根据id查询用户信息
* @param userId
* @return
*/
User findById(Integer userId);
/**
* 根据名称模糊查询
* @param username
* @return
*/
List<User> findByName(String username);
}
- UserDao映射配置文件UserDao.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="blog.mybatis.dao.UserDao">
<!-- 查询所有 -->
<select id="findAll" resultType="blog.mybatis.domain.User">
select * from user
</select>
<!-- 保存用户 -->
<insert id="saveUser" parameterType="blog.mybatis.domain.User">
<!-- 配置插入操作后,获取插入数据的id -->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
insert into user(username,password)values(#{username},#{password})
</insert>
<!-- 更新用户 -->
<update id="updateUser" parameterType="blog.mybatis.domain.User">
update user set username=#{username}, password=#{password} where id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUser" parameterType="Integer">
delete from user where id = #{uid}
</delete>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="blog.mybatis.domain.User">
select * from user where id = #{uid}
</select>
<!-- 根据名称模糊查询用户信息 -->
<select id="findByName" parameterType="string" resultType="blog.mybatis.domain.User">
select * from user where username like #{name}
</select>
</mapper>
- 测试
package blog.mybatis.Test;
import blog.mybatis.dao.UserDao;
import blog.mybatis.domain.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 java.io.InputStream;
import java.util.List;
public class Test {
private InputStream in;
private SqlSession sqlSession;
private UserDao userDao;
@org.junit.Before//在Test执行之前执行
public void init() throws Exception {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession();
//4.获取dao的代理对象
userDao = sqlSession.getMapper(UserDao.class);
}
@org.junit.After//在Test执行之后执行
public void destroy() throws Exception {
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
* @throws Exception
*/
@org.junit.Test
public void testFindAll() {
//5.执行查询所有方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
}
/**
* 测试保存操作
*/
@org.junit.Test
public void testSave() {
User user = new User();
user.setUsername("Tom");
System.out.println("保存操作之前:" + user);
//5.执行保存方法
userDao.saveUser(user);
System.out.println("保存操作之后:" + user);
}
/**
* 测试更新操作
*/
@org.junit.Test
public void testUpdate() {
User user = new User();
user.setId(3);
user.setUsername("Jerry");
//5.执行更新方法
userDao.updateUser(user);
}
/**
* 测试删除操作
*/
@org.junit.Test
public void testDelete() {
//5.执行删除方法
userDao.deleteUser(3);
}
/**
* 测试根据id查询操作
*/
@org.junit.Test
public void testFindById() {
//5.执行根据id查询用户方法
User user = userDao.findById(1);
System.out.println(user);
}
/**
* 测试模糊查询操作
*/
@org.junit.Test
public void testFindByName() {
//5.执行模糊查询方法
List<User> users = userDao.findByName("%M%");
for (User user : users) {
System.out.println(user);
}
}
}
以上是关于MyBatis01基于配置的CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章