mybatis的表关系实现

mybatis的表关系实现


SqlMapConfig.xml

<?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-->
    <properties resource="jdbcConfig.properties"></properties>

    <!--使用typeAliases配置别名,它只能配置domain中类的别名 -->
    <typeAliases>
        <package name="com.fjut.domain"></package>
    </typeAliases>

    <!--配置环境-->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务 -->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件的位置 -->
    <mappers>
        <package name="com.fjut.dao"></package>
    </mappers>
</configuration>

一、一对一实体类关系例子(一个账户对应一个用户)

步骤一:建数据库表。

让账户表关联用户表。(外键形式)

步骤二:写出对应的实体类。

注意:要体现一对一关系,就要在账户实体类中配置用户属性(即private User user;),并生成get和set方法。

步骤三:建立对应的映射配置文件

账户映射配置文件如下:

<?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.fjut.dao.IAccountDao">
    <!--一对一的表关系的resultMap-->
    <resultMap id="accountUserMap" type="account">      <!--type是指返回结果类型(即封装到哪)-->
        <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="sex" column="sex"></result>
            <result property="address" column="address"></result>
            <result property="birthday" column="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>
</mapper>

注意:用户的映射配置文件可以不用。(在测试账户一对一用户的测试下。)

步骤四:测试

package com.fjut.test;

import com.fjut.dao.IAccountDao;
import com.fjut.domain.Account;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class AccountTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao accountDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
        accountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        // sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        List<Account> accounts = accountDao.findAll();
        for(Account account : accounts){
            System.out.println("--------每个account的信息------------");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }
}

结果:
在这里插入图片描述

二、一对多实体类例子(一个用户有多个账户)

步骤一:建数据库表。

让账户表关联用户表。(外键形式)

步骤二:写出对应的实体类。

注意:要体现一对多的关系。即就要在用户实体类中定义多个账户的属性(private List<Account> accounts;),并生成get和set方法。

步骤三:建立对应的映射配置文件

用户映射配置文件代码如下:

<?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.fjut.dao.IUserDao">

    <!-- 定义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集合的映射 -->
        <collection property="accounts" ofType="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 u.*,a.id as aid,a.uid,a.money from user u left outer join account a on u.id = a.uid
    </select>
    
</mapper>

步骤四:测试

@Test
    public void testFindAll(){
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println("-----每个用户的信息------");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

结果:
在这里插入图片描述

三、多对多实体类例子(一个用户有多个角色,一个角色有多个用户)

步骤一:建数据库表。

让用户表和角色表具有多对多的关系。
      做法:创建一个中间表,中间表中包含各自的主键,在中间表中是外键。

步骤二:写出对应的实体类。

让用户和角色的实体类能体现处理多对多的关系
      做法:各自的实体类中各自包含对方的一个集合属性(即:private List<Role> roles;和private List<User> users;),并生成get和set方法。

步骤三:建立对应的映射配置文件

用户的映射配置文件代码如下:
IUserDao.xml

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fjut.dao.IUserDao">
    <resultMap id="userMap" type="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="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="userMap">
        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>
</mapper>

角色的映射配置文件代码如下:
IRoleDao.xml

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fjut.dao.IRoleDao">
    <!--定义roleMap-->
    <resultMap id="roleMap" type="role">
        <id property="roleId" column="id"></id>
        <result property="roleName" column="ROLE_NAME"></result>
        <result property="roleDesc" column="ROLE_DESC"></result>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="roleMap">
        select * from role
    </select>
</mapper>

步骤四:测试

UserTest:测试一个用户有多个角色

	/**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println("---每个用户的信息及用户下角色的信息----");
            System.out.println(user);
            System.out.println(user.getRoles());
        }
    }

RoleTest:测试一个角色有多个用户

/**
	     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        List<Role> roles = roleDao.findAll();
        for(Role role : roles){
            System.out.println("---每个角色的信息及角色下用户的信息----");
            System.out.println(role);
            System.out.println(role.getUsers());
        }
    }

结果:
在这里插入图片描述
在这里插入图片描述


四、注解实现的方式:

一对一:

用到注解 one = @One(select=“方法的全限定名”,fetchType=加载类型(一对一关系一般情况下用立即加载方式)。FetchType.EAGER)
一个账户对应着一个用户。

public interface IAccountDao {


    /**
     * 查询所有账户信息,并显示其一对一的用户信息
     */
    @Select("select * from Account")
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(property = "uid",column = "uid"),
            @Result(property = "money",column = "money"),
            @Result(property = "user",column = "uid",one = @One(select = "com.fjut.dao.IUserDao.findUserById",fetchType = FetchType.EAGER))
    })
    List<Account> findAll();

    /**
     * 根据用户uid查询账户信息(一对多关系)
     * @param uid
     * @return
     */
    @Select("select * from account where uid = #{uid}")
    List<Account> findAccountById(Integer uid);
}

一对多:

用到注解:many = @Many(select=“方法的全限定名”,fetchType=加载方式(一对多和多对多一般用延时加载(懒加载)FetchType.LAZY)
一个用户对应着多个账户。

public interface IUserDao {

    /**
     * 查询所有用户,并显示其一对多的账户信息
     * @return
     */
    @Select("select * from user")
    @Results(id = "userMap",value = {
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "address",column = "address"),
            @Result(property = "sex",column = "sex"),
            @Result(property = "birthday",column = "birthday"),
            @Result(property = "accounts",column = "id",many = @Many(select = "com.fjut.dao.IAccountDao.findAccountById",fetchType = FetchType.LAZY))
    })
    List<User> findAll();


    /**
     * 根据账户表里的uid查询到对应的一对一的用户信息
     */
    @Select("select * from user where id = #{id}")
    User findUserById(Integer id);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值