Mybatis(三)——多表操作

1.连接池

Mybatis连接池提供了三种方式配置。
**配置的位置:**主配置文件SqlMapConfig.xml的dataSource标签,里面的type属性就是表示采用何种连接池方式。
Type属性的取值:

  • POOLED:采用传统的javax.sql.DataSource规范中的连接池,mybatis有针对的实现。
  • UNPOOLED:采用传统的获取连接的方式,虽然也实现javax.sql.DataScource接口,但并没有使用“池”的思想。
  • JNDI:采用服务器提供的JNDI技术实现,来获取DataScource对象。注意:如果不是web或者Maven的war工程,使用能使用的

POOLED的关键操作:原链接
在这里插入图片描述
UNPOOLED的关键操作:原链接
在这里插入图片描述

2.事务控制

设置事务自动提交,使用方法:

SqlSession sqlsession = sqlSessionFactory.openSession(true);//自动提交事务为true;

3.基于xml配置的动态sql语句使用

3.1 if标签

可以加多个

<!--    根据条件查询-->
    <select id="findUserByCondition" resultType="domain.User" parameterType="domain.User">
        select * from User where 1 = 1
        <if test="username != null">
            and username = #{username}
        </if>
    </select>

where标签

<!--    根据条件查询-->
    <select id="findUserByCondition" resultType="domain.User" parameterType="domain.User">
        select * from User
        <where>
	        <if test="username != null">
	            and username = #{username}
	        </if>
        </where>
    </select>

foreach 标签

<!--    根据queryvo中的id集合实现查询用户列表-->
    <select id="findUserInIds" resultType="domain.User" parameterType="domain.QueryVo"><!-- QueryVo实体类中定义ids属性,用来存放id列表 -->
        select * from User
        <where>
            <if test="ids != null and ids.size() > 0">
                <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

抽取重复sql语句

<!-- 定义-->
    <sql id="defaultUser">
        select * from User
    </sql>
<!-- 使用-->
    <select id="findAll" resultType="domain.User">
        <include refid="defaultUser"></include>
    </select>

4 多表操作

有如下两个表:

  • user:
    在这里插入图片描述
  • account:
    在这里插入图片描述

4.1 多对一

多个账户可以对应一个用户,是多对一的关系,mybatis把多对一看做一对一。

  • 一种方法:定义子类继承主表对应的实体类,子类添加从表中需要的属性。
public class AccountUser extends account{
    private String username;
    private String address;
	//get/set方法及toString()方法
}
<!--查询所有及用户信息-->
    <select id="findAllAndUser" resultType="domain.AccountUser">
        select a.*,u.username,u.address from account a,user u where a.uid = u.id;
    </select>
  • 另一种方法:主表对应的实体类中添加从表对应的实体类属性,使用resultMap标签给实体类赋值
<!--    定义封装account和user的resultMap-->
    <resultMap id="accountUserMap" type="domain.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="domain.User">
            <id property="id" column="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </association>
    </resultMap>
<!--    查询所有-->
    <select id="findAll" resultMap="accountUserMap">
        select u.*,a.id as aid,a.uid,a.money from account a,user u where u.id = a.uid;
    </select>
//一对多,一对一,从表应该包含一个主表的实体的对象引用
    private User user;

4.2 一对多

一个用户对应多个账户。

主表对应实体类:

    //一对多关系映射,主表实体类应该包含从表实体类的集合引用
    private List<account> accounts;

配置文件:

<!--    定义User的resultMap-->
    <resultMap id="userAccountMap" type="domain.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对象中account集合的映射 ofType:集合中元素的类型-->
        <collection property="accounts" ofType="domain.account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userAccountMap">
        select * from user u left outer join account a on u.id = a.uid;
    </select>

4.3 多对多

多对多:一个用户可以有多个角色,一个角色可以用于多个用户。
多对多关系需要中间表,中间表有各自表的主键。操作和一对多相同,这里只展示一个用户对多个角色。

  • 需要的三个表结构:

在这里插入图片描述

  • 用户实体类中的角色列表:
    //多对多的关系映射
    private List<Role> roles;
  • 配置文件:
    <resultMap id="findAllRole" type="domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <result property="birthday" column="birthday"></result>
        <collection property="roles" ofType="domain.Role">
            <id property="roleId" column="rid"></id>
            <result property="roleName" column="role_name"></result>
            <result property="roleDesc" column="role_desc"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="findAllRole">
<!--        select * from user u left outer join account a on u.id = a.uid;-->
        select u.*,r.id as rid,r.role_name,r.role_desc from user u left outer join user_role ur on u.id = ur.uid
         left outer join role r on r.id = ur.rid;
    </select>
  • 测试类:
    @Test
    public void tsetFindAll() {
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users) {
            System.out.println("--------------");
            System.out.println(user);
            System.out.println(user.getRoles());
        }
    }
  • 结果:
    在这里插入图片描述

补充:JNDI

JNDI(java naming directory interface,Java命名和目录接口),用来模拟windows的注册表(key【路径+名称】-value【数据】),从而实现通过容器连接数据库

  • 创建Maven工程,选择创建maven-webapp工程。

  • 创建如下目录结构(和之前的目录结构相同):

在这里插入图片描述

  • 添加依赖,在之前依赖的基础上添加servlet和jsp依赖
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
  • context.xml文件中的内容:
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
    <Resource
        name="jdbc/testmybatis"
        type="javax.sql.DataSource"
        auth="Container"
        maxActive="20"
        maxWait="10000"
        maxIdle="5"
        username="root"
        password="root"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/testmybatis"
    />
</Context>
  • 在SqlMapConfig.xml中修改数据源:
<!--            配置连接数据库必备信息,type属性表示是否使用数据源(连接池)-->
            <dataSource type="JNDI">
<!--                java:comp/env/...是路径,固定的,不能修改-->
                <property name="data_source" value="java:comp/env/jdbc/testmybatis"/>
            </dataSource>
  • 在服务器(tomcat)上运行(因为要经过tomcat,所以无法使用test方法)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值