mybatis
2019-11-10 11:11:17 0 举报
AI智能生成
mybatis
作者其他创作
大纲/内容
概述
基于持久层的框架内部封装了jdbc,使开发者只关注sql语句本身,而不需要花费精力去处理加载驱动,创建连接,创建statement等复杂的过程,通过xml或者注解的方式,将要执行的各种statement配置起来,由框架执行sql将结果映射为Java并且返回
创建
file->new->project->maven->next
mybatis环境搭建
1.导入pom.xml依赖:mybatis,mysql,log4j日志,junit测试
2.创建实体类和dao的接口
3.创建mybatis的主配置文件 SqlMapConfig.xml
4.创建映射配置文件
注意事项:
1.创建目录和创建包是不一样的,目录是一级结构,包是三级结构
2.mabatis的映射配置文件必须和dao接口的包结构相同
3.映射配置文件的mapper标签的namespace属性的值必须是dao接口的全限定类名
4.映射配置文件的操作配置select,id属性的取值必须是dao接口的方法名
创建测试类
读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml")
创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
创建SqlSession对象
SqlSession session = factory.openSession();
创建Dao接口的代理对象
UserDao userDao = session.getMapper(UserDao.class);
执行dao中的方法
List<User> users = userDao.findAll();
for (User user : users){
System.out.println(user);
}
释放资源
session.close();
in.close();
使用注解
步骤
1.删除UserDao.xml
2.在dao接口的方法上添加注解,并指定sql语句
@Select(“select*from user”)
3.配置文件SqlMapConfig.xml中的mapper标签下的class属性指定被注解全限定类名。
<mapper class="com.ssm.dao.UserDao"></mapper>
多表查询
分支主题
动态的sql语句
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex=#{userSex}
</if>
</where>
一对多
主表实体包含从表实体的集合引用
<mapper namespace="com.ssm.dao.UserDao">
<!-- 定义User的resultMap -->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!-- 配置User对象中accounts集合的映射
ofType:集合中元素的类别-->
<collection property="accounts" ofType="account">
<!-- property:实体类中属性的名称,column:别名 -->
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
多对一
一对一
从account中包含一个user实体引用
Accountdao.xml封装user对象
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射,配置封装 user 的内容 -->
<association property="user" column="uid" javaType="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
</association>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="accountUserMap">
select * from account a,user u where u.id=a.uid;
</select>
多对多
增删改查
xml
查找所有
持久层(xxx.java)
List<User> findAll();
xxx.xml
<select id="findAll" resultType="com.ssm.domain.User">
select * from user
</select>
增加用户
持久层(xxx.java)
void saveUser(User user);
xxx.xml
<insert id="saveUser" parameterType="com.ssm.domain.User">
insert into user(username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address});
</insert>
删除用户
持久层(xxx.java)
void deleteUser(Integer userId);
xxx.xml
<delete id="deleteUser" parameterType="Integer">
delete from user where id=#{uid}
</delete>
根据id查询
持久层(xxx.java)
User findById(Integer userId);
xxx.xml
<select id="findById" parameterType="int" resultType="com.ssm.domain.User">
select * from user where id=#{uid}
</select>
根据名字的模糊查询
持久层(xxx.java)
List<User> findByName(String userName);
xxx.xml
<select id="findByName" parameterType="String" resultType="com.ssm.domain.User">
<!--select * from user where username like #{name}; -->
select * from user where username like '%${value}%'
</select>
更新用户
持久层(xxx.java)
void updateUser(User user);
xxx.xml
<update id="updateUser" parameterType="com.ssm.domain.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
每个参数的意义
resultType 属性:用于指定结果集的类型。
parameterType 属性:用于指定传入参数的类型。
sql 语句中使用#{}字符:它代表占位符,相当于原来 jdbc 部分所学的?,都是用于执行语句时替换实际的数据。具体的数据是由#{}里面的内容决定的。
{}中内容的写法:由于数据类型是基本类型,所以此处可以随意写。
注解
查找所有
@Select("select * from user")
增加用户
@Insert()
删除用户
@Delete
更新用户
@Update
根据名字的模糊查询
JdbcConfig.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_heima
jdbc.username=root
jdbc.password=123456
SqlMapConfig
<?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>
<!-- 引入外部配置文件 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置别名 -->
<typeAliases>
<package name="com.ssm.domain"/>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<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>
<!-- 引入带有注解的dao接口所在位置 -->
<mappers>
<package name="com.ssm.dao"/>
</mappers>
</configuration>
@Results(id="accountMap",value = {
@Result(id=true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid",one=@One(select="com.ssm.dao.UserDao.findById",fetchType= FetchType.EAGER ))
})
xxx.xml
如果数据库的变量名和代码中的变量名不一样
<!-- 配置 查询结果的列名 和 实体类的属性名 的对应关系 -->
<resultMap id="userMap" type="com.ssm.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!-- 非主键字段的对应 -->
<result property="userName" column="username"></result>
<result property="userBirthday" column="birthday"></result>
<result property="userSex" column="sex"></result>
<result property="userAddress" column="address"></result>
</resultMap>
以insert为例子:insert into user(username,birthday,sex,address) values (#{userName},#{userBirthday},#{userSex},#{userAddress});
</insert>
mybatis配置
在SqlConfig.xml中配置<properties>标签
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_heima"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_heima
jdbc.username=root
jdbc.password=123456
<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>
配置映射文件
<mappers>
<!-- 配置映射文件的位置 -->
<mappers>
<!-- <mapper resource="com/ssm/dao/UserDao.xml"></mapper>-->
<!-- package标签用于指定dao接口所在的包,指定完成之后就不需再写mapper以及resources或者class(注解)了 -->
<package name="com.ssm.dao"/>
</mappers>
缓存
立即加载(多对一,一对一)
延迟加载(一对多、多对多)
<!-- 配置参数 -->
<settings>
<!-- 开启 mybatis 支持延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 允许触发方法进行立即加载,否则按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
一级缓存
一级缓存是 SqlSession 范围的缓存,当调用 SqlSession 的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。
二级缓存
二级缓存:它指的是 mybatis 中 SqlSessionFactory 对象的缓存。由同一个 SqlSessionFactory 对象创建的 SqlSession 共享其缓存
SqlMapConfig
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
UserDao.java
@CacheNamespace(blocking = true)
public interface UserDao {
0 条评论
下一页