1、创建maven工程,导入坐标
<?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.itcast</groupId>
<artifactId>mybatis_crud</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
</project>
2、工程目录
3、数据库表字段
CREATE DATABASE mybatis;
USE DATABASE;
DROP TABLE IF EXISTS student;
CREATE TABLE `student` (
studentNo INT(8) NOT NULL AUTO_INCREMENT COMMENT '学生学号',
studentName VARCHAR(32) NOT NULL COMMENT '学生姓名',
sex CHAR(1) DEFAULT NULL COMMENT '学生性别',
birthday DATETIME DEFAULT NULL COMMENT '学生生日',
PRIMARY KEY(studentNo)
) ENGINE=INNODB DEFAULT CHARSET = utf8;
INSERT INTO student(studentNo,studentName,sex,birthday) VALUES(100,'张三同学','男','2018-02-27 17:47:08');
INSERT INTO student(studentNo,studentName,sex,birthday) VALUES(101,'李四同学','男','2018-02-27 17:47:08');
INSERT INTO student(studentNo,studentName,sex,birthday) VALUES(102,'王五同学','男','2018-02-27 17:47:08');
INSERT INTO student(studentNo,studentName,sex,birthday) VALUES(103,'赵六同学','男','2018-02-27 17:47:08');
4、表对应的实体类
package domain;
import java.io.Serializable;
import java.util.Date;
public class Student implements Serializable {
private Integer studentNo;
private String studentName;
private String sex;
private Date birthday;
public Student() {
}
public Student(Integer studentNo, String studentName, String sex, Date birthday) {
this.studentNo = studentNo;
this.studentName = studentName;
this.sex = sex;
this.birthday = birthday;
}
public Integer getStudentNo() {
return studentNo;
}
public void setStudentNo(Integer studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"studentNo=" + studentNo +
", studentName='" + studentName + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
5、实体类对应的DAO接口
package dao;
import domain.Student;
import java.util.List;
public interface StudentDao {
List<Student> findAll();
List<Student> findByCondition(Student student);
void save(Student student);
void update(Student student);
void deleteByCondition(Student student);
}
6、DAO对应的Mapper文件
<?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="dao.StudentDao">
<!-- 全表查询 -->
<select id="findAll" resultType="domain.Student">
SELECT * FROM student;
</select>
<!-- 根据条件查询 -->
<select id="findByCondition" parameterType="Student" resultType="Student">
SELECT *
FROM student
<where>
<if test="studentNo != null">
studentNo = #{studentNo}
</if>
<if test="studentName != null">
AND studentName = #{studentName}
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
<if test="birthday != null">
AND birthday = #{birthday}
</if>
</where>
</select>
<!-- 插入 -->
<insert id="save" parameterType="Student">
INSERT INTO student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="studentNo != null">
studentNo,
</if>
<if test="studentName != null">
studentName,
</if>
<if test="sex != null">
sex,
</if>
<if test="birthday != null">
birthday
</if>
</trim>
<trim prefix="VALUES(" suffix=")" suffixOverrides=",">
<if test="studentNo != null">
#{studentNo},
</if>
<if test="studentName != null">
#{studentName},
</if>
<if test="sex != null">
#{sex},
</if>
<if test="birthday != null">
#{birthday}
</if>
</trim>
</insert>
<!-- 更新(根据ID) -->
<update id="update" parameterType="Student">
UPDATE student
<!-- 一般使用set标签 -->
<trim prefix="SET" suffixOverrides=",">
<if test="studentName != null">
studentName = #{studentName},
</if>
<if test="sex != null">
sex = #{sex},
</if>
<if test="birthday != null">
birthday = #{birthday}
</if>
</trim>
WHERE studentNo = #{studentNo}
</update>
<!-- 删除 -->
<delete id="deleteByCondition" parameterType="Student">
DELETE FROM student
<trim prefix="WHERE" prefixOverrides="AND">
<if test="studentNo != null">
studentNo = #{studentNo}
</if>
<if test="studentName != null">
AND studentName = #{studentName}
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
<if test="birthday != null">
AND birthday = #{birthday}
</if>
</trim>
</delete>
</mapper>
7、全局配置文件
<?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">
<!-- mybatis环境配置 -->
<configuration>
<!--
properties:引入配置文件
resource:用于指定配置配置文件的classPath与fileName
-->
<properties resource="./db.properties"></properties>
<!-- 使用别名 -->
<typeAliases>
<!-- 给domain.Student类起一个名为Student类的别名,这样做的好处是在使用该类的时候不需要写包名 -->
<!-- <typeAlias type="domain.Student" alias="Student"></typeAlias> -->
<!-- 整个包下的所有类都起别名,别名为类名,不区分大小写 -->
<package name="domain"/>
</typeAliases>
<!--
environments:环境,可以配置多个
default:用于指定采用哪个环境
-->
<environments default="development">
<!-- id:唯一标识 -->
<environment id="development">
<!-- transactionManager:事务管理器,此处采用jdbc类型的事务管理器 -->
<transactionManager type="jdbc"></transactionManager>
<!--
dataSource:用于指定连接池的类型
property:配置连接池的数据源
-->
<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>
<environment id="production">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper resource="dao/StudentDao.xml"></mapper> -->
<package name="dao"/>
</mappers>
</configuration>
8、Junit测试类
import dao.StudentDao;
import domain.Student;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMybatis {
private InputStream inputStream;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
@Before
public void init() {
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
}
@After
public void destroy() {
sqlSession.commit();
if (sqlSession != null) {
sqlSession.close();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test_findAll() {
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.findAll();
for (Student student : students) {
System.out.println(student);
}
}
@Test
public void test_findByCondition() {
Student student = new Student();
student.setStudentName("张三同学");
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Student> students = studentDao.findByCondition(student);
for (Student stu : students) {
System.out.println(stu);
}
}
@Test
public void test_save() {
Student student = new Student();
student.setStudentName("田七同学");
student.setSex("男");
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
studentDao.save(student);
}
@Test
public void test_update() {
Student student = new Student();
student.setStudentNo(107);
student.setStudentName("露西同学");
student.setSex("女");
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
studentDao.update(student);
}
@Test
public void test_deleteByCondition() {
Student student = new Student();
student.setStudentName("田七同学");
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
studentDao.deleteByCondition(student);
}
}