mybatis框架
1.框架(Framework)的概念
1.1 软件开发常用结构
1.1.1 三层架构
三层架构包含的三层
界面层(User Interface layer),业务逻辑层(Busiess Logic Layer),数据访问层(Data access Layer)
三层的职责
1.界面层(表示层,视图层):功能是接收用户的数据。显示请求的处理结果
2.业务逻辑层:接收表示传递过来的数据,检查数据,计算业务逻辑,调用数据访问层获取数据
3.数据访问层:与数据库打交道,实现数据的增删改查,将业务层处理的数据保存到数据库中
三层对应的包
界面层:conntroller(servlet)
业务逻辑层:service包(xxxservice类)
数据访问层:dao包(xxxDao类)
三层的处理请求的交互:
用户------->界面层------->业务逻辑层------->数据访问层(持久层)------->数据库(mysql)
三层对应的框架:
界面层------------servlet----------springmvc(框架)
业务逻辑层------service----------spring(框架)
数据访问层------dao类------------mybatis(框架)
1.1.2框架
框架是一个模块:
1.框架中定义一个好了一些的功能,这些功能是可用的
2.可以加入项目中自己的功能,这些功能时可以利用框架写好的功能
框架是一个软件,半成品的软件,定义好的一些基础功能,需要加入你的共能就是完整得。
基础功能是可以重复使用得,可升级得
框架的特点:
1.框架一般不是全能的,不能做 所有的事情
2.框架是针对某一个领域有效,特长在某一个方面,
3.框架是一个软件
1.1.3 使用JDBC的缺陷
1.代码比较多,开发效率低
2.需要关注Connection,statement,ResultSet对象的创建和销毁
3.对于resultset查询的结果,需要自己封装为list
4.重复的代码比较多
5.业务代码和数据库操作混在一起
1.1.4 mybatis框架概述
mybatis框架
一个框架,早期叫做ibatis,代码在github
mybatis是Mybatis SQL Mapper Framwork for java (sql映射框架)
1.sql mapper :sql映射
可以把数据库表中的一行数据,映射为一个Java对象
一行数据可以看作一个Java对象,操作这个对象,就相当于操作表中的数据
2.Data Access Object(DAOs):数据访问,对数据执行增删改查
mybatis提供了哪些功能:
1.提供了Connection,statement,ResultSet的能力,不需要开发人员创建这些对象了
2.提供了执行sql语句的能力,不用你执行sql
3.提供了循环sql,把sql的结果转为Java对象,list集合的能力
4.提供了关闭资源的能力,不用关闭连接对象
开发人员做的是:提供sql语句
最后是:开发人员提供sql语句------mybatis处理sql------开发人员得到list集合或Java对象(表中的数据)
总结:
mybatis是一个sql映射框架,提供了数据库的操作能力,增强的JDBC,使用mybatis让开发人员集中精神写sql就可以了,不必关心Connection,statement,ResultSet的创建,销毁,sql的执行
Mybatis可以完成;
1.注册数据库的驱动,例如(class.forname(“com.mysql.jdbc.Driver”))
第二章 Mybatis快速入门
2.1 入门案例
2.1.1 使用mybatis准备
下载mybitis
http://github.com/mybatis/mybatis-3/releases
2.1.2 搭建mybatis开发环境
(1)创建mysql数据库和表
(2) 创建maven工程
(3) 删除默认创建的App文件
(4) 加入maven坐标
<!--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>
(5) 加入maven插件
<!--resource标签-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<!--包括目录下的.properties.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>
1.8
</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
(6) 编写Student实体类
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
(7) 编写dao接口 studentDao
/*
*
* 接口操作student表
* */
public interface StudentDao {
//查询student表中的数据
//这些数据要放在集合中
public List<Student> selectStudents();
//插入方法
//参数:student,表示要插入到数据库中的数据
//返回值,int,表示要执行insert操作后的 影响数据库的行数
public int insertStudent(Student student);
}
(8) 编写dao接口Mapper映射文件Student
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jike.dao.StudentDao">
<!--
select:表示查询操作
id:你要执行的sql语法的唯一标识,mybais会使用这个id来找到要执行的sql语句
可以自定义,但要求你使用接口中的方法名称
resultType:表示结果类型,是sql语句执行后的ResultSet,遍历这个resultSet的到的Java对象的类型
值写的类型的全限定名称(类的全路径-类路径)
-->
<select id="selectStudent" resultType="com.jike.domain.Student">
select id,name,email,age from student order by id
</select>
<insert id="insertStudent" >
<!--mybatis如何引用实体类中的属性值
方法如下:用占位符的形式-#{}
-->
insert into student value (#{id},#{name},#{email},#{age})
</insert>
</mapper>
<!--
sql映射文件:写sql语句,mybatis是执行这些sql
1.指定约束文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
mybatis-3-mapper.dtd是约束文件的名称,扩展名是dtd的。
2.约束文件的作用:限制,检查在当前文件中出现的标签,属性必须符合mybatis的要求
3.mapper:是当前问件的根标签,必须的。
namespace:叫做命明空间,唯一值的,可以是自定义的字符串
要求你使用的dao接口的全限定名称
4.在当前文件,可以使用特定的标签,表示数据库的特定操作
<select>:表示执行查询,select语句
<update>:表示更新数据库的操作,就是在update标签中,写的是update sql语句
<insert>:表示插入,放的是insert语句
<delete>:表示删除,执行的delete语句
-->
(9 )创建mybatis主配置文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--settings:控制mybatis的全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--环境配置:数据库的连接信息
default:必须和和某个environment的id值一样
告诉mybatis使用哪个数据库的连接信息,也就是访问哪个数据库
-->
<environments default="mydev">
<!-- environment:一个数据库的信息配置,环境
id:一个唯一值,自定义,表示环境的名称
-->
<environment id="mydev">
<!-- transactionManager:mybatis的事务类型
type:JDBC(表示使用jdbc中的Connection对象中的commit,rollback做事务处理)
-->
<transactionManager type="JDBC"/>
<!--
dataSource:表示数据源,链接数据库
type:表示数据源的类型,POOLED表示使用连接池
-->
<dataSource type="POOLED">
<!--
driver,url,username,password,都是固定的,不能自定义
-->
<!--数据库驱动名称-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--链接数据库的url字符串-->
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<!--访问数据库的用户名-->
<property name="username" value="root"/>
<!--访问数据库的密码-->
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--
sql mapper(sql映射23文件的位置)
-->
<mappers>
<!--
一个mapper标签指定一个文件的位置
从类路径开始的路径信息,target/class(类路径)
-->
<mapper resource="com/jike/dao/StudentDao.xml"/>
</mappers>
</configuration>
<!--
mybatis的主配置文件:主要定义数据库的配置信息,sql映射文件的位置
1.约束文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
mybatis-3-config.dtd:约束文件的名称
2.configuration 根标签
-->
(10)创建测试类MybatisText
public static void main(String[] args) throws IOException {
//访问mybatis读取student数据
//1.定义mybatis主配置文件
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对象,从中取出
SqlSession sqlSession=factory.openSession();
//6.指定要执行的sql语句的标识,sql映射文件中的namespace+“.”标签的id
//String sqlId="com.jike.dao.StudentDao"+"."+"selectStudent";
String sqlId="com.jike.dao.StudentDao.selectStudent";
//7.执行sql语句,通过sqlId找到语句
List<Student> studentList=sqlSession.selectList(sqlId);
//8.输出结果
//studentList.forEach(stu -> System.out.println(stu));
for (Student stu:studentList
) {
System.out.println("查询的学生="+stu);
}
//9.关闭sqlSession对象
sqlSession.close();
}
(11)配置日志功能
<!--settings:控制mybatis的全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
(12)创建使用mybatis类,通过mybatis访问数据库
private static SqlSessionFactory factory=null;
//静态方法创建factory
static {
String config="mybatis.xml";
try {
InputStream in= Resources.getResourceAsStream(config);
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;
}
2.1.3 insert操作
(1)StudentDao接口中增夹方法
(2)Student .xml加入sql语句
(3)增加测试方法
web前端的学习
React angular Vue Ajax
git,gulp或webpack等工具
svn,gulp,webpack等工具;
2.2 Mybatis对象分析
2.2.1 主要类的介绍
1)Resources:mybatis中的一个类,负责读取主配置文件
InputStream in= Resources.getResourceAsStream(config);
2)SqlSessionFactoryBuilder:创建SqlSessionFactory对象
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//4.创建SqlSessionFactory对象
SqlSessionFactory factory=builder.build(in);
3)SqlSessionFactory:重量级对象,程序创建一个对象耗时间比较长,使用资源比较多
在整个项目中,有一个就够用了
SqlSessionFactory接口:接口实现类DefaultSqlSessionFactory
SqlSessionFactory作用:获取SqlSession对象,SqlSession sqlSession=factory.openSession();
openSession()方法说明:
1.openSession():无参数的,获取的是非自动提交事务的openSession对象
2.openSession(boolean):openSession(true) 获取自封提交事务的openSession
openSession(false) 非自动提交事务的openSession对象
4)SqlSession:
SqlSession接口:定义了操作数据库的方法,例如:selectOne,selectList,insert,update,delete,commit,rollback
SqlSession接口的实现类DefaultSqlSession(实现这些数据库的方法)
使用要求:SqlSession对象不是线程安全的,需要在方法内部使用,在执行sql语句之前,使用openSession()获取SqlSession对象,在执行sql语句之后,需要关闭它,执行SqlSession.close(),这样就能保证他的使用时线程安全的
2.2.2工具类的使用
创建一个工具类MybatisUtils,里面包含定义获取sqlsession的方法,一个静态方法,获取配置文件,静态方法创建factory,在测试方法中直接MyBatisUtils.getSqlSession();就可以使用完成创建
2.3 Mybatis使用传统Dao开发
具体操作步骤
2.3.1新建的student表
2.3.2加入meven的mybatis坐标,mybatsi驱动的坐标
<!--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>
2.3.3创建实体类,student–保存表中的一行数据
创建一个包(domain),里面创建一个实体类,包含数据库的属性
2.3.4创建持久层的dao接口(studentDao),执行操作数据库的方法(studentDao.xml)
1.创建一个包(dao),先创建一个接口(StudentDao),这里面包含数据库的增删改查的方法,例如:List selectStudents();
2.再创建一个xml文件,(mapper属性)这里面是数据库的增删改查操作代码,其中namespace是接口的全限定类名,resultType是实体类的全限定类名
2.3.5创建一个mybatis使用的配置文件
创建一个包(utils),创建一个MyBatisUtils类----->访问mybatis读取student数据,先创建一个静态方法,李明创建一个factory工厂
static {
String config="mybatis.xml";
try {
InputStream in= Resources.getResourceAsStream(config);
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;
}
注意,后期有改动
2.3.6创建mybatis的主配置文件(resultset文件夹下创建mybatis.xml文件)
这里面是连接数据库的操作
<configuration>
<!--settings:控制mybatis的全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jike/dao/StudentDao.xml"/>
</mappers>
其中下的 中的resource是StudentDao.xml文件夹的位置
2.3.7最后创建测试类进行测试程序(使用注解)
@Test
public void selectMybatis(){
StudentDao dao1=new StudentDaoImpl();
List<Student> studentList=dao1.selectStudents();
for (Student stu:studentList) {
System.out.println(stu);
}
}
第三章 Mybatis框架dao代理
3.1Dao代理实现数据库操作
3.1.1 步骤
3.1.2 原理
动态代理:parameterType="java.lang.Integer"
3.2 深入理解参数
从java代码中把数据传入到mapper文件的sql语句中
3.2.1 parameterType
写在mapper文件中的一个属性。表示dao接口中方法的参数的数据类型
例如:StudentDao接口
public Student selectStudentById(Integer id)
3.2.2 一个简单参数
public interface StudentDao {
//定义查询方法
/*
* 一个简单类型的参数:
* 简单类型:mybatis把java的基本数据类型和String都叫简单类型
*
* 再mapper文件获取简单类型一个参数,使用#{任意字符}
* */
public Student selectStudentById(Integer id);
接口:public Student selectStudentById(Integer id);
mapper文件:select id,name,email,age from student where id=#{id}
其余的类似上面的步骤
<mapper namespace="com.jike.dao.StudentDao">
<!--parameterType="java.lang.Integer"可以去掉-->
<!--
parameterType:dao接口中方法参数的数据类型
parameterType它的值是java的数据类型全限定名称或者mybatis定义的别名
例如:parameterType="java.lang.Integer"
parameterType="int"
注意parameterType不是强制的,mybatis通过反射机制能够发现接口参数的数据类型
所以可以没有,一般我们也不会
-->
<select id="selectStudentById" parameterType="java.lang.Integer" resultType="com.jike.domain.Student">
select id,name,email,age from student where id=#{id}
</select>
@Test
public void selectMybatisById(){
/*
* 使用mybatis的动态代理机制,使用sqlsession.getMapper(dao接口)
* getMapper能获取dao接口对于的实现类对象
* */
SqlSession session= MyBatisUtils.getSqlSession();
StudentDao dao=session.getMapper(StudentDao.class);
Student student=dao.selectStudentById(1);
System.out.println(student);
}
3.2.3 多个参数–使用@Param
接口 public List selectMulitParam(@Param(“myname”) String name,@Param(“myage”) Integer age)
使用@Param(“参数名”)String name
在mapper文件中配置
select * from student where name=#{myname} or age=#{myage} ``` /* * 多个参数:命名参数,在形参定义的前面加入@param(“自定一参数名”) * */ public interface StudentDao { List selectStudentParam(@Param("myname") String name, @Param("myage") Integer age); ```<!--多个参数,使用@param命明-->
<select id="selectStudentParam" resultType="com.jike.domain.Student">
select name,email,age from student where name=#{myname} or age=#{myage}
</select>
@Test
public void selectStudentParam(){
SqlSession session= MyBatisUtils.getSqlSession();
StudentDao dao=session.getMapper(StudentDao.class);
List<Student> stu=dao.selectStudentParam("李四",32);
for (Student student: stu){
System.out.println("学生="+stu);
}
session.close();
}
3.2.4 多个参数–使用对象
/*
* 多个参数:使用java对象作为接口中的方法参数
* */
List<Student> selectStudentObject(QueryParam param);
新建一个包,包中含有这个类
public class QueryParam {
private String paramName;
private Integer paramAge;
public String getParamName() {
return paramName;
}
public void setParamName(String paramName) {
this.paramName = paramName;
}
public Integer getParamAge() {
return paramAge;
}
public void setParamAge(Integer paramAge) {
this.paramAge = paramAge;
}
}
<!--多个参数,使用Java对象的属性值,作为参数的实际值
使用对象的语法:#{属性名,javaType=类型名,jdbcType=数据类型} 很少用
javaType:指java中的属性数据类型
jdbcType:在数据库中的数据类型
例如:#{paramName,javaType=java.lang.String,jdbcType=VARCHAR}
name=#{paramName,javaType=java.lang.String,jdbcType=VARCHAR
age=#{paramAge,javaType=java.lang.Integer,jdbcType=INTEGER
我们使用简化的方式:#{属性名},javaType,jdbcType的值MyBatis反射能获取,不用提供
-->
<select id="selectStudentObject" resultType="com.jike.domain.Student">
select name,email,age from student where name=#{paramName} or
age=#{paramAge}
</select>
@Test
public void selectStudentObject(){
SqlSession session= MyBatisUtils.getSqlSession();
StudentDao dao=session.getMapper(StudentDao.class);
QueryParam param=new QueryParam();
param.setParamName("123");
param.setParamAge(12);
List<Student> stu=dao.selectStudentObject(param);
for (Student student: stu){
System.out.println("学生="+stu);
}
session.close();
}
3.2.5多个参数–按位置(了解)
3.2.6 多个参数–使用Map
Map集合可以存储多个值,使用Map向mapper文件一次传入多个参数,Map集合使用String的key
Object类型的值存储参数,mapper文件使用#{key}引用参数值。
例如 :
Map<String,Object> data=new HashMap<String,Object>();
data.put(“myname”,“liming”);
data.put(“myage”,20);
接口的方法
List<Student> stu(Map<String,Object> map);
/*
* 多个参数:使用Map
* */
List<Student> selectStudentMap(Map<String,Object> map);
<!--多个参数,使用map-->
<select id="selectStudentMap" resultType="com.jike.domain.Student">
select name,email,age from student where name=#{myname} or
age=#{myage}
</select>
@Test
public void selectStudentMap(){
SqlSession session= MyBatisUtils.getSqlSession();
StudentDao dao=session.getMapper(StudentDao.class);
Map<String,Object> data=new HashMap<>();
data.put("myname","123");
data.put("myage",12);
List<Student> stu=dao.selectStudentMap(data);
for (Student student: stu){
System.out.println("学生="+stu);
}
session.close();
}
3.2.7 # 和 $(建议使用#)
#:占位符告诉mybatis使用的实际参数值代替,并使用PrepareStatement对象执行sql语句,#{…}代替sql语句中的 ? ,这样做更安全,更迅速,同通常也是首选的做法。
mapper文件:
<select id="selectStudentObject" resultType="com.jike.domain.Student">
select name,email,age from student where name=#{paramName} or
age=#{paramAge}
</select>
转为mybatis执行的是:
Sql sql=" select name,email,age from student where id=?";
PrepareStatement ps=conn.PrepareStatement();id
ps.setInt(1,1005);
解释:where id=?就是id=#{id};
ps.setInt(1,1005)中的1005可以代替#{id}
$ 字符串替换,告诉mybatis使用$ 包含的字符串替换所在的位置,使用statement把sql语句和${}的内容连接起来,主要用在替换表明,列名,不同列排序等操作。
3.2.8 复习
什么是动态代理:mybatis帮你创建dao接口的实现类,在实现类中调用SqlSession的方法执行sql语句
使用动态代理的方式:
1.获取SqlSession对象,
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
sqlSession=factory.openSession();
2.使用getMapper方法获取某个接口的对象
session.getMapper(StudentDao.class);
3.使用dao接口方法,调用方法执行mapper文件中的sql语句
使用动态代理的要求:
1.dao接口和mapper文件放在一起,同一个目录
2.dao接口和mapper文件名称一致
3.mapper文件中的namespace的值是dao接口的全限定名称
4.mapper文件中select,insert,update,delete等的id是接口中方法名称
5.dao接口中不要使用重载方法,不要使用同名的,不同参数的方法
3.3 封装Mybatis输出结果
3.3.1 resultType
resultType:执行sql得到的ResultRst转换的类型,使用类型的完全限定名或别名,注意如果返回的是集合,那么应该设置为集合包含的类型,而不是集合本身。resultType和resultMap不能同时使用
mybatis的输出结果
mybatis执行了sql语句,得到Java对象
1.resultType结果类型,指sql语句执行完毕后,数据转为的Java对象,java对象是任意的
resultType结果类型的值可以是 1.类型的全限定名称,2.类型的别名,例如 java.lang.Integer的别名是int
处理方式:
1.mybatis执行sql语句,然后mybatis调用类的无参数构造方法,创建对象
2.mybatis把ResultSet指定列值付同名的属性
举例:
<select id="selectStudentObject" resultType="com.jike.domain.Student">
select name,email,age from student where name=#{paramName} or
age=#{paramAge}
</select>
对等的jdbc
ResultSet rs=executeQuery(“select id,name,email,age from setudent”)
while(rs.next()){
Student stu=new Student();
stu.setId(rs.getIntId());
stu.setName(rs.getStringName());
}
A 简单类型
接口方法:
int countStudent();
mapper文件:
<select id="countStudent" resultType="int">
select count(*) from student
</select>
B 对象类型
接口方法:
Student selectById(int id);
mapper文件中:
<select id="selectById" resultType="com.jike.domain.Student">
select name,email,age from student where id=#{id}
</select>
框架的处理:使用构造方法创建对象,调用setXXX给属性赋值。
Student student=new Student();
sql语句 Java对象
id setId(rs.getInt(“id”)) 调用列名对应的set方法
name setName(rs.getString(“name”)) id列---------setId()
email setEmail(rs.getString(“email”)) name列-----setName()
C Map
sql的查询结果作为Map的key和value,推荐使用Map<Object,Object>
注意:map作为接口返回值,sql语句的查询结果做多只能有一条记录,大于一条记录时错误的
3.3.2 resultMap
resultMap可以自定义sql的结果和Java对象属性的映射关系,更灵活的把列值赋值给指定属性
常用在列名和Java对象属性名不一样的情况
resultMap:结果映射,制定列名和java对象的属性对应关系
1.你自定义列值赋值给哪个属性
2.当你的列名和属性名不一样时,一定要使用resultMap
使用resultMap方法
1.先定义resultmap
2.在select标签中,使用resultMap来引用1定义的
定义resultMap
id:自定义名称,表示你定义的这个resultMap
type:java类型的全限定类名
<resultMap id="studentMap" type="com.jike.domain.Student">
列明和java属性的关系
主键列,使用id标签
column:列明
property:Java类型的属性名
<id column="id" property="id"/>
非主键列使用result
<result column="name" property="name"/>
<result column="email" property="email"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectAllStudent" resultMap="studentMap">
select id,name,email,age from student
</select>
3.3.3 实体类属性名和列名不同的处理方式
(1)使用列名和
(2)使用
public interface StudentDao {
/*
* 使用resultMap定义映射文件
* */
List<Student> selectAllStudent();
<!--使用resultMap方法
1.先定义resultmap
2.在select标签中,使用resultMap来引用1定义的
-->
<!--定义resultMap
id:自定义名称,表示你定义的这个resultMap
type:java类型的全限定类名
-->
<resultMap id="studentMap" type="com.jike.domain.Student">
<!--列明和java属性的关系-->
<!--主键列,使用id标签
column:列明
property:Java类型的属性名
-->
<id column="id" property="id"/>
<!--非主键列使用result-->
<result column="name" property="name"/>
<result column="email" property="email"/>
<result column="age" property="age"/>
</resultMap>
<!---->
<select id="selectAllStudent" resultMap="studentMap">
select id,name,email,age from student
</select>
@Test
public void selectAllStudent(){
SqlSession session=MyBatisUtils.getSqlSession();
StudentDao dao= session.getMapper(StudentDao.class);
List<Student> students= dao.selectAllStudent();
for (Student stu:students) {
System.out.println("查询的学生时:"+stu);
}
session.close();
}
3.4模糊查询 like
模糊查询的实现的有两种方式,一是java代码中给查询数据加上“%”;二是给条件位置夹上“%”
第一种:Java代码中提供要查询的“%李%”
第二种:mapper文件中使用like name=“%” #{xxx} “%”
public interface StudentDao {
/*
* 模糊查询
* */
List<Student> selectLike(String name);
<!--第一种模糊查询,在Java代码指定like的连接内容-->
<select id="selectLike" resultType="com.jike.domain.Student">
select id,name,email,age from student where name like #{name}
</select>
@Test
public void selectLike(){
SqlSession session=MyBatisUtils.getSqlSession();
StudentDao dao= session.getMapper(StudentDao.class);
//准备like的内容
String name="%张%";
List<Student> students= dao.selectLike(name);
for (Student stu:students) {
System.out.println("查询的学生时:"+stu);
}
session.close();
}
第四章 MyBatis框架动态SQL
动态SQL
指的是sql的内容是变化的,可以根据条件获取到不同的sql语句
主要是where部分发生变化
动态sql的实现,使用的mybatis提供的标签,常用的标签有,,
4.1环境准备
4.2动态sql之
是条件判断的
语法:
部分sql语句
public interface StudentDao {
//使用动态sql,参数要是Java对象
List<Student> selectStudentif(Student student);
<!-- if
<if test="使用参数Java对象的属性值作为判断条件 语法,属性=xxx值">
-->
<select id="selectStudentif" resultType="com.jike.domain.Student">
<include refid="studentSql"></include>
where
<if test="name !=null and name !='' ">
name=#{name}
</if>
<if test="age > 0">
and age>#{age}
</if>
</select>
mybatis.xml配置文件中
<!--定义别名-->
<typeAliases>
<!--
第一种方式:
可以指定一个类型一个自定义别名
type:自定义类型的全限定名称
alies:别名(短小,容易记忆)
使用时,resultType直接是别名
-->
<typeAlias type="com.jike.domain.Student" alias="stu"></typeAlias>
<!--
第二种方式:
<package name=""/>,name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)
使用时,resultType直接是类名
-->
<!-- <package name="com.jike.domain"/>-->
</typeAliases>
<!--配置插件plugin-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
@Test
public void selectStudentif(){
SqlSession session= MyBatisUtils.getSqlSession();
StudentDao dao=session.getMapper(StudentDao.class);
Student student=new Student();
student.setName("李四");
student.setAge(20);;
List<Student> students=dao.selectStudentif(student);
for (Student stu:students
) {
System.out.println("学生是"+stu);
}
session.close();
}
4.3动态sql之
使用来包含多个if 的,当多个if成立的,where会自动增加一个where关键字
并去掉if中多余的and,or等
public interface StudentDao {
//使用动态sql,参数要是Java对象
List<Student> selectStudentwhere(Student student);
<!--where: <where> <if>....</if> </where> -->
<select id="selectStudentwhere" resultType="com.jike.domain.Student">
<include refid="studentSql"></include>
<where>
<if test="name !=null and name !='' ">
name=#{name}
</if>
<if test="age > 0">
or age>#{age}
</if>
</where>
</select>
4.4动态sql之
标签用于实现对数组和集合的遍历,对其使用,
循环Java中的数组,list集合,主要用在sql的in语句中
需要注意:
collection表示遍历的集合类型,list,array等;
open,close,separator为对遍历内容的sql拼接
<foreach collection="集合类型" open="开始的字符" close="结束的字符" item="集合中的成员" separator="集合成员之间的分隔符">
#{item}
</foreach>
语法规则:
collection:表示接口中的方法参数的类型,如果是数组使用array,如果是list集合使用list
item:自定义,表示数组和集合成员的变量
open:循环开始的字符
close:循环结束的字符
separator:集合成员之间的分隔符
public interface StudentDao {
//foreach 用法一
List<Student> selectForeachone(List<Integer> idlist);
//foreach 用法二
List<Student> selectForeachtwo(List<Student> stulist);
<!--foreach使用1,List<Integer>-->
<select id="selectForeachone" resultType="com.jike.domain.Student">
select * from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
<select id="selectForeachtwo" resultType="com.jike.domain.Student">
select * from student where id in
<foreach collection="list" item="stu" open="(" close=")" separator=",">
#{stu.id}
</foreach>
</select>
@Test
public void selectForeach(){
SqlSession session=MyBatisUtils.getSqlSession();
StudentDao dao= session.getMapper(StudentDao.class);
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
List<Student> students= dao.selectForeachone(list);
for (Student stu:students
) {
System.out.println("循环的结果是"+stu);
}
}
@Test
public void selectForeachtwo(){
SqlSession session=MyBatisUtils.getSqlSession();
StudentDao dao= session.getMapper(StudentDao.class);
List<Student> list=new ArrayList<>();
Student s1=new Student();
s1.setId(1);
list.add(s1);
s1.setId(2);
list.add(s1);
List<Student> students= dao.selectForeachtwo(list);
for (Student stu:students
) {
System.out.println("循环的结果是"+stu);
}
}
4.5动态sql之代码片段
标签用于定义sql片段,以便其他sql标签复用,而其他标签使用了该SQL片段,需要使用子标签,该标签可以定义sql语句中的任何部分,所以子标签可以放在动态sql的任何位置
动态sql之代码片段:就是复用一些语句
步骤:
1.先定义 :sql语句,表名,字段等
2.在使用,
3.
接口方法:
List
第五章 MyBatis配置文件
5.1主配置文件
<!--settings:控制mybatis的全局行为-->
<settings>
<!--设置mybatis输出日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
5.2dataSource标签
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
dataSource:表示数据源,Java体系中,规定实现了javax.sql.DataSource接口的都是数据源
type:指定数据源的类型
1.POOLED:使用连接池,mybatis会创建PooledDataSource类
2.UPOOLED:不使用连接池,在每次执行sql语句,先创建连接,执行sql,在关闭连接
mybatis会创建一个UnPooledDataSource,管理Connection对象的使用
5.3 事务
<transactionManager type="JDBC"/>
transactionManager:mybatis提交事务,回顾事务的方式
type:事务的成立类型
JDBC:表示mybatis底层是调用JDBC中的connection对象的,commit,rollback
MANAGED:把mybatis事务处理委托给其他的容器,(一个服务器软件,一个框架(spring))
5.4 使用数据库属性配置文件
数据库的属性配置文件,把数据库连接信息放在一个单独的文件中,和mybatis主配置文件分开
目的是便于修改,保存,处理多个数据库信息
1.在resource目录中定义一个属性配置文件,例如jdbc.properties
在属性配置文件中,定义数据,格式是kye=value
key:一般用.做多级目录
2.在mybatis的主配置文件中,使用指定文件的位置
在需要使用值得地方,${key}
5.5 typeAliases(类型别名)
<typeAliases>
<!--
第一种方式:
可以指定一个类型一个自定义别名
type:自定义类型的全限定名称
alies:别名(短小,容易记忆)
使用时,resultType直接是别名
-->
<typeAlias type="com.jike.domain.Student" alias="stu"></typeAlias>
<!--
第二种方式:
<package name=""/>,name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)
使用时,resultType直接是类名
-->
<!-- <package name="com.jike.domain"/>-->
</typeAliases>
5.6mappers(映射器)
<mappers>
<mapper resource="com/jike/dao/StudentDao.xml"/>
</mappers>
第一种方式,指定多个mapper文件
第二种:使用包名
name:xml文件(mapper文件)所在的包名
作用:这个包中的所有xml文件一次性都能加载给mybatis
使用package的要求:
1.mapper文件名称需要和接口名称一样,区分大小写的一样
2.mapper问价和dao接口需要在同一目录
<package name=""/>
第六章 扩展
6.1PageHelper
做数据分页的
使用步骤
1.在配置文件中加入PageHelper依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
2.在mybatis文件中加入plugin配置(在数据库连接的环境前面加入)
<!--配置插件plugin-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
3.在Studentdao中定义查询的方法
//使用PageHelper分页数据
List<Student> selectPage();
4.在Studentdao.xml中书写查询语句
<!-- 查询分页数据-->
<select id="selectPage" resultType="stu">
select * from student order by id
</select>
5.进程测试方法
public void selectPage(){
SqlSession session=MyBatisUtils.getSqlSession();
StudentDao dao= session.getMapper(StudentDao.class);
//加入pageHelper的方法,分页
//pageNum:第几页,从1开始
//pageSize:一页中共有多少行数据
PageHelper.startPage(1,2);
List<Student> students= dao.selectPage();
for (Student stu:students
) {
System.out.println("学生为"+stu);
}
}