这是mybatis官方文档https://mybatis.org/mybatis-3/zh/configuration.html
第一个例子
Mybatis实现步骤
- 创建mysql数据库和表
- 创建maven工程
- 修改pom.xml
1)加入依赖:mybatis依赖、MySQL驱动、junit
2)在
<?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.fawde</groupId><artifactId>ch01-mybatis-first</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--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>5.1.9</version></dependency></dependencies><build><!--资源插件,处理src/main/java目录中的xml--><resources><resource><directory>src/main/java</directory><!--所在的目录--><includes><!--包括目录下的.properties,.xml 文件都会扫描到--><include>**/*.properties</include><include>**/*.xml</include><include>*.xml</include></includes><filtering>false</filtering></resource></resources></build></project>
- 创建实体类,定义属性,属性名和列明保持一致 ```java package com.fawde.domain;
public class Student { // 属性名和列名一样 private Integer id; private String name; private String email; private Integer age; // set ,get , toString
public Integer getId() {return id;}public String getName() {return name;}public String getEmail() {return email;}public Integer getAge() {return age;}public void setId(Integer id) {this.id = id;}public void setName(String name) {this.name = name;}public void setEmail(String email) {this.email = email;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "学生实体信息{" +"id=" + id +", name='" + name + '\'' +", email='" + email + '\'' +", age=" + age +'}';}
}
5. 创建Dao接口,定义操作数据库的方法。```javapackage com.fawde.dao;import com.fawde.domain.Student;import java.util.List;public interface StudentDao {//查询一个学生Student selectStudentById(Integer id);//public List <Student> selectStudents();//添加学生//返回值int:表示本次操作影响的数据库的行数int insertStudent(Student student);}
- 创建xml文件(mapper文件),写sql语句。
1)mybatis框架推荐把sql语句和Java代码分开
2) mapper文件:定义和dao接口在同一个目录,一个表一个mapper文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace :必须有值,自定义的唯一字符串推荐使用: dao 接口的全限定名称 --><mapper namespace="com.fawde.dao.StudentDao"><!-- <select>: 查询数据, 标签中必须是 select 语句id: 唯一标识,sql 语句的自定义名称,推荐使用 dao 接口中方法名称,使用名称表示要执行的 sql 语句resultType: 告诉mybatis,执行sql语句,把数据赋值给哪个类型的java对象。resultType的值现在使用的是Java对象全限定类名 --><select id="selectStudentById" resultType="com.fawde.domain.Student"><!--要执行的 sql 语句,查询一个学生 --><!--注意是没有分号的#{studentId}:占位符,表示从Java程序中传入过来的数据-->select id,name,email,age from student where id = #{studentId}</select><!--添加insert--><insert id="insertStudent">insert into student values(1003,"lifeng","lifeng@qq.com",26)</insert></mapper><!--1.约束文件http://mybatis.org/dtd/mybatis-3-mapper.dtd约束文件作用:定义和限制当前文件中可以使用的标签和属性吗,以及标签出现的顺序。2.mapper是根标签,namespace:命名空间,必须有值,不能为空,唯一值。推荐使用Dao接口的全限定名称。作用:参与识别sql语句的作用。3.在mapper的里面可以写<insert>,<update>,<delete>,<select><insert>里面是insert语句,他表示执行insert操作......-->
- 创建mybatis的主配置文件(XML文件):有一个,放在resources目录下
1)定义创建连接实例的数据源(DataSource)对象
2)指定其他mapper文件的位置
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//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="mydev"><environment id="mydev"><transactionManager type="JDBC"/><!--配置数据源,创建Connection对象--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/sqlearn?useUnicode=true&characterEncoding=utf-8"/><property name="username" value="root"/><property name="password" value=""/></dataSource></environment></environments><!--指定其他mapper文件的位置;其他mapper文件目的是找到其他文件的sql语句--><mappers><!--使用mapper的resource属性指定mapper文件的路径。这个路径是从target/calsses路径开启的使用注意:resource=“mapper文件的路径,使用/分割路径”一个mapper resource指定一个mapper文件--><mapper resource="com/fawde/dao/StudentDao.xml"/></mappers></configuration>
- 创建测试的内容。
1) 使用main方法,测试mybatis访问数据库
2) 也可以使用junit访问数据库
package com.fawde;import com.fawde.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.io.InputStream;import java.util.List;public class MyTest {//测试mybatis执行sql语句@Testpublic void testSelectStudentById() throws IOException {//访问mybatis读取student数据//1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess)String config="mybatis.xml";//2.读取这个config表示的文件InputStream in = Resources.getResourceAsStream(config);//3.创建了SqlSessionFactoryBuilder对象SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();//4.创建SqlSessionFactory对象SqlSessionFactory factory = builder.build(in);//5.获取SqlSession对象,从SqlSessionFactory中获取SqlSessionSqlSession sqlSession = factory.openSession();//6.【重要】指定要执行的sql语句的标识。// sql映射文件中的namespace + "." + select|update|insert|delete标签的id值//String sqlId = "com.bjpowernode.dao.StudentDao" + "." + "selectStudents";String sqlId = "com.fawde.dao.StudentDao.selectStudentById";//7. 重要】执行sql语句,通过sqlId找到语句// List<Student> studentList = sqlSession.selectList(sqlId);Student stu=sqlSession.selectOne(sqlId,1002);System.out.println("使用mybatis查询的一个学生:"+stu);//8.关闭SqlSession对象sqlSession.close();}@Testpublic void testInsertStudentById() throws IOException {String config="mybatis.xml";InputStream in = Resources.getResourceAsStream(config);SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(in);SqlSession sqlSession = factory.openSession();String sqlId = "com.fawde.dao.StudentDao.insertStudent";int stu=sqlSession.insert(sqlId);System.out.println("使用mybatis新增的一个学生,rows="+stu);sqlSession.close();}}
Mybatis的一些重要对象
Resources类
Resources: mybatis框架中的对象, 负责读取主配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactoryBuilder
SqlSessionFactoryBuilder : 创建SqlSessionFactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();//创建SqlSessionFactory对象SqlSessionFactory factory = builder.build(in);
SqlSessionFactory : 重量对象
SqlSessionFactory 是重量级对象, 程序创建一个对象耗时比较长,使用资源比较多。在整个项目中,有一个就够用了。
public interface SqlSessionFactory {SqlSession openSession();SqlSession openSession(boolean var1);SqlSession openSession(Connection var1);SqlSession openSession(TransactionIsolationLevel var1);SqlSession openSession(ExecutorType var1);SqlSession openSession(ExecutorType var1, boolean var2);SqlSession openSession(ExecutorType var1, TransactionIsolationLevel var2);SqlSession openSession(ExecutorType var1, Connection var2);Configuration getConfiguration();}
SqlSessionFactory:接口 , 它的接口实现类是 DefaultSqlSessionFactory
SqlSessionFactory作用: 获取SqlSession对象。SqlSession sqlSession = factory.openSession();
openSession()方法说明:
1. openSession() :无参数的, 获取是非自动提交事务的SqlSession对象
2. openSession(boolean): openSession(true) 获取自动提交事务的SqlSession.
openSession(false) 非自动提交事务的SqlSession对象
SqlSession
SqlSession接口 :是通过 SqlSessionFactory获取的。
SqlSession接口的实现类DefaultSqlSession。

定义了操作数据的方法,用于执行sql语句。
| selectOne() | 执行sql语句,最多得到一行记录,多于一行是错误的 |
|---|---|
| selectList() | 执行sql语句,返回多行数据 |
| selectMap() | 执行sql语句,返回一个Map结果 |
| insert() | 执行insert语句 |
| update() | 执行update语句 |
| delete() | 执行delete语句 |
| commit() | 提交事务 |
| rollback() | 回滚事务 |
注意SqlSession对象不是线程安全的,使用的步骤:<br />1)在方法内部使用, 在执行sql语句之前,先使用openSession()获取SqlSession对象。<br />2)调用SqlSession的方法,执行sql语句<br />3) 关闭SqlSession对象,执行SqlSession.close().<br /> 这样能保证他的使用是线程安全的。
使用工具类和模板
1)创建模板,mapper文件模板和mybatis主配置文件模板
创建模板的步骤:
创建模板

