IDEA+Maven使用MyBatis实现CRUD操作
Hello,大家好,今天我为大家带来在IDEA中使用Maven构建MyBatis项目,实现简单的增删改查操作,总结了博主在学习过程中的一些经验,下面进入构建项目
MyBatis介绍
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。 ---> 摘自MyBatis官网
为什么使用MyBatis
首先,之前用的是JDBC实现数据库的CRUD操作,拼接SQL语句过于麻烦,代码容易出错,大大降低开发效率使用MyBatis实现CRUD操作大大提升了开发效率,MyBatis作为一款优秀的持久层框架,大大减少了SQL语句的拼接,提升了代码的易读性,便于维护,利用MyBatis采用接口对应XML文件的方式来实现对数据库的CRUD操作。
新建Maven项目
File --> New ---> Project
如下:
单击Next
单击Finish完成Maven项目创建
==注意:Maven构建项目时需要看Maven指向的路径是不是本地路径==
File --> setting --> Build,Exception,Eeployment --> Build Tools --> Maven
配置完后,单击Apply同意,OK确认
配置pom.xml文件
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>libs/</directory>
<targetPath>libs</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
</resources>
</build>
项目结构
数据库准备
新建数据库mybatis ,数据表user
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
)
resources ---> New ---> File 命名为db.properties配置数据库信息
db.properties文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/mybatis?useSSL=true
username=root
password=111111
MyBatis核心配置文件
resources ---> New ---> File 命名为mybatis-config.xml
==注意:单击刷新键,将配置的文件从远程仓库下载到本地仓库中==
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>
<!-- 引入数据库配置信息-->
<properties resource="db.properties"/>
<settings>
<!-- 标准的日志工厂实现-->
<setting name="logImpl" value="StDOUT_LOGGING"/>
<!-- <setting name="logImpl" value="LOG4J"/>-->
</settings>
<typeAliases>
<package name="com.wanshi.bean"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 注册接口-->
<mappers>
<mapper resource="com/wanshi/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
编写源代码
新建如下项目结构
MyBatis工具类
编写MyBatisUtils类
package com.wanshi.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 {
String resources = "mybatis-config.xml";
//将mybatis核心配置文件封装成输入流
InputStream in = Resources.getResourceAsStream(resources);
//SqlSessionFactoryBuilder对输入流进行build编译为sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* sqlSessionFactory构造返回一个SqlSession进行数据库CRUD操作
* @return
*/
public SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
实体类
编写User类
package com.wanshi.bean;
public class User {
private Integer id;
private String name;
private Integer password;
public User() {
}
public User(Integer id, String name, Integer password) {
this.id = id;
this.name = name;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password=" + password +
'}';
}
}
mapper接口与xml文件编写
编写UserMapper接口
package com.wanshi.mapper;
import com.wanshi.bean.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
/**
* 查询所有的用户
* @return
*/
List<User> getUserList();
/**
* 根据用户id查询一个用户信息
* @param id
* @return
*/
User getByUserId(@Param("uid") Integer id);
/**
* 增加一个用户
* @param user
* @return
*/
Integer add(User user);
/**
* 修改一个用户信息
* @param user
* @return
*/
Integer update(User user);
/**
* 根据用户id删除一个用户
* @param id
* @return
*/
Integer delete(@Param("uid") Integer id);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wanshi.mapper.UserMapper">
<select id="getUserList" resultType="user">
select * from user
</select>
<select id="getByUserId" resultType="user">
select * from user where id = #{uid}
</select>
<insert id="insert" parameterType="user">
insert into user (name, password) values(#{name}, #{password})
</insert>
<update id="update" parameterType="user">
update user set name = #{name}, password = #{password} where id = #{id}
</update>
<delete id="delete" parameterType="int">
delete from user where id = #{uid}
</delete>
</mapper>
IDEA中连接数据库
单击右侧DataSource选项连接数据库
单击+
选择DataSource --- > MySQL
单击apply同意,单击ok,连接成功,如下页面
测试
新建测试类,TestUser,这里利用Junit单元测试来实现
package com.wanshi.test;
import com.wanshi.bean.User;
import com.wanshi.mapper.UserMapper;
import com.wanshi.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestUser {
@Test
public void getUserList() {
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void getByUserId() {
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getByUserId(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void insert() {
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setName("admin");
user.setPassword(1234);
Integer i = userMapper.insert(user);
System.out.println(i);
// 注意:增删改操作需要手动开启事务,否则无法执行
if (i > 0) {
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void update() {
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer i = userMapper.update(new User(3, "李三", 123445));
System.out.println(i);
// 注意:增删改操作需要手动开启事务,否则无法执行
if (i > 0) {
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void delete() {
SqlSession sqlSession = MyBatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Integer i = userMapper.delete(2);
System.out.println(i);
// 注意:增删改操作需要手动开启事务,否则无法执行
if (i > 0) {
sqlSession.commit();
}
sqlSession.close();
}
}
测试结果
查询所有用户
根据用户id查询指定用户
增加用户
修改用户
删除用户
结语
MyBatis入门级的增删改查操作就结束了,程序执行肯定没问题,遇到问题的小伙伴可在评论区留言,我们下篇见,Mybatis系列文章!