1.什么是Mybatis
一种持久层的框架,类似于JDBC访问数据库的操作
jdbc使用的是Connection对象,PreparedStatement对象,ResultSet对象
而mybatis框架的核心对象有SqlSessionFactoryBuilder对象和SqlSessionFactory对象和SqlSession对象等,并且mybatis框架较为灵活
2.为什么使用框架:
通过框架来制定开发规范,更进一步保证所有的开发人员能够快速编写统一的代码,让开发人员专注于业务实现
3.常用框架技术
3.1 Spring
Spring是一个J2EE的框架,这个框架提供了对轻量级IOC的良好支持,同时也提供了对AOP技术非常好的封装,相比于其他的框架,Spring框架的设计更加模块化,框架内的每个模块都能完成特定的工作,而且各个模块可以独立的运行,不会相互的前置,因此,在使用Spring框架的时候,我们可以使用整个框架,也可以使用框架中的一部分
主要学习:
IOC:控制反转---DI(依赖注入),spring容器化管理,取代new对象
AOP:面向切面,专门的人做专门的事
3.2 SpringMVC
Spring MVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架,通过把Model,View,Controller分离,将web层进行职责解耦,把复杂的web应用分成逻辑清晰的几部分,简化开发,减少出错,方便组内开发人员之间的配合。
3.3 Mybatis
Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只需要关注SQL语句本身,不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。程序员直接编写原生态sql,可以严格控制sql执行性能,灵活度高
3.4Mybatis组成部分
核心对象:
SqlSessionFactoryBuilder; 用于生成SqlSessionFactory
SqlSessionFactory; 用于生成SqlSession
SqlSession; 用于执行sql语句
配置文件:
核心配置文件:mybatis-config.xml
sql映射文件:映射实体类和数据库中的表
4.mybatis小工程
4.1创建数据库:
CREATE TABLE `t_person` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`nickname` varchar(32) DEFAULT NULL,
`age` int(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t_person` VALUES ('1', 'zs', 'zz', '3');
INSERT INTO `t_person` VALUES ('2', 'lisi', 'll', '4');
INSERT INTO `t_person` VALUES ('3', 'wangwu', 'ww', '5');
创建一个数据库
4.2创建一个maven工程
包的结构路径,在src下面创建一个test文件夹,里面创建一个java文件夹,(test和main同级)设置为test类型
main中,和webapp同级的创建两个文件夹,一个java,一个resources,java设置问java文件夹,resources为资源文件夹
然后再java文件夹中创建包结构,域名.组织域名.工程名.包名。例如:cn.kgc.mybatis.entity实体类包
4.3加入依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
mybatis jar包依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
mysql 依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
4.5创建实体类
Person.java在cn.kgc.pro_mybatis.entity中
加载lombokjar包后,添加@Getter和@Setter就默认生成getset方法
@Getter
@Setter
public class Person {
private Integer id;
private String name;
private String nickName;
private Integer age;
}
4.6创建mapper/PersonMapper接口
mapper接口相当于dao接口,不同的是不需要手动写BaseDao工具类和实现类,mybatis框架中自动实现
<?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="cn.kgc.pro_mybatis.mapper.PersonMapper">
<-- namespace,命名空间,是对应的mapper接口的包路径 -->
<-- 里面添加sql语句,id是mapper接口中的方法名,不可以同名, -->
<-- resultType是返回值类型的路径 -->
<select id="findCount" resultType="java.lang.Integer">
select count(*) from t_person
<-- sql语句 -->
</select>
</mapper>
4.8 创建mybatis主配置文件mybatis-config.xml
在resources目录下,创建主配置文件,mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<-- 文件头 -->
<configuration>
<-- 环境配置:数据库的连接信息 -->
<-- default:配置的值需要和某个enviroment的id相同,访问对应的数据库 -->
<environments default="development">
<environment id="development">
<-- mybatis的事务类型,选择JDBC -->
<transactionManager type="JDBC"></transactionManager>
<-- 数据源 -->
<dataSource type="POOLED">
<-- 四个属性 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis001"/>
<property name="username" value="root"/>
<property name="password" value="111"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/kgc/pro_mybatis/mapper/PersonMapper.xml"/>
</mappers>
</configuration>
4.9测试类TestMybatis.java
在test,java中创建一个测试类,利用三大对象进行测试
package cn.kgc.test;
import cn.kgc.entity.Person;
import cn.kgc.mapper.PersonMapper;
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 java.io.IOException;
import java.io.InputStream;
public class Test {
@org.junit.Test
public void testFindCount() throws IOException {
//通过Resources.getResourceAsStream读取主配置文件,以流的形式
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//实例化SqlSessionFactoryBuilder
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//通过实例化SqlSessionFactoryBuilder创建SqlSessionFactory
SqlSessionFactory build = builder.build(in);
//通过SqlSessionFactory对象的openSession方法创建SqlSession
SqlSession sqlSession = build.openSession();
//执行方法
Integer count = sqlSession.getMapper(PersonMapper.class).findCount();
System.out.println("count:" + count);
//关闭流对象
sqlSession.close();
}
}
5.mybatis小工程2
5.1增删改等方法:
在上面测试了查询方法,现在可以试试增删改方法:
首先在mapper接口中添加方法,以增加为例子:
//增加
Integer addPerson(Person person);
sql映射文件:
注意:增删改查对应不同的标签,增删改没有返回值类型
<insert id="addPerson" parameterType="cn.kgc.mapper.PersonMapper">
insert into t_person(`name`,nickname,age) values (#{name},#{nickname},#{age})
</insert>
增insert,删delete,改update,查select
test测试:
注意:增删改需要先提交,commit(),先条件后关闭
@org.junit.Test
public void testAddPerson() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(in);
SqlSession sqlSession = build.openSession();
Person person = new Person();
person.setName("yangchaoyue");
person.setNickname("杨超越");
person.setAge(22);
sqlSession.getMapper(PersonMapper.class).addPerson(person);
//提交事务
sqlSession.commit();
sqlSession.close();
}
对应的sql映射文件:
<select id="findByNameNickname" resultType="cn.kgc.entity.Person" parameterType="cn.kgc.entity.Person">
select * from t_person where `name`=#{name} and nickname=#{nickname}
</select>
<select id="findByNameNickname2" resultType="cn.kgc.entity.Person">
select * from t_person where `name`=#{name} and nickname=#{nickname}
</select>
<select id="findByNameNickname3" resultType="cn.kgc.entity.Person" parameterType="java.util.Map">
select * from t_person where `name`=#{name} and nickname=#{nickname}
</select>
5.3优化测试类,添加工具类
在测试的时候,可以看到,每个测试方法,都需要三大对象来创建,所以将相同的代码片段提取,封装成一个工具类
package cn.kgc.util;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
//定义私有的静态SqlSessionFactory对象
private static SqlSessionFactory factory = null;
//在类加载的时候执行,读取配置文件,创建一个SqlSessionFactory对象并赋值
static {
try {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
if (factory != null) {
sqlSession = factory.openSession();
}
return sqlSession;
}
}
5.4sql语句中的#和$
在sql映射文件中,可以添加#或者$来进行值的操作
但是#是传递值
而$是替代字段
例如,在查询排序的时候,用两个不同的符号,会出现不同的效果,#无法排序
除此之外,#安全PreparedStatement,$不安全Statement
5.5将主配置文件的四个路径改成配置文件的方式:
将主配置文件中的死数据修改成活数据
在resources文件夹根目录下创建文件jdbc.properties,添加jdbc连接数据库的参数
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_mybatis001
username=root
password=111
在主配置文件中添加资源路径,并修改下方的参数
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/kgc/mapper/PersonMapper.xml"/>
</mappers>
</configuration>