- 新建一个数据库 db1,新建一张表student
- 打开IDEA创建一个maven项目,结构如下
- 配置
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>org.example</groupId>
<artifactId>mybatisex</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<!--依赖列表-->
<dependencies>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!--资源插件: 处理src/main/java目录中的xml-->
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
mybatis.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>
<!--设置日志-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--配置数据源: 创建Connection对象。-->
<dataSource type="POOLED">
<!--driver:驱动的内容-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--连接数据库的url-->
<property name="url"
value="jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8"/>
<!--用户名-->
<property name="username" value="username"/>
<!--密码-->
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<!--指定其他mapper文件的位置:
其他mapper文件目的是找到其他文件的sql语句
-->
<mappers>
<!--
使用mapper的resource属性指定mapper文件的路径。
这个路径是从target/classes路径开启的
使用注意:
resource=“mapper文件的路径,使用 / 分割路径”
一个mapper resource 指定一个mapper文件
-->
<mapper resource="indi/wtl/dao/StudentDao.xml"/>
</mappers>
</configuration>
- 实体类
Student.java
package indi.wtl.domain;
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "学生实体{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
- dao层
StudentDao.java
package indi.wtl.dao;
import indi.wtl.domain.Student;
import java.util.List;
public interface StudentDao {
//重载方法
Student selectById(Integer id);
List<Student> selectStudents();
int insertStudent(Student student);
}
StudentDao.xml
<?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="indi.wtl.dao.StudentDao">
<!-- 使用insert, update,delete,select标签写sql -->
<select id="selectById" resultType="indi.wtl.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
<select id="selectStudents" resultType="indi.wtl.domain.Student">
select id,name,email,age from student
</select>
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
</mapper>
- 工具类
MyBatisUtil.java
package indi.wtl.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;
/**
* 工具类:创建SqlSession对象
*/
public class MyBatisUtil {
private static SqlSessionFactory factory = null;
static {
String config="mybatis.xml";
try {
InputStream inputStream =Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//创建方法,获取SqlSession对象
public static SqlSession getSqlSession(){
SqlSession session = null;
if( factory != null ){
session =factory.openSession(); // openSession(true)自动提交事务
}
return session;
}
}
- 测试
MyTest.java
package indi.wtl;
import indi.wtl.domain.Student;
import indi.wtl.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest {
@Test
public void testSelectById(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="indi.wtl.dao.StudentDao.selectById";
//3.执行SqlSession的方法,表示执行sql语句
Student student = session.selectOne(sqlId,1);
System.out.println("查询的结果==="+student);
//4.关闭SqlSession对象
session.close();
}
@Test
public void testSelectStudents(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="indi.wtl.dao.StudentDao.selectStudents";
//3.执行SqlSession的方法,表示执行sql语句
List<Student> students= session.selectList(sqlId);
for(Student stu:students){
System.out.println("student===="+stu);
}
//4.关闭SqlSession对象
session.close();
}
@Test
public void testInsertStudent(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="indi.wtl.dao.StudentDao.insertStudent";
//3.执行SqlSession的方法,表示执行sql语句
Student student = new Student();
student.setId(3);
student.setName("东皇");
student.setEmail("donghuang@QQ.com");
student.setAge(30);
int rows = session.insert(sqlId, student);
session.commit();
System.out.println("insert的行数==="+rows);
//4.关闭SqlSession对象
session.close();
}
}
- 使用dao的方法实现
StudentDaoImpl.java
package indi.wtl.dao.impl;
import indi.wtl.dao.StudentDao;
import indi.wtl.domain.Student;
import indi.wtl.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class StudentDaoImpl implements StudentDao {
@Override
public Student selectById(Integer id) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
String sqlId="indi.wtl.dao.StudentDao.selectById";
Student student = sqlSession.selectOne(sqlId,id);
sqlSession.close();
return student;
}
@Override
public List<Student> selectStudents() {
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="indi.wtl.dao.StudentDao.selectStudents";
//3.执行SqlSession的方法,表示执行sql语句
List<Student> students= session.selectList(sqlId);
//4.关闭SqlSession对象
session.close();
return students;
}
@Override
public int insertStudent(Student student) {
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.指定sqlId
String sqlId="indi.wtl.dao.StudentDao.insertStudent";
//3.执行SqlSession的方法,表示执行sql语句
int rows = session.insert(sqlId, student);
session.commit();
System.out.println("insert的行数==="+rows);
//4.关闭SqlSession对象
session.close();
return rows;
}
}
测试
MyTest2.java
package indi.wtl;
import indi.wtl.dao.StudentDao;
import indi.wtl.dao.impl.StudentDaoImpl;
import indi.wtl.domain.Student;
import org.junit.Test;
import java.util.List;
public class MyTest2 {
/**
* 使用dao的代理要求:
* 1. mapper文件中的namespace: 必须是dao接口的全限定名称
* 2. mapper文件中标签的id是 dao接口中的方法名称(一摸一样的)
*/
@Test
public void testSelectOne(){
//要使用dao的方法
// 接口类型 变量 = new 接口的实现类();
StudentDao dao = new StudentDaoImpl();
Student student = dao.selectById(2);
System.out.println("通过dao执行方法,的到的对象=="+student);
}
@Test
public void testSelectStudents(){
StudentDao dao = new StudentDaoImpl();
List<Student> students = dao.selectStudents();
students.forEach( stu-> System.out.println("stu="+stu));
}
@Test
public void testInsert(){
StudentDao dao = new StudentDaoImpl();
Student student = new Student();
student.setId(4);
student.setName("周强");
student.setEmail("zhouqiang@qq.com");
student.setAge(28);
dao.insertStudent(student);
}
}
- MyBatis-dao代理的使用
删掉indi包
MyTest3.java
package indi.wtl;
import indi.wtl.dao.StudentDao;
import indi.wtl.domain.Student;
import indi.wtl.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MyTest3 {
@Test
public void testSelectById(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.获取dao的代理
StudentDao dao = session.getMapper(StudentDao.class);
Student student = dao.selectById(4);
System.out.println("student = " + student);
//3.关闭SqlSession对象
session.close();
}
@Test
public void testSelectStudents(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.获取dao的代理
StudentDao dao = session.getMapper(StudentDao.class);
List<Student> students = dao.selectStudents();
students.forEach( stu-> System.out.println("stu="+stu));
//3.关闭SqlSession对象
session.close();
}
@Test
public void testInsertStudent(){
//1.获取SqlSession
SqlSession session = MyBatisUtil.getSqlSession();
//2.获取dao的代理
StudentDao dao = session.getMapper(StudentDao.class);
Student student = new Student();
student.setId(5);
student.setName("张飞");
student.setEmail("zhangfei@QQ.com");
student.setAge(25);
int rows = dao.insertStudent(student);
session.commit();
System.out.println("insert的行数==="+rows);
//3.关闭SqlSession对象
session.close();
}
}