# MyBatis 数据库框架入门案例# 创建数据库 mybatis 和表 userscreate database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('孤傲苍狼', 19);
INSERT INTO users(NAME, age) VALUES('白虎神皇', 29);
# 添加 mybatis 框架 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 = " mysql" > < environment id = " mysql" > < transactionManager type = " JDBC" /> < 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> </ configuration>
# 定义数据库 user,对应的实体类 Userpackage me. gacl. domain ; * @author gacl * users 表所对应的实体类 */ public class User { private int id; private String name; private int age; 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; } @Override public String toString ( ) { return "User [id=" + id + ", name=" + name + ", age=" + age + "]" ; } }
# MyBatis 映射(新建一个包,专门用于存放 sql 映射文件)userMapper.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 = " me.gacl.mapping.userMapper" > < select id = " getUser" parameterType = " int" resultType = " me.gacl.domain.User" > select * from users where id=#{id} </ select> </ mapper>
# 在 mybatis-config.xml 文件中注册 userMapper.xml 文件 < mappers> < mapper resource = " me/gacl/mapping/userMapper.xml" /> </ mappers>
# 编写 Test1 测试类package me. gacl. test ; import java. io. IOException ; import java. io. InputStream ; import java. io. Reader ; import me. gacl. domain. User ; import org. apache. ibatis. io. Resources ; import org. apache. ibatis. session. SqlSession ; import org. apache. ibatis. session. SqlSessionFactory ; import org. apache. ibatis. session. SqlSessionFactoryBuilder ; public class Test1 { public static void main ( String [ ] args) throws IOException { String resource = "mybatis-config.xml" ; InputStream is = Resources . getResourceAsStream ( resource) ; SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder ( ) . build ( is) ; SqlSession session = sessionFactory. openSession ( ) ; * 映射 sql 的标识字符串, * me.gacl.mapping.userMapper 是 userMapper.xml 文件中 mapper 标签的 namespace 属性的值, * getUser 是 select 标签的 id 属性值,通过 select 标签的 id 属性值就可以找到要执行的 SQL */ String statement = "me.gacl.mapping.userMapper.getUser" ; User user = session. selectOne ( statement, 1 ) ; System . out. println ( user) ; } }
# 运行结果(查询 id=1 的信息)
# 创建数据表,并实现增删改查# 数据库 mybatis studentcreate database mybatis character set utf8;
use mybatis;
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20),
grade int,
department VARCHAR(20)
);
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼', 2020, '抓鱼专业');
INSERT INTO student (name, grade,department) VALUES('王者', 2021, '游戏boss专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼2', 2022, '扫地专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼3', 2021, '航天狩猎专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼4', 2020, '抓鱼专业');
# Student 实体类 (get and set + to string)package me. gacl. domain ; public class Student { private Integer id; private String name; private Integer grade; private String department; 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 Integer getGrade ( ) { return grade; } public void setGrade ( Integer grade) { this . grade = grade; } public String getDepartment ( ) { return department; } public void setDepartment ( String department) { this . department = department; } @Override public String toString ( ) { return "Student [id=" + id + ", name=" + name + ", grade=" + grade + ", department=" + department + "]" ; } }
# studentMapper.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 = " me.gacl.mapping.studentMapper" > < insert id = " insertOneStudent" parameterType = " me.gacl.domain.Student" > insert into student (name,grade,department)values(#{name},#{grade},#{department} ); </ insert> < select id = " getStudent" parameterType = " int" resultType = " me.gacl.domain.Student" > select * from student where id=#{id} </ select> < update id = " updateStudent" parameterType = " me.gacl.domain.Student" > update student set department = "计算机" where name =#{name}; </ update> < delete id = " deleteStudent" parameterType = " String" > delete from student where name=#{name}; </ delete> </ mapper>
# 在 mybatis-config.xml 中注册 studentMapper.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> < ! -- 1. 配置环境 ,默认的环境id为mysql -- > < environments default = "mysql" > < ! -- 1.2 . 配置id为mysql的数据库环境 -- > < environment id= "mysql" > < ! -- 使用JDBC的事务管理 -- > < transactionManager type= "JDBC" / > < ! -- 数据库连接池 -- > < 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> < ! -- 注册userMapper. xml文件, userMapper. xml位于me. gacl. mapping这个包下,所以resource写成me/ gacl/ mapping/ userMapper. xml -- > < mappers> < mapper resource= "me/gacl/mapping/userMapper.xml" / > < mapper resource= "me/gacl/mapping/studentMapper.xml" / > < / mappers> < / configuration>
# 创建 Test1 类,测试增删改查package me. gacl. test ; import java. io. IOException ; import java. io. InputStream ; 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 me. gacl. domain. Student ; public class Test1 { public static void main ( String [ ] args) throws IOException { String resource = "mybatis-config.xml" ; InputStream is = Resources . getResourceAsStream ( resource) ; SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder ( ) . build ( is) ; SqlSession session = sessionFactory. openSession ( ) ; String statement = "me.gacl.mapping.studentMapper.deleteStudent" ; int rows = session. delete ( statement, "张三" ) ; System . out. println ( "成功删除了" + rows + "条" ) ; session. commit ( ) ; session. close ( ) ; } }
配置 studentMapper.xml ,修改 statement ,调用方法
# 运行结果(updateStudent)