【Java】MyBatis学习笔记——约定大于配置

前言

MyBatis主要用于持久层,就是负责和数据库进行直接交互的部分,主要学习的核心内容就是sql语句的拼接。约定大于配置。 复习Mybatis自己做记录。



一、配置文件法

1.mybatis.xml文件

配置信息的顺序必须严格遵循下图
mybatis-config.xml文件规范

①属性配置——properties

内部先加载,外部的后来居上,覆盖前者。

<properties resource="db.properties">	
	<propertie name="jdbc.name" value="name"/>
</properties>

②设置配置——settings

<settings>
	<!--一级缓存(默认开启)-->
	<setting name="cacheEnabled" value="true">
	<!--日志配置-->
    <setting name="logImpl" value="LOG4J"/>
</settings>

③别名配置——typeAliases

别名在配置文件中用,配置好后不用写全限定类名。

  • 扫描一个类
<typeAliases>
	<typeAlias aliase="User" type="com.xxx.pojo.User">
</typeAliases>
  • 扫描一个包:根据set方法获取类名,别名为小写
<typeAliases>
	<typeAlias package="com.xxx.pojo">
</typeAliases>

④数据库配置——environments(ssm框架中交给Spring)

<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:3310/javaweb?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        </dataSource>
    </environment>
</environments>

⑤映射器配置——mappers

  • 映射mapper文件
<mappers>
    <mapper resource="com/study/dao/UserMapper.xml"/>
</mappers>
  • 映射全限定类名——Mapper接口和配置文件同包
<mappers>
	<mapper class="com.dao.UserMapper">
</mappers>
  • 映射一个包内——Mapper接口和配置文件同包
<mappers>
	<package name="com.dao"/>
</mappers>

2.Mybatis工具类

Mybatis中有下面三个非常重要的概念:

  • SqlSessionFactoryBuilder:创建SqlSessionFactory后释放(局部变量)
  • SqlSessionFactory:运行期间一直存在(单例模式/静态单例)连接池
  • SqlSession:收到http请求就打开一个Sqlsession,返回响应后就关闭(方法作用域)连接请求
public class MybatisUtils{
	//提升作用域
	private static SqlSessionFactory sqlSessionFactory;
	static{
		try{
			//使用Mybatis获取SqlSessionFactory对象
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resource.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		}catch(IOException e){
			e,printStackTrace();
		}
	}
	
	public static SqlSession getSqlSqlSession(){
		//true:自动提交事务 ~ sqlSession.commit()
		return sqlSessionFactory.openSession(true);
	}
}

3.xxxMapper.xml

<!--绑定Mapper接口-->
<mapper namespace="com.dao.xxxMapper">
	<!--
		id:方法名
		patameterType:参数类
		resultType:结果类
	-->
	<select id="getUserById" parameterType="int" resultType="User">
		select * from user where id = #{id}
	</select>
</mapper>

4.实现方法

@Test
public void userTest(){
	SqlSession sqlSession = MybatisUtils.getSession();
	//通过sqlSession的getMapper方法获取Dao类,用于调用方法
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
	User user = mapper.getUserById(1);

	//关闭sqlSession
	sqlSession.close();
}

二、注解法

1.别名

①实体类起别名——@Alias

@Alias("User")
public class User{...}

②属性起别名——@Param

int test(@Param("user_id") int id)

2.CRUD——xxxMapper接口文件

①查——@Select

@Select("select * from user where id = #{id}")
User getUser(@Param("id") int id)

②增——@Insert

@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{pwd})")
int insertUser(User user)

③改——@Update

@Update("update user set name=#{name}" where id = #{id})
int updateUser(User user)

④删——@Delete

@Delete("delete from user where id = #{id}")
int deleteUser(int id)

三、参数和结果集

1.参数——parameterType

  • 直接传参
  • 对象传参
  • 一个基本参数,可以省略
  • 多个参数,用Map/注解

万能Map传参

//Mapper接口
int addUser(Map<String,Object> map);
//测试方法
Map<String,Object> map = new HashMap<String,Object>();
map.put("key","value");
mapper.addUser(map);

2.结果集映射——resultMap

<select id="getUser" resultMap="UserMap">
	select * from user
</select>
<resultMap id="UserMap" type="User">
	<result property="实体字段" column="数据库字段">
</resultMap>

四、动态SQL

1.SQL复用

打包

<sql id="xxx">
	sql语句
</sql>

引用

<include refid="xxx"></include>

2.标签

  • if标签
<select>
	select * from user
	<if test="id!=null">
		and id=#{id}
	</if>
</select>
  • choose(when,otherwise)
<choose>
	<when test="xx!=null">xxx</when>
	<when test="xx!=null">xxx</when>
	<otherwise>xxx</otherwise>
</choose>
  • trim->where,set

trim:

属性意义
prefix前缀
suffix后缀
prefixOverrides前缀覆盖
suffixOverrides后缀覆盖

where:智能去除where和and,or等前缀

<select>
	select * from user
	<where>
		<if test="#{name}!=null">name=#{name}</if>
		<if test="#{sex}!=null">and sex=#{sex}</if>
	</where>
</select>
<trim prefix="where" prefixOverrids="and|or">
	xxx
</trim>

set:智能去除set和逗号后缀

<trim prefix="set" suffixOverrides=",">
  • foreach:遍历集合,拼接sql语句
<!--select * from user where 1=1 and (id=1 or id=2 or id=3)-->
<select paramType="map">
	select * from user
	<where>
		<!--
			collection:map传的集合
			open:拼接的开头
			close:拼接的结尾
			seprator:中间的分割
		-->
		<foreach collection="ids" item=id open="(" close=")" seprator="or">
			id=#{id}
		</foreach>
	</where>
</select>

五、复杂查询

1.多对一:关联——association

方法一:子查询

<select id="getStudent" resultMap="StudentTeacher">
	select * from student
</select>
<resultMap id="StudentTeacher" resulType="Student">
	 <result property="id" column="id"/>
	 <result property="name" column="name"/>
	 <association property="teacher" column="tid" javaType="Teacher" select="getTeacher" />
</resultMap>
<select id="getTeacher" resultType="Teacher">
	select * from teacher where id = #{id}
</select>

方法二:按照结果嵌套查询

<select id="getStudent" resultMap="StudentTeacher">
	select s.sid,s.sname,t.tname
	from student s,teacher t
	where s.sid=t.tid
</select>
<resultMap id="StudentTeacher">
	<result property="id" column="sid"/>
	<result property="name" column="sname"/>
	<association id="teacher" javaType="Teacher">
		<result property="id" column="tid"/>
		<result property="name" column="tname"/>
	</association>
</resultMap>

2.一对多:集合——collection

两个方法同上

<!--
	ofType:集合里对象的类
-->
<collection property=students javaType="ArrayList" ofType="Student" />

六、缓存

减少与数据库的交互,减小开销,提高效率
经常查询但是不怎么修改的数据

1.一级缓存(默认开启LRU)

sqlSession中有效
缓存失效:

  • ①查询不同东西
  • ②增删改,缓存会刷新
  • ③查询不同Mapper.xml
  • ④手动清理缓存 sqlSession,clearCache();

2.二级缓存(注解sql不会二级缓存)

会话提交/关闭时,一级缓存数据提交到二级缓存中。

  • 全局
<cache/>
  • 单独设置
<select userCache="true"></select>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值