前言
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
一、导入所需jar
mybatis-3.4.1.jar
mysql-connector-java-5.1.13-bin.jar
二、配置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>
- <!-- 数据库环境 -->
- <environments default="development">
- <!-- 每一个环境的id -->
- <environment id="development">
- <!-- 使用的事务管理为jdbc,除此之外还有ManagedTransaction -->
- <transactionManager type="JDBC" />
- <!-- 使用mybatis自带的数据库连接池来管理数据库连接 -->
- <!-- 除此之外还有jndi,unpooled -->
- <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>
- <!-- 对应的mapper映射文件的全类名 -->
- <mappers>
- <mapper resource="com/mybatis/mapper/StudentMapper.xml"/>
- </mappers>
- </configuration>
三、构造实体对象
- package com.mybatis.pojo;
- public class Student {
- private int id;
- private String name;
- private int age;
- private String address;
- public Student() {
- super();
- }
- public Student(int id, String name, int age, String address) {
- super();
- this.id = id;
- this.name = name;
- this.age = age;
- this.address = address;
- }
- public Student(String name, int age, String address) {
- super();
- this.name = name;
- this.age = age;
- this.address = address;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void set Name(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- @Override
- public String toString() {
- return"Student [id=" + id + ",name=" + name + ", age=" + age + ",address=" + address + "]";
- }
- }
四、创建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">
- <!-- 名空间,当仅仅使用 mybtias 时,此属性中的值一般为自己的全类名,也可随意设置。若和 mybatis 的接口搭配使用,则填写对应接口的全类名 -->
- <mapper namespace="com.mybatis.mapper.StudentMapper">
- <!-- SQL语句一共分为四类,分别为增删改查 ,每个namespace中的 id是唯一的-->
- <!--parameterType 为参数类型,可以是基本数据类型,也可以是引用数据类型,基本数据类型和String 可以简写,而引用数据类型需要全类名 -->
- <select id="queryStudentById" parameterType="int" resultType="com.mybatis.pojo.Student">
- SELECT * FROM student WHERE id=#{value}
- </select>
- <!--resultMap属性只有 select 中才会有,为输出类型,当列字段和类中的成员变量不一致,或有一对多,多对多的关系,可以使用 resultMap 进行关系映射 -->
- <select id="queryStudentList" resultMap="queryStudentList">
- SELECT * FROMstudent
- </select>
- <!--resultMap标签 中有两个属性,分别是 type : 代表着所对应的类的全类名 , id : 对应着 select 中的 resultMap 中的值-->
- <resultMap type="com.mybatis.pojo.Student" id="queryStudentList">
- <span style="white-space:pre;"> </span><!-- column对应着列中的字段,property对应着实体类中的属性 -->
- <span style="white-space:pre;"> </span><id column="id" property="id" />
- <span style="white-space:pre;"> </span><result column="name" property="name" />
- <span style="white-space:pre;"> </span><result column="age" property="age" />
- <span style="white-space:pre;"> </span><result column="address" property="address" />
- </resultMap>
- <!-- 当传入参数时,可以用 ${} 和 #{} 取出响应的值 -->
- <insert id="insertStudent" parameterType="com.mybatis.pojo.Student">
- <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
- SELECT LAST_INSERT_ID()
- </selectKey>
- INSERT INTOstudent (name,age,address) VALUES (#{name},#{age},#{address})
- </insert>
- <!-- 增删改没有 resultType 属性,只能返回修改的条数,为 int 型 -->
- <update id="updateStudentById" parameterType="com.mybatis.pojo.Student">
- UPDATE studentSET name=#{name},age=#{age},address=#{address} WHERE id=#{id}
- </update>
- <delete id="deleteStudentById"parameterType="int">
- DELETE FROMstudent WHERE id=#{value}
- </delete>
- </mapper>
//关于mybatis动态SQL标签的用法,引了一个超链接,讲的很细
https://www.cnblogs.com/ywqbj/p/5707652.html
五、测试及运行结果
- package com.mybatis.test;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.List;
- 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 com.mybatis.pojo.Student;
- public class TestStudent {
- private SqlSession session=null;
- //执行每个单元测试之前会执行before方法
- @Before
- public void getSqlSession() throws IOException {
- String resource="mybatis-config.xml";
- InputStream inputStream=Resources.getResourceAsStream(resource);
- SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
- session=sessionFactory.openSession();
- }
- //查询单个学生
- @Test
- public void queryStudentById() {
- Student student=session.selectOne("queryStudentById", 1);
- System.out.println(student);
- }
- //查询所有学生
- @Test
- public void queryStudentList() {
- List<Student> students=session.selectList("queryStudentList");
- for(Student s:students) {
- System.out.println(s);
- }
- }
- //添加学生
- @Test
- public void insertStudent() {
- Student student=new Student("小华", 16, "北京");
- session.insert("insertStudent", student);
- session.commit();
- System.out.println("刚刚插入的用户的ID:"+student.getId());
- }
- //修改学生
- @Test
- public void updateStudentById() {
- Student student=new Student(8,"小黑", 15, "天津");
- session.commit();
- session.insert("updateStudentById", student);
- }
- //删除学生
- @Test
- public void deleteStudentById() {
- session.delete("deleteStudentById", 8);
- session.commit();
- }
- //执行每个单元测试之后会执行After方法
- @After
- public void closeSqlSession() {
- if(session!=null) {
- session.close();
- }
- }
- }
1、根据查询某个学生
DEBUG [main] - ==> Preparing: SELECT * FROM student WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
Student [id=1, name=张三, age=18, address=安徽]
2、查询全部学生
DEBUG [main] - ==> Preparing: SELECT * FROM student
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 5
Student [id=1, name=张三, age=18, address=安徽]
Student [id=2, name=李四, age=16, address=上海]
Student [id=3, name=王五, age=14, address=北京]
Student [id=4, name=赵六, age=15, address=深圳]
Student [id=5, name=韩七, age=17, address=南京]
3、新增某个学生
DEBUG [main] - ==> Preparing: INSERT INTO student (name,age,address) VALUES (?,?,?)
DEBUG [main] - ==> Parameters: 小华(String), 16(Integer), 北京(String)
DEBUG [main] - <== Updates: 1
DEBUG [main] - ==> Preparing: SELECT LAST_INSERT_ID()
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 1
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1c3a4799]
刚刚插入的用户的ID:8
4、根据ID修改某个学生
DEBUG [main] - ==> Preparing: UPDATE student SET name=?,age=?,address=? WHERE id=5
DEBUG [main] - ==> Parameters: 小黑(String), 15(Integer), 天津(String)
DEBUG [main] - <== Updates: 1
5、根据ID删除某个学生
DEBUG [main] - ==> Preparing: DELETE FROM student WHERE id=?
DEBUG [main] - ==> Parameters: 8(Integer)
DEBUG [main] - <== Updates: 1
运行后数据库如下
最后配一张流程图