MyBatis
一、构建Mybatis
1、相关Maven依赖
<!--Mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!--Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!--junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
2、mybatis核心配置文件
<?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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
3、创建mapper接口
moviesMapper.java
package com.chao.LogoDemo.mapper;
public interface moviesMapper {
/*
* Mybatis面向接口有两个一致
* 1.对应的Mapper(映射文件) 配置文件的namespace应该与Mapper的接口文件全类名一致
* 2.对应的Mapper(映射文件) 配置文件的id与Mapper的接口方法名一致
* */
/*
* 添加电影,返回值int为受影响的行数
* */
int insertMovie();
}
4、创建映射文件
moviesMapper.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="com.chao.LogoDemo.mapper.moviesMapper">
<insert id="insertMovie">
insert into Movies values (null,'倚天屠龙记','张无忌',5,200,45,12);
</insert>
</mapper>
5、Mybatis测试
MovieTest.java
package com.chao.LogoTest;
import com.chao.LogoDemo.mapper.moviesMapper;
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;
public class MovieTest {
/*
* 默认不提交事务,在openSession方法里设为true为自动提交事务
* */
@Test
public void mybatisTest() throws IOException {
//加载配置文件
InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory
SqlSessionFactory SqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession = SqlSessionFactory.openSession(true);
//获取Mapper接口对象
moviesMapper mapper = sqlSession.getMapper(moviesMapper.class);
//测试功能
int result = mapper.insertMovie();
//提交事务
// sqlSession.commit();
System.out.println("受影响的行数:" + result);
}
}
6、注意事项
- Mybatis面向接口有两个一致
- 1.对应的Mapper(映射文件) 配置文件的namespace应该与Mapper的接口文件==全类名一致==
- 2.对应的Mapper(映射文件) 配置文件的id与Mapper的==接口方法名一致==
- Mybatis中pojo,Mapper接口,Mapper映射文件都对应Mysql数据库中的一个表
- Mybatis核心配置文件中resource的路径是”/“,不是”.”
- Mybatis测试类中SqlSession默认不提交sql事务,需要在openSession方法参数里设为True,自动提交sql事务
- Mapper映射文件下的查询功能标签必须设置==resultType==或==resultMap==
- resultType:设置默认的映射关系
- resultMap:设置自定义的映射关系(Mysql条目名类型与pojo属性类型不一致时)
二、Mybatis核心配置文件
1、引入properties文件
标签顺序:
properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?
Mybatis-config.xml
<properties resource="jdbc.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/Demo
jdbc.username=chao
jdbc.password=123456
作用:方便修改配置文件中的参数
2、设置类型别名
放在configuration标签内,environments标签前,properties之后,alias默认值为全类名的类名,可以不写
Mybatis-config.xml
<typeAliases>
<!--不常用-->
<typeAlias type="com.chao.pojo" alias="User"></typeAlias>
<!--常用:以包名为单位,将包下所有类型设置默认的类型别名,即类名不区分大小写-->
<package name="com.chao.pojo"/>
</typeAliases>
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="com.chao.mapper.UserMapper">
<select id="selectUser" resultType="User">
select id, MovieName, Protagonist, Score, Duration, Price, Votes
from Movies
where Score = #{arg0}
and Price = '${arg1}';
</select>
</mapper>
作用:在Mybatis映射文件中使用别名替代全类名
3、将_映射为驼峰
<settings>
<setting name="mapUnderscoreToCamelcase" value="true"/>
</settings>
4、设置全局加载模式
- lazyLoadingEnabled:表示延迟加载(需要那个属性就调用此属性对应Sql)
- aggressiveLazyLoading:表示立即加载(不管调用那个属性都会执行两条Sql)
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--默认情况下的是立即加载-->
<!-- <setting name="lazyLoadingEnabled" value="true"/>-->
<!-- <setting name="aggressiveLazyLoading" value="true"/>-->
</settings>
5、以包名为单位引入映射文件
要求:
- mapper接口所在的包要和映射文件所在的包一致
- mapper接口要和映射文件的名字一致
<mappers>
<package name="com.chao.LogoDemo.mapper"/>
</mappers>
三、Mybatis获取参数的两种方式(重点)
1、Mybatis获取数值的两种方式
==${}== 本质是字符串拼接,需要加上单引号,会产生sql注入的问题
==#{}== 本质是占位符赋值
2、Mybatis获取参数值的各种情况
①mappper接口方法的参数为单个的字面量类型
可以通${}和#{}以任意的名称获取参数值,但注意${}的单引号问题
②mapper接口方法的参数有多个字面量
此时,Mybatis会将这些参数放在一个Map集合中,以两种方式进行存储:
- 以arg0,arg1….为键,以参数为值
- 以param1,param2….为键,以参数为值
因此只需要通过#{}和${}以键的方式访问值即可,但是需要注意${}的单引号问题
③mapper接口方法的参数有多个字面量,手动将参数放在Map集合中存储
- 以自定义Map集合中的键为键,以参数为值
mapper接口方法的参数是实体类类型参数
- 以实体类的属性为键,以创建的对象为值
- 注意:实体类构造器形参顺序必须与Mysql表的条目顺序相同
- 以实体类的属性为键,以创建的对象为值
使用@Param注解作为参数
- 以@Param注解中的值为键,以参数为值
- 以param1,param2….为键,以参数为值
四、特殊SQL执行
1、模糊查询
三种方式
<select id="getMovieLike" resultType="movies">
<!-- select * from Movies where MovieName like '%${MovieName}%';-->
<!-- select * from Movies where MovieName like concat('%',#{MovieName},'%');-->
select * from Movies where MovieName like "%"#{MovieName}"%"
</select>
2、批量删除
<delete id="deletMore">
delete from Movies where id in (${ids})
</delete>
3、动态设置表名
<!--List<movies> selectTableMovie(@Param("tableName") String tableName);-->
<select id="selectTableMovie" resultType="movies">
select *
from ${tableName}
</select>
4、添加功能获取自增的主键
<!--
void insertMovies(movies movies);
useGeneratedKeys:设置当前标签中的Sql使用了自增的组件
keyProperty:将自增的主键的值赋值给传输到映射文件中参数的某个属性
-->
<insert id="insertMovies" useGeneratedKeys="true" keyProperty="id">
insert into Movies
values (#{id}, #{MovieName}, #{Protagonist}, #{Score}, #{Duration}, #{Price}, #{Votes})
</insert>
<!--
@Test
public void insertTokey(){
SqlSession sqlSession = SqlSessionUtil.sqlSessionUtil();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
movies movies = new movies(null, "流浪地球", "吴京", 10, 210, 75, 7);
mapper.insertMovies(movies);
System.out.println(movies.getId());
}
-->
五、自定义映射resultMap
1、解决字段名和属性名不一致
为字段名起别名:
<select id="selectAllToTable" resultType="user"> select id,user_name userName,user_password userPassword,name,sex,user_name userName,user_balance userBlance from ${tableName} </select>
设置全局配置,将_自动映射为驼峰
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
通过restultMap映射
<!-- property:映射关系中的属性名,必须是type属性所设置的实体类类型中的属性 column:设置映射关系中的字段名,必须是sql语句查询的所需的字段名 --> <resultMap id="UserResultMap" type="User"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userBalance" column="user_balance"/> </resultMap> <select id="selectAllToTableForResultMap" resultMap="UserResultMap"> select * from ${tableName} </select>
2、处理多对一映射关系
多对一对应对象association,对多对应集合collection
级联属性赋值
在User实体类中创建Movies类型的属性,通过User类中Movies获取Movies类属性
<resultMap id="userAndMovieResultMap" type="User" > <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userBalance" column="user_balance"/> <result property="movies.id" column="id"/> <result property="movies.MovieName" column="MovieName"/> <result property="movies.Protagonist" column="Protagonist"/> <result property="movies.Duration" column="Duration"/> <result property="movies.Score" column="Score"/> <result property="movies.Price" column="Price"/> <result property="movies.Votes" column="Votes"/> </resultMap> <select id="selectAllTable" resultMap="userAndMovieResultMap"> select * from User left join Movies on User.id = Movies.id where User.id = #{id}; </select>
association标签
property:需要处理多对映射关系的属性名
javaType:该属性的实体类类型
<resultMap id="userAndMovieResultMap" type="User" > <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userBalance" column="user_balance"/> <result property="userPhone" column="user_phone"/> <association property="movies" javaType="Movies"> <id property="id" column="id"/> <result property="MovieName" column="MovieName"/> <result property="Protagonist" column="Protagonist"/> <result property="Duration" column="Duration"/> <result property="Score" column="Score"/> <result property="Price" column="Price"/> <result property="Votes" column="Votes"/> </association> </resultMap> <select id="selectAllTable" resultMap="userAndMovieResultMap"> select * from User left join Movies on User.id = Movies.id where User.id = #{id}; </select>
分步查询
property:User类的Movie类型属性
select:设置分布查询的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
column:设置分布查询的条件
fetchType:当开启了全局的延迟加载后,通过以下属性可手动控制延迟加载的效果,此时忽略全局延迟加
- lazy:表示延迟加载(需要那个属性就调用此属性对应Sql)
- eager:表示立即加载(不管调用那个属性都会执行两条Sql)
<resultMap id="userAndMovieByStepResultMap" type="User"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userBalance" column="user_balance"/> <result property="userPhone" column="user_phone"/> <association property="movies" select="com.chao.mapper.UserMapper.selectAllTableResultMapON2" column="id" fetchType="eager"></association> </resultMap> <select id="selectAllTableResultMapON1" resultMap="userAndMovieByStepResultMap"> select * from User where id = #{id} </select> <select id="selectAllTableResultMapON2" resultType="movies"> select * from Movies where id = #{id} </select>
3、处理一对多映射关系
处理一对多查询时,注意多表查询的主键条目名不能一样,否则会覆盖
多对一对应对象association,对多对应集合collection
级联属性赋值
collection:处理一对多的映射关系
ofType:表示该属性对应的集合中存储数据的类型
<select id="selectMovieAndUser" resultMap="getMovieAndUser"> select * from Movies right join User on Movies.eid = User.eid where Movies.eid = #{eid}; </select> <resultMap id="getMovieAndUser" type="Movies"> <id property="id" column="mid"/> <result property="MovieName" column="MovieName"/> <result property="Protagonist" column="Protagonist"/> <result property="Duration" column="Duration"/> <result property="Score" column="Score"/> <result property="Price" column="Price"/> <result property="Votes" column="Votes"/> <collection property="userList" ofType="User"> <id property="id" column="id"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userPhone" column="user_phone"/> <result property="userBalance" column="user_balance"/> </collection>
分布查询
property:User类的Movie类型属性
select:设置分布查询的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
column:设置分布查询的条件
<select id="selectMoviesAndUserByOne" resultMap="getMoviesAndUserByOne"> select * from Movies where eid = #{eid} </select> <resultMap id="getMoviesAndUserByOne" type="Movies"> <id property="id" column="mid"/> <result property="MovieName" column="MovieName"/> <result property="Protagonist" column="Protagonist"/> <result property="Duration" column="Duration"/> <result property="Score" column="Score"/> <result property="Price" column="Price"/> <result property="Votes" column="Votes"/> <association property="userList" select="com.chao.mapper.MovieMapper.selectMoviesAndUserByTwo" column="eid"/> </resultMap> <select id="selectMoviesAndUserByTwo" resultMap="getMoviesAndUserByTwo"> select * from User where eid = #{eid} </select> <resultMap id="getMoviesAndUserByTwo" type="User"> <id property="id" column="id"/> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="userPhone" column="user_phone"/> <result property="userBalance" column="user_balance"/> </resultMap>
六、动态SQL
1、横成立实现动态SQL查询
if:根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到SQL中
<select id="selectUsers" resultType="User">
select * from User where 1=1
<if test="name !=null and name !=''">
and name=#{name}
</if>
<if test="eid !=null and eid!=''">
and eid=#{eid}
</if>
<if test="userBalance !=null and userBalance !=''">
and user_balance=#{userBalance}
</if>
</select>
2、where标签实现动态SQL查询
where:当 where标签中有内容时,会自动生成where关键字,并且将内容前多余的and或or去掉
当where标签中没有内容时,此时where标签没有任何效果
注意:where标签不能将SQL内容后面的and或or去掉
<select id="selectUsers" resultType="User">
select * from User
<where>
<if test="name !=null and name !=''">
and name=#{name}
</if>
<if test="eid !=null and eid!=''">
and eid=#{eid}
</if>
<if test="userBalance !=null and userBalance !=''">
and user_balance=#{userBalance}
</if>
</where>
</select>
3、trim标签实现动态SQL查询
prefix|suffix:将trim标签中内容前或后==添加指定内容==
prefixOverrides|suffixOverrides:如果内容前或后的SQL为空,就将trim标签中内容前或后==去掉指定内容==,反之内容前后存在就不 去掉指定内容
<select id="selectUsers2" resultType="User">
select * from User
<trim prefix="where" suffixOverrides="and">
<if test="name !=null and name !=''">
name=#{name} and
</if>
<if test="eid !=null and eid!=''">
eid=#{eid} and
</if>
<if test="userBalance !=null and userBalance !=''">
user_balance=#{userBalance}
</if>
</trim>
</select>
4、choose标签实现动态SQL查询
when至少有一个,choose可以有多个otherwise最多只能有一个,choose相当于if—else中的if,otherwise相当于else
<select id="selectUsers3" resultType="User">
select * from User
<where>
<choose>
<when test="name !=null and name !='' and eid !=null and eid!=''">
name like '%${name}%' and eid like'%${eid}%'
</when>
<when test="name !=null and name !='' and userBalance !=null and userBalance !=''">
name like '%${name}%' and user_balance like'%${userBalance}%'
</when>
<when test="eid !=null and eid!='' and userBalance !=null and userBalance !=''">
eid like '%${eid}%' and user_balance like'%${userBalance}%'
</when>
<when test="eid !=null and eid!='' and name !=null and name !='' and userBalance !=null and userBalance !=''">
eid like '%${eid}%' and user_balance like'%${userBalance}%' name like '%${name}%'
</when>
<when test="name !=null and name !=''">
name like '%${name}%'
</when>
<when test="eid !=null and eid!=''">
eid like '%${eid}%'
</when>
<when test="userBalance !=null and userBalance !=''">
user_balance like'%${userBalance}%'
</when>
<otherwise>null</otherwise>
</choose>
</where>
5、foreach标签实现动态SQL
collection:需要循环的数组或集合,若为数组的话写成array ,若为集合的话,写成list),若使用了@Param(“uid”)注解,就为注解中内容
item:表示在集合或数组中的每个元素,相当于每遍历一次就把值传各item,要与#{}内的内容保持一致
separator:循环体之间的分隔符
open:循环开始之前的标识符
close:循环结束后的标识符
<!--void deleteUser1( Integer[] id);-->对应接口名称
<delete id="deleteUser1">
delete from User where User.eid in (
<foreach collection="array" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
)
</delete>
<!--相当于sql: delete from User where User.eid in (1,2,3,4,5)-->
<delete id="deleteUser1">
delete from User where
<foreach collection="uid" item="eid" separator="or" >
User.eid = #{eid}
</foreach>
</delete>
<!--相当于sql: delete from User where User.eid=1 or User.eid=2 or User.eid=3 or User.eid=4-->
<!-- int insertUser1(List<User> user);-->
<insert id="insertUser1">
insert into User values
<foreach collection="users" item="user" separator=",">
(id=null,#{user.userName}, #{user.userPassword}, #{user.name},#{user.sex}, #{user.userPhone},
#{user.userBalance},null)
</foreach>
</insert>
6、SQL片段标签
<sql id="updateSet">user_name</sql>
<update id="updateUser1">
update User set <include refid="updateSet"/>='${afterUserName}' where <include refid="updateSet"/>='${beforeUserName}'
</update>
七、Mybatis缓存
1、Mybatis的一级缓存
一级缓存是SqlSession的级别,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
使一级缓存失效的四种情况:
- 不同的SqlSession对应不同的一级缓存
- 同一个SqlSession当时查询条件不同
- 同一个SqlSession两次查询期间执行了任何一次增删改操作
- 同一个SqlSession两次查询期间手动清空了缓存 sqlSession.clearCache( );
2、Mybatis的二级缓存
二级缓存时sqlSessionFactory级别,通过同一个sqlSessionFactory创建的sqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启条件:
- 在核心配置文件中,设置全局配置属性cacheEnabled=”true”,默认为true,不需要设置
- 在映射文件中设置
标签 - 二级缓存只有在SqlSession关闭或提交后才有效
- 查询的数据所转换的实体类类型必须实现序列化的接口 implements Serializable
使二级缓存失效的情况:
- 两次查询之间执行了任意的增删改操作,会使一级缓存和二级缓存同时失效
二级缓存相关配置:
映射文件的
eviction属性:缓存回收策略
- LRU:最近最少使用的,移除最长时间不被使用的对象
- FIFO:先进先出,按对象进入缓存的顺序来移除它们
- SOFT:软引用,移除基于垃圾回收机器状态和软引用规则的对象
- 默认为LRU
flushInterval属性:刷新间隔,单位毫秒
- 默认情况下不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
size属性:引用数目,正整数
- 代表缓存最多可以存储多少个对象,太大容易内存溢出
readOnly属性:只读 true/false
- true:只读缓存,会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改,提供了很好的性能优势
- false:读写缓存,会返回缓存对象的拷贝(通过序列化),这会慢一些,但是安全,因此默认false
7、Mybatis缓存查询顺序
- 先查询二级缓存,因为二级缓存中可能会有其它程序已经查出来的数据,可以直接使用
- 如果二级缓存没有命中,再查询一级缓存
- 如果一级缓存没有命中,则查询数据库
- SqlSession关闭后,一级缓存中的数据会写入二级缓存
8、整合第三方缓存EHCache
依赖导入
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.2</version>
</dependency>
EHCache配置文件,规定固定名称ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"
updateCheck="true" monitoring="autodetect"
dynamicConfig="true">
<!--磁盘保存路 -->
<diskStore path="E:\Project\Intellij\SSM\MyBatis\MyBatisDemo1\Log"/>
<!--maxEntriesLocalHeap:内存中element最大缓存数目
maxElementsOnDisk:磁盘上element的最大缓存数目,若是0则为无穷大
eternal:设置缓存的element是否永远不过期。true->缓存的数据始终有效,false->根据timeToIdleSeconds、timeToLiveSeconds判断
timeToIdleSeconds:当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds规定的时间,这些数据便会被删除,默认值为0,也就是可闲置时间无穷大
overflowToDisk:设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
timeToLiveSeconds:缓存element的有效生命期,默认是0,也就是可以存活时间为无穷大
-->
<defaultCache
maxEntriesLocalHeap="1000"
maxElementsOnDisk="1000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="12"
/>
</ehcache>
八、Mybatis的逆向工程
- 正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的。
- 逆向工程:先创建数据库表,有框架负责根据数据库表,反向生成如下资源
- Java实体类
- Mapper接口
- Mapper映射文件
1、创建逆向工程步骤
a.添加依赖和插件
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
</dependencies>
<build>
<!-- 构建过程中用到的插件 -->
<plugins>
<!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 插件的依赖 -->
<dependencies>
<!-- 逆向工程的核心依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
b.创建Mybatis核心配置文件
c.创建逆向工程的配置文件
文件名必须是:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--
targetRuntime::此属性用于指定生成的代码的运行时环境。
-->
<context id="Mysql" targetRuntime="MyBatis3Simple">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<!-- <property name="suppressDate" value="true" /> <!–是否生成注释代时间戳 –>-->
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://daichao.xyz:26203/Cinema"
userId="chao"
password="@DC642817">
</jdbcConnection>
<!--JavaBean生成策略-->
<javaModelGenerator targetPackage="com.chao.mybatis.pojo" targetProject=".\src\main\java">
<!-- 是否在当前路径下添加子包 -->
<property name="enableSubPackages" value="true"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--映射文件生成策略 -->
<sqlMapGenerator targetPackage="com.chao.mybatis.mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mapper接口生成策略 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.chao.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="Movies" domainObjectName="Movies"/>
<table tableName="User" domainObjectName="User"/>
</context>
</generatorConfiguration>
九、Mybatis分页插件
1、添加依赖
maven导入jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
Mybatis核心配置文件添加插件坐标
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>
2、分页插件的使用
a.在查询之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
pageNum:当前页的页码
pageSize:每页显示的条数
b.在查询获取list集合后,使用PageInfo
list:分页之后的数据
navigatePages:导航分页的页码数
c.分页相关数据
PageInfo{pageNum=2, pageSize=2, size=2, startRow=3, endRow=4, total=13, pages=7, list=Page{count=true, pageNum=2, pageSize=2, startRow=2, endRow=4, total=13, pages=7, reasonable=false, pageSizeZero=false}, prePage=1, nextPage=3, isFirstPage=false, isLastPage=false, hasPreviousPage=true, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=5, navigatepageNums=[1, 2, 3, 4, 5]}
常用数据:
pageNum:当前页的页码
pageSize:每一页显示的条数
size:当前页显示的真实条数
startRow:首行
endRow:尾行
total:总记录数
pages:总页数
prePage:上一页的页码
nextPage:下一页的页码
isFirstPage/isLastPage:是否为第一页/最后一页
hasPreviousPage/hasNextPage:是否为上一页/下一页
navigatePages:导航分页的页码数
navigatepageNums:导航分页的页码,[1,2,3,4,5]
Spring
一、Spring简介
1、Spring概述
官网地址:https://spring.io/
Spring 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用
Spring 框架来创建性能好、易于测试、可重用的代码。
Spring 框架是一个开源的 Java 平台,它最初是由 Rod Johnson 编写的,并且于 2003 年 6 月首
次在 Apache 2.0 许可下发布。
Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。
Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应
用程序是需要扩展的。 Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO
编程模型来促进良好的编程实践。
2、Spring家族
项目列表:https://spring.io/projects
3、Spring Framework
Spring 基础框架,可以视为 Spring 基础设施,基本上任何其他 Spring 项目都是以 Spring Framework
为基础的。
4、Spring Framework特性
非侵入式:使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常小。对领域模型可以做到零污染;对功能 性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这就使得基于 SpringFramework开发应用程序时结构清晰、简洁优雅。
控制反转:IOC——Inversion of Control,翻转资源获取方向。把自己创建资源、向环境索取资源
变成环境将资源准备好,我们享受资源注入。
面向切面编程:AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功
能。
容器:Spring IOC 是一个容器,因为它包含并且管理组件对象的生命周期。组件享受到了容器化
的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发
效率。
组件化:Spring 实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用 XML
和 Java 注解组合这些对象。这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭
建超大型复杂应用系统。
声明式:很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且Spring 旗下的项目已经覆盖了广泛领域, 很多方面的功能性需求可以在 Spring Framework 的基
础上全部使用 Spring 来实现。
5、Spring Framework五大功能模块
功能模块 | 功能介绍 |
---|---|
Core Container | 核心容器,在Spring环境下使用任何功能都必须基于容器IOC容器 |
AOP&Aspects | 面向切面编程 |
Testing | 提供了对junit或TestNG测试框架的整合 |
Data Access/Integration | 提供了对数据访问/集成的功能 |
Spring MVC | 提供了面向Web应用程序的集成功能 |
二、IOC
1、IOC思想
==IOC:Inversion of Control,翻译过来是反转控制。==
①获取资源的传统方式
自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程
中的全部细节且熟练掌握。
在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的
模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效
率。
②反转控制方式获取资源
点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。
反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主
动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源
的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。
③DI
==DI:Dependency Injection,翻译过来是依赖注入。==
DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器
的资源注入。相对于IOC而言,这种表述更直接。
所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。
2、IOC容器在Spring中的实现
Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建
bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:
①BeanFactory
这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
②ApplicationContext
BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用
ApplicationContext 而不是底层的 BeanFactory。
③ApplicationContext的主要实现类
类型名 | 简介 |
---|---|
ClassPathXmlApplicationContext | 通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象 |
FileSystemXmlApplicationContext | 通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象 |
ConfigurableApplicationContext | ApplicationContext 的子接口,包含一些扩展方法refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力 |
WebApplicationContext | 专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中 |
3、基于XML管理bean
3.1创建IOC
①创建Maven Module
②引入依赖
<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
③创建类HelloWorld
public class HelloWorld {
public void sayHello(){
System.out.println("helloworld");
}
}
④创建Spring的配置文件
applicationContext.xml
⑤在Spring的配置文件中配置bean
<!--
配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
通过bean标签配置IOC容器所管理的bean
属性:
id:设置bean的唯一标识
class:设置bean所对应类型的全类名
-->
<bean id="helloworld" class="com.atguigu.spring.bean.HelloWorld"></bean>
⑥创建测试类测试
@Test
public void testHelloWorld(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloworld = (HelloWorld) ac.getBean("helloworld");
helloworld.sayHello();
}
3.2获取bean
①方式一:根据id获取
由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。
上个实验中我们使用的就是这种方式。
②方式二:根据类型获取
@Test
public void testHelloWorld(){
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld bean = ac.getBean(HelloWorld.class);
bean.sayHello();
}
③方式三:根据id和类型
@Test
public void testHelloWorld(){
ApplicationContext ac = new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld bean = ac.getBean("helloworld", HelloWorld.class);
bean.sayHello();
}
④注意
当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个
当IOC容器中一共配置了两个:
<bean id="helloworldOne" class="com.atguigu.spring.bean.HelloWorld"></bean>
<bean id="helloworldTwo" class="com.atguigu.spring.bean.HelloWorld"></bean>
根据类型获取时会抛出异常:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean
of type ‘com.atguigu.spring.bean.HelloWorld’ available: expected single matching bean but
found 2: helloworldOne,helloworldTwo
⑤扩展
如果组件类实现了接口,根据接口类型可以获取 bean 吗?
可以,前提是bean唯一
如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
不行,因为bean不唯一
⑥结论
根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类
型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
3.3依赖注入之setter注入
①创建学生类Student
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
public Student() {
}
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 getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
②配置bean时为属性赋值
<bean id="studentOne" class="com.atguigu.spring.bean.Student">
<!-- property标签:通过组件类的setXxx()方法给组件对象设置属性 -->
<!-- name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关)
-->
<!-- value属性:指定属性值 -->
<property name="id" value="1001"></property>
<property name="name" value="张三"></property>
<property name="age" value="23"></property>
<property name="sex" value="男"></property>
</bean>
③测试
@Test
public void testDIBySet(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
Student studentOne = ac.getBean("studentOne", Student.class);
System.out.println(studentOne);
}
3.4依赖注入之构造器注入
①在上方Student类中添加有参构造
public Student(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
②配置bean
<bean id="studentTwo" class="com.atguigu.spring.bean.Student">
<constructor-arg value="1002"></constructor-arg>
<constructor-arg value="李四"></constructor-arg>
<constructor-arg value="33"></constructor-arg>
<constructor-arg value="女"></constructor-arg>
</bean>
注意:
constructor-arg标签还有两个属性可以进一步描述构造器参数:
- index属性:指定参数所在位置的索引(从0开始)
- name属性:指定参数名
③测试
@Test
public void testDIBySet(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
Student studentOne = ac.getBean("studentTwo", Student.class);
System.out.println(studentOne);
}
3.5特殊值的处理
①字面量赋值
什么是字面量?
int a = 10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a
的时候,我们实际上拿到的值是10。
而如果a是带引号的:’a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面
量。所以字面量没有引申含义,就是我们看到的这个数据本身。
<!-- 使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量 -->
<property name="name" value="张三"/>
②null值
<property name="name">
<null />
</property>
③xml实体
<!-- 小于号在XML文档中用来定义标签的开始,不能随便使用 -->
<!-- 解决方案一:使用XML实体来代替 -->
<property name="expression" value="a < b"/>
④CDATA节
<property name="expression">
<!-- 解决方案二:使用CDATA节 -->
<!-- CDATA中的C代表Character,是文本、字符的含义,CDATA就表示纯文本数据 -->
<!-- XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析 -->
<!-- 所以CDATA节中写什么符号都随意 -->
<value><![CDATA[a < b]]></value>
</property>
3.6为类类型属性赋值
①创建班级类Clazz
public class Clazz {
private Integer clazzId;
private String clazzName;
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
}
②修改Student类
在Student类中添加以下代码:
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
③方式一:引用外部已声明的bean
配置Clazz类型的bean:
<bean id="clazzOne" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="1111"></property>
<property name="clazzName" value="财源滚滚班"></property>
</bean>
为Student中的clazz属性赋值:
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
</bean>
如果错把ref属性写成了value属性,会抛出异常: Caused by: java.lang.IllegalStateException:
Cannot convert value of type ‘java.lang.String’ to required type
‘com.atguigu.spring.bean.Clazz’ for property ‘clazz’: no matching editors or conversion
strategy found
意思是不能把String类型转换成我们要的Clazz类型,说明我们使用value属性时,Spring只把这个
属性看做一个普通的字符串,不会认为这是一个bean的id,更不会根据它去找到bean来赋值
④方式二:内部bean
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<property name="clazz">
<!-- 在一个bean中再声明一个bean就是内部bean -->
<!-- 内部bean只能用于给属性赋值,不能在外部通过IOC容器获取,因此可以省略id属性 -->
<bean id="clazzInner" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="2222"></property>
<property name="clazzName" value="远大前程班"></property>
</bean>
</property>
</bean>
③方式三:级联属性赋值
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- 一定先引用某个bean为属性赋值,才可以使用级联方式更新属性 -->
<property name="clazz" ref="clazzOne"></property>
<property name="clazz.clazzId" value="3333"></property>
<property name="clazz.clazzName" value="最强王者班"></property>
</bean>
3.7为数组类型属性赋值
①修改Student类
在Student类中添加以下代码:
private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
②配置bean
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<value>抽烟</value>
<value>喝酒</value>
<value>烫头</value>
</array>
</property>
</bean>
3.8为集合类型属性赋值
①为List集合类型属性赋值
在Clazz类中添加以下代码:
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
配置bean:
<bean id="clazzTwo" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="4444"></property>
<property name="clazzName" value="Javaee0222"></property>
<property name="students">
<list>
<ref bean="studentOne"></ref>
<ref bean="studentTwo"></ref>
<ref bean="studentThree"></ref>
</list>
</property>
</bean>
若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可
②为Map集合类型属性赋值
创建教师类Teacher:
public class Teacher {
private Integer teacherId;
private String teacherName;
public Integer getTeacherId() {
return teacherId;
}
public void setTeacherId(Integer teacherId) {
this.teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Teacher(Integer teacherId, String teacherName) {
this.teacherId = teacherId;
this.teacherName = teacherName;
}
public Teacher() {
}
@Override
public String toString() {
return "Teacher{" +
"teacherId=" + teacherId +
", teacherName='" + teacherName + '\'' +
'}';
}
}
在Student类中添加以下代码:
private Map<String, Teacher> teacherMap;
public Map<String, Teacher> getTeacherMap() {
return teacherMap;
}
public void setTeacherMap(Map<String, Teacher> teacherMap) {
this.teacherMap = teacherMap;
}
配置bean:
<bean id="teacherOne" class="com.atguigu.spring.bean.Teacher">
<property name="teacherId" value="10010"></property>
<property name="teacherName" value="大宝"></property>
</bean>
<bean id="teacherTwo" class="com.atguigu.spring.bean.Teacher">
<property name="teacherId" value="10086"></property>
<property name="teacherName" value="二宝"></property>
</bean>
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<value>抽烟</value>
<value>喝酒</value>
<value>烫头</value>
</array>
</property>
<property name="teacherMap">
<map>
<entry>
<key>
<value>10010</value>
</key>
<ref bean="teacherOne"></ref>
</entry>
<entry key="10086" value-ref="teacherTwo"></entry>
</map>
</property>
</bean>
③引用集合类型的bean
<!--list集合类型的bean-->
<util:list id="students">
<ref bean="studentOne"></ref>
<ref bean="studentTwo"></ref>
<ref bean="studentThree"></ref>
</util:list>
<!--map集合类型的bean-->
<util:map id="teacherMap">
<entry key="10010" value-ref="teacherOne"/>
<entry key="10086" value-ref="teacherTwo"/>
</util:map>
<bean id="clazzTwo" class="com.atguigu.spring.bean.Clazz">
<property name="clazzId" value="4444"></property>
<property name="clazzName" value="Javaee0222"></property>
<property name="students" ref="students"></property>
</bean>
<bean id="studentFour" class="com.atguigu.spring.bean.Student">
<property name="id" value="1004"></property>
<property name="name" value="赵六"></property>
<property name="age" value="26"></property>
<property name="sex" value="女"></property>
<!-- ref属性:引用IOC容器中某个bean的id,将所对应的bean为属性赋值 -->
<property name="clazz" ref="clazzOne"></property>
<property name="hobbies">
<array>
<value>抽烟</value>
<value>喝酒</value>
<value>烫头</value>
</array>
</property>
<property name="teacherMap" ref="teacherMap"></property>
</bean>
使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择
3.9p命名空间
引入p命名空间后,可以通过以下方式为bean的各个属性赋值
<bean id="studentSix" class="com.atguigu.spring.bean.Student"
p:id="1006" p:name="小明" p:clazz-ref="clazzOne" p:teacherMap-ref="teacherMap">
</bean>
3.10引入外部属性文件
①加入依赖
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
②创建外部属性文件
jdbc.user=root
jdbc.password=atguigu
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
③引入属性文件
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
④配置bean
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
⑤测试
@Test
public void testDataSource() throws SQLException {
ApplicationContext ac = new ClassPathXmlApplicationContext("springdatasource.xml");
DataSource dataSource = ac.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
3.11bean的作用域
①概念
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:
取值 | 含义 | 创建对象的时机 |
---|---|---|
singleton(默认) | 在IOC容器中,这个bean的对象始终为单实例 | IOC容器初始化时 |
prototype | 这个bean在IOC容器中有多个实例 | 获取bean时 |
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
取值 | 含义 |
---|---|
request | 在一个请求范围内有效 |
session | 在一个会话范围内有效 |
②创建类User
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
③配置bean
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建
对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean class="com.atguigu.bean.User" scope="prototype"></bean>
④测试
@Test
public void testBeanScope(){
ApplicationContext ac = new ClassPathXmlApplicationContext("springscope.xml");
User user1 = ac.getBean(User.class);
User user2 = ac.getBean(User.class);
System.out.println(user1==user2);
}
3.12bean的生命周期
①具体的生命周期过程
- bean对象创建(调用无参构造器)
- 给bean对象设置属性
- bean对象初始化之前操作(由bean的后置处理器负责)
- bean对象初始化(需在配置bean时指定初始化方法)
- bean对象初始化之后操作(由bean的后置处理器负责)
- bean对象就绪可以使用
- bean对象销毁(需在配置bean时指定销毁方法)
- IOC容器关闭
②修改类User
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
System.out.println("生命周期:1、创建对象");
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
System.out.println("生命周期:2、依赖注入");
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void initMethod(){
System.out.println("生命周期:3、初始化");
}
public void destroyMethod(){
System.out.println("生命周期:5、销毁");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
注意其中的initMethod()和destroyMethod(),可以通过配置bean指定为初始化和销毁的方法
③配置bean
<!-- 使用init-method属性指定初始化方法 -->
<!-- 使用destroy-method属性指定销毁方法 -->
<bean class="com.atguigu.bean.User" scope="prototype" init-method="initMethod"
destroy-method="destroyMethod">
<property name="id" value="1001"></property>
<property name="username" value="admin"></property>
<property name="password" value="123456"></property>
<property name="age" value="23"></property>
</bean>
④测试
@Test
public void testLife(){
ClassPathXmlApplicationContext ac = new
ClassPathXmlApplicationContext("spring-lifecycle.xml");
User bean = ac.getBean(User.class);
System.out.println("生命周期:4、通过IOC容器获取bean并使用");
ac.close();
}
⑤bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
创建bean的后置处理器:
package com.atguigu.spring.process;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("☆☆☆" + beanName + " = " + bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("★★★" + beanName + " = " + bean);
return bean;
}
}
在IOC容器中配置后置处理器:
<!-- bean的后置处理器要放入IOC容器才能生效 -->
<bean id="myBeanProcessor" class="com.atguigu.spring.process.MyBeanProcessor"/>