阅读你将学会:
1.从零开始配置一个Mybatis项目
2.通过非常简单的实例掌握Mybatis基本操作
3.mybatis的三种SQL映射方式
1.1项目介绍
基于mybatis的mysql数据库增删改查程序。
1.2程序流程和目标效果:
1.有一张student学生表,只有学号id、名字name、年龄age,三个属性
2.通过mybatis完成对student表的增删改查(crud)
3.三种SQL映射方式都过一遍:注释、session.selectXXX、session.getMapper
1.2.整体目录结构展示:
一般把Test1放在test文件夹中,做@test单元测试,这里没放是因为一开始没有想做单元测试。
2.1项目开始
2.1数据表的创建:
CREATE TABLE `table1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
2.3.创建一个maven项目
2.4.打开pom.xml配置文件
加入这个文件需要的所有依赖
1.mybatis核心依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
2.其余依赖:(主要是日记和mysql)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.2-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ow2.asm/asm -->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.0.3</version>
</dependency>
</dependencies>
2.5.核心配置文件:mybatis-configs.xml
2.5.1.这个setting非常好用,可以打印出最终执行的SQL。
<settings>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
2.5.2.mybatis主要就是通过配置文件去映射
注意:其中Mapper.xml如果在resouces下不需要写前缀
<!-- 配置映射文件 -->
<mappers>
<mapper resource="Mapper.xml"/>
<package name="dao.StudentDao"/>
</mappers>
2.5.3.全部配置文件内容(包含上述两者)
<?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>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/test1?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false" />
<property name="username" value="root" />
<property name="password" value="你的密码" />
</dataSource>
</environment>
</environments>
<!-- 配置映射文件 -->
<mappers>
<mapper resource="Mapper.xml"/>
<package name="dao.StudentDao"/>
</mappers>
</configuration>
2.6创建实体类Student
1.其中@Data是Lombok插件,用于自动生成get/set/equels方法的,如果不想安装插件,把这个注释去掉,并且手写set/get即可。
2.Student每个属性对应数据库表中的字段
@Data public class Student {
private int id;
private String name;
private int age;
public Student(){
super();
}
public Student(int id,String name,int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public void showStudent() {
System.out.println("查询结果:[id=" + this.id + ", name=" + this.name + ", age=" + this.age + "]" + "\n");
}
2.6三种SQL映射方式以及Dao接口:studentDao
三种SQL映射方式:
1.第一种,使用注释的方式,把sql写在Dao接口中
public interface StudentDao {
/**
* 插入数据
* @param student
*/
@Insert("insert into table1 values(#{id},#{name},#{age})")
void annotationInsert(Student student);
}
2.第二种,使用getMapper方法,在Dao中声明,在xml中写SQL
public interface StudentDao {
Student InterfaceSelectOne(int id);
}
3.第三种,直接在Mapper.xml写sql
<select id="mySelectOne" parameterType="int" resultType="student.Student">
select * from table1 where id=#{v}
</select>
第2.3种方法不够简洁,所以我这个程序使用第一种:SQL写在注释中的形式。
2.7映射文件Mapper.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">
<!-- namespace:命名空间,用于隔离sql-->
<mapper namespace="dao.StudentDao">
<!-- 第二种SQL映射方式,如果采用注释SQL的方式,就不需要写这个 -->
<select id="InterfaceSelectOne" parameterType="int" resultType="student.Student">
select * from table1 where id=#{v}
</select>
</mapper>
2.8开始测试
通过sqlSessionFactory的openSession方法获取session,并且传给以下几种测试对象。
1.wayOne:第三种SQL映射方式
2.wayTwo:第二种SQL映射方式
3.xxxxByAnnotation:注释的SQL映射方式
public static void main(String[] args) throws IOException {
//Mybatis中的工具类Resources可以读取指定配置文件(以及映射文件)
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-configs.xml");
// 创建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 通过工厂创建sqlSession
SqlSession session = sqlSessionFactory.openSession();
wayOne(session);
wayTwo(session);
selectByAnnotation(session);
insertByAnnotation(session);
deleteByAnnotation(session);
updateByAnnotation(session);
}
wayOne:
static void wayOne(SqlSession session){
// 方法一:session直接去Mapper.xml找sql语句
//缺点:复杂项目命名空间名称很长,传的这个方法名前面就会带上一长串的命名空间,非常复杂不美观,而且传参错了不容易被发现
Student a = session.selectOne("mySelectOne",1);
a.showStudent();
session.close();
}
wayTwo:
static void wayTwo(SqlSession session){
//方法二:session.getMapper方法去调一个代理接口,跟映射文件的交互全部通过这个接口负责
//优势:比起方法一的selectXXX,避免了命名空间过于复杂导致的参数名字过长且易错的问题
StudentDao sd = session.getMapper(StudentDao.class);
Student b = sd.InterfaceSelectOne(2);
b.showStudent();
session.close();
}
xxxxByAnnotation:
static void insertByAnnotation(SqlSession session){
Student c = new Student();
c.setId(5);
c.setName("小五");
c.setAge(15);
StudentDao sd = session.getMapper(StudentDao.class);
sd.annotationInsert(c);
session.commit();//提交到数据库
session.close();
}