增删改查简称为CURD,即Create Update Retrieve Delete 操作。
首先创建一个Maven项目,pom.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0)"
xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"
xsi:schemaLocation="[http://maven.apache.org/POM/4.0.0](http://maven.apache.org/POM/4.0.0)[http://maven.apache.org/xsd/maven-4.0.0.xsd](http://maven.apache.org/xsd/maven-4.0.0.xsd)">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bianla.wql</groupId>
<artifactId>TestMybatisCRUD</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- [https://mvnrepository.com/artifact/mysql/mysql-connector-java](https://mvnrepository.com/artifact/mysql/mysql-connector-java)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- [https://mvnrepository.com/artifact/org.mybatis/mybatis](https://mvnrepository.com/artifact/org.mybatis/mybatis)-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
</project>
然后创建数据库,表名为Student,字段为student_id, student_name, student_score, student_age.
文件目录:
然后在java目录下创建一个包,包中创建四个文件夹,分别为dao、entity、test、util文件夹。
在dao文件夹中创建一个StudentDao文件:
package com.bianla.demo.dao;
import com.bianla.demo.entity.StudentEntity;
import java.util.List;
import java.util.Map;
public interface StudentDao{
//查询学生 如果不传入map,则查询全部学生
List<StudentEntity> selectAllStudents(Map map);
//插入学生
void insertStudent(StudentEntity entity);
//更新学生
void updateStudent (StudentEntity entity);
//删除学生
void deleteStudent (int id);
}
然后在entity文件夹中创建StudentEntity文件:
package com.bianla.demo.entity;
public class StudentEntity {
private int studentId;
private String studentName;
private int studentAge;
private String studentScore;
public StudentEntity(){}
public StudentEntity(int id, String name, int age, String score){
this.studentId = id;
this.studentName = name;
this.studentAge = age;
this.studentScore = score;
}
@Override
//重写了toString方法
public String toString(){
return "{StudentEntity: id="+studentId+" name="+studentName+" age="+studentAge+" score="+studentScore+"}";
}
//省略了get、set方法
}
然后在util文件夹下创建MyBatisUtil文件:
package com.bianla.demo.util;
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 MyBatisUtil {
//sqlSessionFactory对象
private static SqlSessionFactory sqlSessionFactory = null;
//类线程锁
private static final Class CLASS_LOCK = MyBatisUtil.class;
//私有化构造参数
private MyBatisUtil(){}
//构建sessionFactory 单例模式
public static SqlSessionFactory initSessionFactory(){
//文件路径以resources为根路径
String source = "mybatis-config.xml";
InputStream stream = null;
try {
stream = Resources.getResourceAsStream(source);
}catch (IOException e){
e.printStackTrace();
}
//下面括号中不能写this,因为initSessionFactory是静态方法
synchronized (CLASS_LOCK){
if (sqlSessionFactory == null){
sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
}
}
return sqlSessionFactory;
}
//打开sqlSession
public static SqlSession openSqlSession(){
if (sqlSessionFactory == null){
initSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
然后在resources目录下创建mysql.properties文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/wl_test_database?useSSL=false&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=Aa123456
然后在resources目录下创建mybatis-config.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//[mybatis.org//DTD](http://mybatis.org//DTD)Config 3.0//EN"
"[http://mybatis.org/dtd/mybatis-3-config.dtd](http://mybatis.org/dtd/mybatis-3-config.dtd)">
<configuration>
<properties resource="mysql.properties"/>
<environments default="wqlTestDevelopment">
<environment id="wqlTestDevelopment">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
然后在resources目录下创建mapper文件夹,在mapper文件夹中创建StudentMapper.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPEmapper
PUBLIC"-//[mybatis.org//DTD](http://mybatis.org//DTD)mapper 3.0//EN"
"[http://mybatis.org/dtd/mybatis-3-mapper.dtd](http://mybatis.org/dtd/mybatis-3-mapper.dtd)">
<!--映射文件中的namespace是用于绑定Dao接口的,即面向接口编程-->
<!--当我们的namespace绑定接口后,你就可以不用写接口实现类,mybatis会通过该绑定自动帮我们找到要执行的SQL语句-->
<!--不过需要注意:namespace对应文件的接口要与映射文件中的SQL语句的ID一一对应,即StudentDao的接口名,与StudentMapper的sql语句的id一致-->
<mapper namespace="com.bianla.demo.dao.StudentDao">
<!--配置实体与表的映射-->
<resultMap id="studentMap" type="com.bianla.demo.entity.StudentEntity">
<id column="student_id" property="studentId"/>
<result column="student_name" property="studentName"/>
<result column="student_age" property="studentAge"/>
<result column="student_score" property="studentScore"/>
</resultMap>
<!--一般findAll查询所有,不需要条件。这里是为说明可以设置这样的条件-->
<select id="selectAllStudents" parameterType="map" resultMap="studentMap">
select * from student
<!--where开始设置条件-->
<where>
<!--如果传进来的id不为null,就设置条件表字段的id=传进来的id,这里可以动态设置条件也就是mybatis强大的动态sql。-->
<if test="id!=null">
and student_id=#{id}
</if>
</where>
</select>
<!--增加一位学生
id:要与StudentDao中的接口名一致
parameterType:传入的参数类型为studentEntity
-->
<insert id="insertStudent" parameterType="com.bianla.demo.entity.StudentEntity">
<!--selectKey用来将主键回写
keyProperty:查询出来的主键对应StudentEntity的哪个属性
keyColumn:查询出来的主键在Student表中的字段
order:查询主键语句在插入语句的前面还是后面执行
resultType:查询出来的主键的类型-->
<selectKey keyProperty="studentId" keyColumn="student_id" order="AFTER" resultType="int">
select LAST_INSERT_ID()
</selectKey>
insert into `Student` values (#{studentId},#{studentName},#{studentAge},#{studentScore})
</insert>
<!--更新学生数据-->
<update id="updateStudent" parameterType="com.bianla.demo.entity.StudentEntity">
update `Student` set student_name = #{studentName}, student_age = #{studentAge}, student_score = #{studentScore} where student_id = #{studentId}
</update>
<!--根据ID删除学生-->
<delete id="deleteStudent" parameterType="int">
delete from student where student_id = #{id}
</delete>
</mapper>
最后再在test文件夹下创建StudentTest文件:
增删改查的内容为核心代码。
package com.bianla.demo.test;
import com.bianla.demo.dao.StudentDao;
import com.bianla.demo.entity.StudentEntity;
import com.bianla.demo.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentTest {
public static void main (String[] args){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.openSqlSession();
// 通过SqlSession对象得到Mapper接口的一个代理对象
// 需要传递的参数是Mapper接口的类型
StudentDao dao = sqlSession.getMapper(StudentDao.class);
//增加
StudentEntity entity = new StudentEntity();
//entity.setStudentId(6);
entity.setStudentAge(123);
entity.setStudentName("唐昊");
entity.setStudentScore("92");
dao.insertStudent(entity);
//更改
StudentEntity updateEntity = new StudentEntity();
updateEntity.setStudentName("小舞");
updateEntity.setStudentScore("921");
updateEntity.setStudentAge(16);
updateEntity.setStudentId(2);
dao.updateStudent(updateEntity);
//删除
dao.deleteStudent(5);
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
Map<String,Object> map = new HashMap<String, Object>();
map.put("id",1);
list = dao.selectAllStudents(map);
System.out.println(list);
[sqlSession.commit();](http://sqlsession.commit();/)
}catch (Exception e){
e.printStackTrace();
System.err.println(e.getMessage());
sqlSession.rollback();
}finally {
if (sqlSession != null){
sqlSession.close();
}
}
}
}
我们分别试验一下:
查询全部(核心代码仅使用以下内容):
...
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
list = dao.selectAllStudents(null);
System.out.println(list);
...
此时的效果:
核对一下数据库:
没问题。
查询id为1的对象(核心代码):
...
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
Map<String,Object> map = new HashMap<String, Object>();
map.put("id",1);
list = dao.selectAllStudents(map);
System.out.println(list);
...
效果:
新增一位学生,并查询(核心代码):
...
//增加
StudentEntity entity = new StudentEntity();
entity.setStudentId(6);
entity.setStudentAge(123);
entity.setStudentName("唐昊");
entity.setStudentScore("92");
dao.insertStudent(entity);
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
list = dao.selectAllStudents(null);
System.out.println(list);
...
效果:
核对一下数据:
删除一位学生,并查询全部的学生(核心代码):
...
dao.deleteStudent(5);
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
list = dao.selectAllStudents(null);
System.out.println(list);
...
效果:
核对一下数据库:
修改id为2的数据(核心代码),并查询:
...
//更改
StudentEntity updateEntity = new StudentEntity();
updateEntity.setStudentName("小舞");
updateEntity.setStudentScore("921");
updateEntity.setStudentAge(16);
updateEntity.setStudentId(2);
dao.updateStudent(updateEntity);
//查询
List<StudentEntity> list = new ArrayList<StudentEntity>();
list = dao.selectAllStudents(null);
System.out.println(list);
...
效果:
核对数据库:
完美~
加油~