项目结构
数据库表
引入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
mybatis-config.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>
<!-- dddd-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="ture"/><!--配置下划线转换为驼峰命名风格-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager><!--事务管理器-->
<dataSource type="POOLED"><!--数据源 POOLED代表池化-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="dao/StudentDao.xml"></mapper>
</mappers>
</configuration>
编写实体类
package com.tmg.domain;
public class Student {
private int id;
private String name;
private int age;//提供构造器
private String email;//提供set(),get(),toString(),hascode()等方法
public Student(int id, String name, int age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
}
控制数据库数据方法
package com.tmg.dao;
import com.tmg.domain.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentDao {
void insert(Student employee);
void update(Student employee);
void deleteById(Long id);
List<Student> selectAll();
Student selectById(Long id);
//多个参数的配置
void insertEmp( @Param("stuName") String name,
@Param("stuAge") int age, @Param("stuEmail") String email);
}
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--映射的命名空间 = 包名+接口类-->
<mapper namespace="com.tmg.dao.StudentDao">
<!--配置insert操作 id是方法名 parameterType是参数类型 #{属性名}用于读取对象的属性值-->
<!--#{}和${}的区别,#{}相当于PreparedStatement的占位符?提前编译,避免SQL注入 ${}是Statement字符串拼接,不能避免注入 -->
<!--获得最新的自增主键值 useGeneratedKeys=true keyProperty主键的属性-->
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.tmg.domain.Student">
insert into student( stu_id,stu_name,stu_age,stu_email) values (#{id},#{name},#{age},#{email});
</insert>
<update id="update">
update student set stu_age=#{age},stu_email=#{email},stu_name=#{name} where stu_id=#{id} ;
</update>
<delete id="deleteById">
delete from student where stu_id=#{id};
</delete>
<!-- 问题:查询出的名称为多个单词的字段出现null值-->
<!-- 原因:数据库的字段单词以下划线分隔,Java的属性以驼峰命名,导致部分名称不一致无法实现映射-->
<select id="selectAll" resultType="com.tmg.domain.Student" resultMap="student">
select * from student
</select>
<resultMap id="student" type="com.tmg.domain.Student">
<!--配置主键 property是java属性名 column是表字段名-->
<id property="id" column="stu_id" javaType="java.lang.Integer"></id>
<!--普通字段-->
<result property="name" column="stu_name"></result>
<result property="age" column="stu_age"></result>
<result property="email" column="stu_email"></result>
</resultMap>
<select id="selectById" resultType="com.tmg.domain.Student">
select * from student where stu_id=#{id}
</select>
<insert id="insertEmp">
insert into student(stu_name,stu_age,stu_email) values (#{stuName},#{stuAge},#{stuEmail});
</insert>
</mapper>
StudentDaoText 测试类
package com.tmg.dao;
import com.tmg.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.Test;
import java.io.IOException;
import java.util.List;
public class StudentDaoText {
@Test
public void testinsert() throws IOException {
//创建会话工厂构建器
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
//创建会话
SqlSession sqlSession = factory.openSession();
//获得Mapper对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);//通过jdk动态代理创建实现类,返回代理对象
Student student = new Student(0, "zzz", 20, "zzz@qq.com");
mapper.insert(student);
sqlSession.commit();
System.out.println("insert--->"+student);
}
@Test
public void testupdate() throws IOException {
//创建会话工厂构建器
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
//创建会话
SqlSession sqlSession = build.openSession();
//获得Mapper对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Student student = new Student(12, "zl", 99, "zl@qq.com");
mapper.update(student);
sqlSession.commit();
}
@Test
public void testdeleteById() throws IOException {
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
mapper.deleteById(11L);
sqlSession.commit();
}
@Test
public void testselectAll() throws IOException {
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = build.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
List<Student> students = mapper.selectAll();
for(Student student : students){
System.out.println(student);
}
}
@Test
public void testselectById() throws IOException {
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = factory.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
Student student = mapper.selectById(3L);
System.out.println("student---->"+student);
}
@Test
public void testinsertEmp() throws IOException {
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = factoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = factory.openSession();
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
mapper.insertEmp("tmg",18,"tmg@qq.com");
sqlSession.commit();
}
}