- 一、入门
- 1.什么是Mybatis?
- 2.MyBatis开发步骤
- 3.MyBatis的映射文件概述
- 4. 标签
- (1)environments标签
- (2)mapper标签
- (3)Properties标签
- (4)typeAliases标签
- (5)typeHandlers标签
- (5)plugins标签
- 5.代理开发方式介绍
- 6.MyBatis映射文件深入
- 二、多表查询
- 1.没有注解
- (1)一对一查询
- (2)一对多查询
- (3)多对多查询
- 2.注解
- (1)一对一查询
- (2)一对多查询
- (3)多对多查询
- 三、demo执行步骤
- 1.进行环境的搭建
- 2.数据库表的创建
- 3.实体类的创建
- 4.选择注解配置或者xml文件配置
- (1)xml文件配置
- (2)注解配置
- 总结
一、入门 1.什么是Mybatis?
2.MyBatis开发步骤mybatis 是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
- 添加MyBatis的坐标
- 创建user数据表
- 编写User实体类
- 编写映射文件UserMapper.xml
- 编写核心文件SqlMapConfig.xml
- 编写测试类
举例
- 环境搭建
- 导入MyBatis的坐标和其他相关坐标
- 创建user数据表
- 编写User实体
- 编写UserMapper映射文件
- 编写MyBatis核心文件
- 编写测试代码
导入MyBatis的坐标和其他相关坐标
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.12version>
dependency>
编写UserMapper映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.itheima.domain.User">
select * from User
select>
mapper>
编写MyBatis核心文件
<configuration>
<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:///test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"/>
mappers>
configuration>
3.MyBatis的映射文件概述
mybatis事务默认不提交,跟jdbc不一样!!!!需加一句:sqlSession.commit() !!!
- 事务管理器(transactionManager)类型有两种
- JDBC
- MANAGED
- 数据源(dataSource)类型有三种
- UNPOOLED
- POOLED
- JNDI
该标签的作用是加载映射的,加载方式有如下几种
- 使用相对于类路径的资源引用:
- 使用完全限定资源定位符(URL):
- 使用映射器接口实现类的完全限定类名:
- 将包内的映射器接口实现全部注册为映射器:
自定义别名
注意它的存放顺序
开发步骤:
- 定义转换类继承类BaseTypeHandler
- 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
public class MyDateTypeHandler extends BaseTypeHandler<Date> {
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) {
preparedStatement.setString(i,date.getTime()+"");
}
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}
- 在MyBatis核心配置文件中进行注册
<typeHandlers>
<typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler">typeHandler>
typeHandlers>
(5)plugins标签
开发步骤:
- 导入通用PageHelper坐标
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>3.7.5version>
dependency>
<dependency>
<groupId>com.github.jsqlparsergroupId>
<artifactId>jsqlparserartifactId>
<version>0.9.1version>
dependency>
- 在mybatis核心配置文件中配置PageHelper插件
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
plugin>
- 测试分页代码实现
@Test
public void testPageHelper(){
//设置分页参数
PageHelper.startPage(1,2);
List<User> select = userMapper2.select(null);
for(User user : select){
System.out.println(user);
}
}
获得分页相关的其他参数
//其他分页的数据
PageInfo<User> pageInfo = new PageInfo<User>(select);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页:"+pageInfo.getPageNum());
System.out.println("每页显示长度:"+pageInfo.getPageSize());
System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
5.代理开发方式介绍
Mapper 接口开发需要遵循以下规范:
- Mapper.xml文件中的namespace与mapper接口的全限定名相同
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
- Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
编写UserMapper接口
动态sql语句
- 动态 SQL 之
<select id="findByCondition" parameterType="user" resultType="user">
select * from User
<where>
<if test="id!=0">
and id=#{id}
if>
<if test="username!=null">
and username=#{username}
if>
where>
select>
- 动态 SQL 之
- foreach标签的属性含义如下
- collection:代表要遍历的集合元素,注意编写时不要写#{}
- open:代表语句的开始部分
- close:代表结束部分
- item:代表遍历集合的每个元素,生成的变量名
- sperator:代表分隔符
- foreach标签的属性含义如下
例如:SELECT * FROM USER WHERE id IN (1,2,5)。
<select id="findByIds" parameterType="list" resultType="user">
select * from User
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
SQL片段抽取
sql>
<select id="findById" parameterType="int" resultType="user">
<include refid="selectUser">include> where id=#{id}
select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser">include>
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
二、多表查询
1.没有注解
(1)一对一查询
- 一对一查询的语句:select * from orders o,user u where o.uid=u.id;
- 配置OrderMapper.xml
<resultMap id="orderMap" type="com.itheima.domain.Order">
<result property="id" column="id">result>
<result property="ordertime" column="ordertime">result>
<result property="total" column="total">result>
<association property="user" javaType="com.itheima.domain.User">
<result column="uid" property="id">result>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
association>
resultMap>
(2)一对多查询
- 一对多查询的语句:select *,o.id oid from user u left join orders o on u.id=o.uid;
- 配置UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
<resultMap id="userMap" type="com.itheima.domain.User">
<result column="id" property="id">result>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
<collection property="orderList" ofType="com.itheima.domain.Order">
<result column="oid" property="id">result>
<result column="ordertime" property="ordertime">result>
<result column="total" property="total">result>
collection>
resultMap>
<select id="findAll" resultMap="userMap">
select *,o.id oid from user u left join orders o on u.id=o.uid
select>
mapper>
(3)多对多查询
- 多对多查询的语句:select u.,r.,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id;
- 配置UserMapper.xml
<resultMap id="userRoleMap" type="com.itheima.domain.User">
<result column="id" property="id">result>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
<collection property="roleList" ofType="com.itheima.domain.Role">
<result column="rid" property="id">result>
<result column="rolename" property="rolename">result>
collection>
resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap">
select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id
inner join role r on ur.role_id=r.id
select>
2.注解
MyBatis的常用注解 :
- @Insert:实现新增
- @Update:实现更新
- @Delete:实现删除
- @Select:实现查询
- @Result:实现结果集封装
- @Results:可以与@Result 一起使用,封装多个结果集
- @One:实现一对一结果集封装
- @Many:实现一对多结果集封装
- 一对一查询的语句
select * from orders;
select * from user where id=查询出订单的uid;
- 使用注解配置Mapper
public interface OrderMapper {
@Select("select * from orders")
@Results({
@Result(id=true,property = "id",column = "id"),
@Result(property = "ordertime",column = "ordertime"),
@Result(property = "total",column = "total"),
@Result(property = "user",column = "uid",
javaType = User.class,
one = @One(select = "com.itheima.mapper.UserMapper.findById"))
})
List<Order> findAll();
}
public interface UserMapper {
@Select("select * from user where id=#{id}")
User findById(int id);
}
(2)一对多查询
- 一对多查询的语句
select * from user;
select * from orders where uid=查询出用户的id;
- 使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "orderList",column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid"))
})
List<User> findAllUserAndOrder();
}
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
List<Order> findByUid(int uid);
}
(3)多对多查询
- 多对多查询的语句
select * from user;
select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=用户的id
- 使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "roleList",column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();}
public interface RoleMapper {
@Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
List<Role> findByUid(int uid);
}
三、demo执行步骤
1.进行环境的搭建
数据库文件的配置
编写核心文件
就不需要上述的xml配置文件,只需要在接口文件上进行注解配置
但是在核心文件中要进行映射关系的配置
下面的案例事一对一案例
总结
MyBatis多表配置方式
- 一对一配置:使用
做配置 - 一对多配置:使用
做配置+ - 多对多配置:使用
做配置+
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)