一.数据库准备及环境搭建
1.数据库mysql中使用database名为mybatis并在其中创建表student表
create table student(
-> id int(11) primary key auto_increment,
-> stuname varchar(11),
-> major varchar(11),
-> sex varchar(1),
-> age int(11)
-> )ENGINE=InnoDB DEFAULT CHARSET=utf8;
并插入一条数据用于测试
insert into student(stuname,major,sex,age)
values('roy','computer','M','23');
2.在IntelliJ IDEA中新建project命名为mybatis_crudTest,建立结束后先在pom.xml配置文件中添加依赖全部代码块如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.lut</groupId>
<artifactId>mybatis_crudTest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.在src-》main-》java包中新建java项目命名为:com.lut.domain.Student
并将属性和getter、setter和toString方法加入。
Student.java如下:
package com.lut.domain;
public class Student {
private Integer id;
private String stuname;
private String major;
private String sex;
private int age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuname='" + stuname + '\'' +
", major='" + major + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4.在resources包中首先创建数据库配置文件jdbcConfig.properties,再创建sql映射文件sqlMapConfig.xml。
①:jdbcConfig.properties代码如下
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
②:sqlMapConfig.xml代码如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.ory//DTD Config 3.0//EN"
"htpp://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis的主配置文件-->
<configuration>
<!--配置properties可以在标签内部配置连接数据库的信息,也可以通过属性引用外部配置信息文件
resource属性:用于 指定配置文件的位置,是按照类路径得分写法来写,并且必须存在与类路径下 -->
<properties resource="jdbcConfig.properties">
</properties>
<!--使用typeAliases配置别名,它只能配置domain中类的别名-->
<typeAliases>
<!--用于指定要配置的别名的包,当指定智斗,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写-->
<package name="com.lut.domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务的类型-->
<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>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<!--package标签用户指定dao接口所在的包,当指定完成之后,就不需要再写mapper以及resource或者class了-->
<package name="com.lut.dao"></package>
</mappers>
</configuration>
二.dao编写及映射文件的创建
1.在src->main->java下新建java文件命名为:com.lut.dao.IStudentDao
代码如下:
package com.lut.dao;
import com.lut.domain.Student;
import java.util.List;
public interface IStudentDao {
//查询表中所有学生
List<Student> findAll();
//添加学生信息
void saveStudent(Student student);
//更新学生信息
void updateStudent(Student student);
//根据id删除学生信息
void deleteStudent(Integer id);
}
2.在resources包中新建directory为com,然后在com包下新建directory为lut,然后在lut包下新建directory为dao,并在dao包下新建file为IStudentDao.xml。(注意此映射文件是IStudentDao的映射,故包的结构需要和其对应的dao对应相同)。
IStudentDao.xml的代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.ory//DTD Mapper 3.0//EN"
"htpp://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lut.dao.IStudentDao">
<!--查询所有信息-->
<select id="findAll" resultType="student">
select * from student
</select>
<!--保存学生信息-->
<insert id="saveStudent">
insert into student(stuname,major,sex,age)values(#{stuname},#{major},#{sex},#{age})
<!--插入操作之后获取插入数据id-->
<selectKey keyProperty="id" order="AFTER" resultType="int">
select last_insert_id();
</selectKey>
</insert>
<update id="updateStudent" parameterType="student">
update student set stuname=#{stuname},major=#{major},sex=#{sex},age=#{age} where id=#{id}
</update>
<delete id="deleteStudent" parameterType="int">
delete from student where id=#{id}
</delete>
</mapper>
3.最后在test包下的java中新建java为com.lut.test.studentTest的Test类
studentTest.java为:
package com.lut.test;
import com.lut.dao.IStudentDao;
import com.lut.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.junit.Test;
/**
* @author Roy
* @date 2020/6/23 16:30
*/
public class studentTest {
public InputStream in;
private SqlSession sqlSession;
private IStudentDao studentDao;
@Before//测试方法之前执行
public void init() throws Exception{
//读取配置文件
in= Resources.getResourceAsStream("sqlMapConfig.xml");
//创建SQL SessionFactory工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//使用工厂生产SQL Session对象
sqlSession=factory.openSession(true);
//使用sqlSession对象创建Dao接口的代理对象
studentDao=sqlSession.getMapper(IStudentDao.class);
}
@After//测试方法之后执行
public void destroy() throws Exception{
//释放占用的资源
sqlSession.close();
in.close();
}
//测试查询方法
@Test
public void testFindAll(){
List<Student> students=studentDao.findAll();
for(Student student:students){
System.out.println("学生信息为:");
System.out.println(student);
}
}
//测试保存方法
@Test
public void testSaveStudent(){
Student student=new Student();
student.setStuname("July");
student.setMajor("English");
student.setSex("F");
student.setAge(22);
System.out.println("保存之前的student为:"+student);
studentDao.saveStudent(student);
System.out.println("保存之后的student为:"+student);
}
//测试更新方法
@Test
public void testUpdateStudent(){
Student stu=new Student();
stu.setId(1);
stu.setStuname("roy");
stu.setMajor("ICS");
stu.setSex("M");
stu.setAge(24);
studentDao.updateStudent(stu);
}
//测试删除方法
@Test
public void testDeleteStudent(){
studentDao.deleteStudent(2);
}
}
至此基于mybatis的增删改查简单功能就完成了。
其中建好的包结构如下图所示: