增删改查简称为CURD,即Create Update Retrieve Delete 操作。
首先创建一个Maven项目,pom.xml配置如下:
4.0.0
com.bianla.wql
TestMybatisCRUD
1.0-SNAPSHOT
mysql
mysql-connector-java
8.0.13
org.mybatis
mybatis
3.4.6
然后创建数据库,表名为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 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文件:
然后在resources目录下创建mapper文件夹,在mapper文件夹中创建StudentMapper.xml文件:
select LAST_INSERT_ID()
insert into `Student` values (#{studentId},#{studentName},#{studentAge},#{studentScore})
update `Student` set student_name = #{studentName}, student_age = #{studentAge}, student_score = #{studentScore} where student_id = #{studentId}
delete from student where student_id = #{id}
最后再在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 list = new ArrayList();
Map map = new HashMap();
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 list = new ArrayList();
list = dao.selectAllStudents(null);
System.out.println(list);
...
此时的效果:
核对一下数据库:
没问题。
查询id为1的对象(核心代码):
...
//查询
List list = new ArrayList();
Map map = new HashMap();
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 list = new ArrayList();
list = dao.selectAllStudents(null);
System.out.println(list);
...
效果:
核对一下数据:
删除一位学生,并查询全部的学生(核心代码):
...
dao.deleteStudent(5);
//查询
List list = new ArrayList();
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 list = new ArrayList();
list = dao.selectAllStudents(null);
System.out.println(list);
...
效果:
核对数据库:
完美~
加油~