mybatis(diary)----表与表之间的关系

多对一【包括一对一】

  1. 实体类 
    package com.yuan.doman;
    
    import java.util.Date;
    import java.util.List;
    
    public class User {
        private Integer id;
        /**
         * 用户姓名
         */
        private String  username;
        /**
         * 用户生日
         */
        private Date    birthday;
    
        /**
         * 用户性别
         */
        private String  sex;
        /**
         * 用户地址
         */
        private String  address;
    
        /**
         *角色下的账户集合
         * @return
         */
        private List<Account> roles;
    //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.yuan.dao.AccountDao">
        <!--配置一对多关系的resultMap-->
        <resultMap id="accountUserMap" type="account">
                <!--id是唯一标识-->
                <!--type是对应的实体类-->
            <id column="aid" property="id"/>
            <!--id是主键-->
            <!--result是普通列-->
                <!--column是数据库列名-->
                <!--property是属性名-->
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
            <!--association对应主表关系-->
                <!--property表示外键属性是User-->
                <!--column表示用uid字段来获取-->
                <!--javaType表示返回的Java类型是什么-->
            <association property="user" column="uid" javaType="com.yuan.doman.User">
                <id column="id" property="id"/>
                <result column="username" property="username"/>
                <result column="birthday" property="birthday"/>
                <result column="sex" property="sex"/>
                <result column="address" property="address"/>
            </association>
        </resultMap>
    
        <!--查询全部Account-->
        <select id="findAll" resultMap="accountUserMap">
            SELECT a.id as AID,a.UID,a.MONEY,u.* from account a,user u where u.id = a.UID
        </select>
        
    </mapper>
    package com.yuan.test;
    
    import com.yuan.dao.AccountDao;
    import com.yuan.doman.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.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class AccountDaoTest {
        InputStream is = null;
        SqlSessionFactory factory = null;
        SqlSession session = null;
        AccountDao accountDao = session.getMapper(AccountDao.class);
    
        @Before
        public void init() throws IOException {
            //读取配置文件
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建会话工厂
            factory = new SqlSessionFactoryBuilder().build(is);
            //生产SQLSession对象
            session = factory.openSession();
        }
    
        @After
        public void close() throws IOException {
            session.commit();
            session.close();
            is.close();
        }
    
        @Test
        public void finAllAccount() {
            List<Account> accountAll = accountDao.findAll();
            for (Account account : accountAll) {
                System.out.println("---------------");
                System.out.println("account = " + account);
                System.out.println(account.getUser());
            }
        }
    
    }

     

  2. 一对多

  3. 实体类

    package com.yuan.doman;
    
    import java.util.Date;
    import java.util.List;
    
    public class User {
        private Integer id;
        /**
         * 用户姓名
         */
        private String  username;
        /**
         * 用户生日
         */
        private Date    birthday;
    
        /**
         * 用户性别
         */
        private String  sex;
        /**
         * 用户地址
         */
        private String  address;
    
        /**
         *角色下的账户集合
         * @return
         */
        private List<Account> roles;
    //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.yuan.dao.UserDao">
    
        <sql id="defUser">
    SELECT u.*,a.ID as aid,A.MONEY
    FROM USER u LEFT JOIN ACCOUNT a
    ON a.UID = u.id
        </sql>
    
        <resultMap id="userAccountMap" type="user">
            <id property="id" column="id"></id>
            <result property="username" column="username"/>
            <result property="birthday" column="birthday"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
            <!--账户定义集合-->
            <!--property 集合属性名-->
            <!--ofType 集合的泛型-->
            <collection property="accounts" ofType="com.yuan.doman.Account">
                <id column="aid" property="id"/>
                <result column="uid" property="uid"/>
                <result column="money" property="money"/>
            </collection>
        </resultMap>
    
    
        <!--查询全部User-->
        <select id="findAll" resultMap="userAccountMap">
            <include refid="defUser"/>
        </select>
    
        <!--根据ID查询User-->
        <select id="findById" resultMap="userAccountMap" parameterType="int">
            <include refid="defUser"/>
            <where>
                ID = #{id}
            </where>
        </select>
    
    
    </mapper>

    测试:

    package com.yuan.test;
    
    import com.yuan.dao.UserDao;
    import com.yuan.doman.Account;
    import com.yuan.doman.User;
    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.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class UserDaoTest {
        InputStream is = null;
        SqlSessionFactory factory = null;
        SqlSession session = null;
    
    
        @Before
        public void init() throws IOException {
            //读取配置文件
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建会话工厂
            factory = new SqlSessionFactoryBuilder().build(is);
            //生产SQLSession对象
            session = factory.openSession();
        }
    
        @After
        public void close() throws IOException {
            session.commit();
            session.close();
            is.close();
        }
    
    
        @Test
        public void finAllAccount() {
            UserDao userDao = session.getMapper(UserDao.class);
            List<User> userAccounts = userDao.findAll();
            for (User userAccount : userAccounts) {
                System.out.println("------------------------");
                System.out.println("userAccount = " + userAccount);
                if (!(userAccount.getAccounts().size()<=0)) {
                    for (Account account : userAccount.getAccounts()) {
                        System.out.println("account = " + account);
                    }
                }
            }
    
        }
    }

    多对多 

    1. 实体类

      package com.yuan.doman;
      
      import java.util.List;
      
      public class Role {
          private Integer id;
          private String role_name;
          private String role_desc;
          /**
           * 角色对应的账户结合
           */
          private List<User> users;
          //Get() Set() 方法
      }
      package com.yuan.doman;
      
      import java.util.Date;
      import java.util.List;
      
      public class User{
          private Integer id;
          /**
           * 用户姓名
           */
          private String  username;
          /**
           * 用户生日
           */
          private Date    birthday;
          /**
           * 用户性别
           */
          private String  sex;
          /**
           * 用户地址
           */
          private String  address;
      
          /**
           *角色下的账户集合
           * @return
           */
          private List<Role> roles;
          //Get() Set() 方法
      }

      映射文件:

      1. <?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.yuan.dao.RoleDao">
            
            <resultMap id="roleUserMap" type="role">
                <id property="id" column="rid"></id>
                <result property="role_name" column="role_name"/>
                <result property="role_desc" column="role_desc"/>
                <collection property="users" ofType="user">
                    <id property="id" column="UID"></id>
                    <result property="username" column="username"/>
                    <result property="birthday" column="birthday"/>
                    <result property="sex" column="sex"/>
                    <result property="address" column="address"/>
                </collection>
            </resultMap>
        
        
            <!--查询全部User-->
            <select id="findAll" resultMap="roleUserMap">
         SELECT
         r.id as rid
        ,r.ROLE_NAME
        ,r.ROLE_DESC
        ,u.id AS UID
        ,u.username
        ,u.sex
        ,u.address
        ,u.birthday
         from role r
         LEFT JOIN user_role ur ON r.ID = ur.RID
         LEFT JOIN user       u ON u.id = ur.UID
            </select>
        
            <!--根据ID查询User-->
            <select id="findById" resultMap="roleUserMap" parameterType="int">
            </select>
        
        
        </mapper>
        <?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.yuan.dao.UserDao">
        
        
            <resultMap id="userRolestMap" type="user">
                <id property="id" column="uid"></id>
                <result property="username" column="username"/>
                <result property="birthday" column="birthday"/>
                <result property="sex" column="sex"/>
                <result property="address" column="address"/>
        
                <collection property="roles" ofType="role">
                    <id property="id" column="rid"></id>
                    <result property="role_name" column="role_name"/>
                    <result property="role_desc" column="role_desc"/>
                </collection>
            </resultMap>
        
        
            <!--查询全部User-->
            <select id="findAll" resultMap="userRolestMap">
        SELECT
           u.id AS UID
          ,u.username
          ,u.sex
          ,u.address
          ,u.birthday
          ,r.id as rid
          ,r.ROLE_NAME
          ,r.ROLE_DESC
        from user       u
          LEFT JOIN user_role ur ON u.ID = ur.UID
          LEFT JOIN role r ON r.ID = ur.RID
            </select>
        
            <!--根据ID查询User-->
            <select id="findById" resultMap="userRolestMap" parameterType="int">
            </select>
        
        
        </mapper>

        测试:

        package com.yuan.test;
        
        import com.yuan.dao.RoleDao;
        import com.yuan.doman.Role;
        import com.yuan.doman.User;
        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.IOException;
        import java.io.InputStream;
        import java.util.List;
        
        public class RoleDaoTest {
            InputStream is = null;
            SqlSessionFactory factory = null;
            SqlSession session = null;
            RoleDao roleDao = null;
            @Before
            public void init() throws IOException {
                //读取配置文件
                is = Resources.getResourceAsStream("SqlMapConfig.xml");
                //创建会话工厂
                factory = new SqlSessionFactoryBuilder().build(is);
                //生产SQLSession对象
                session = factory.openSession();
                roleDao = session.getMapper(RoleDao.class);
            }
            @After
            public void close() throws IOException {
                session.commit();
                session.close();
                is.close();
            }
            @Test
            public void finAll() {
        
                List<Role> roles = roleDao.findAll();
                for (Role role : roles) {
                System.out.println("-----------------");
                    System.out.println("role = " + role);
                    if(!(role.getUsers().size()<=0)){
                        for (User user : role.getUsers()) {
                            System.out.println("user = " + user);
                        }
                    }
                }
            }
        }
        package com.yuan.test;
        
        import com.yuan.dao.UserDao;
        import com.yuan.doman.User;
        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.IOException;
        import java.io.InputStream;
        import java.util.List;
        
        public class UserDaoTest {
            InputStream is = null;
            SqlSessionFactory factory = null;
            SqlSession session = null;
            UserDao userDao = null;
        
            @Before
            public void init() throws IOException {
                //读取配置文件
                is = Resources.getResourceAsStream("SqlMapConfig.xml");
                //创建会话工厂
                factory = new SqlSessionFactoryBuilder().build(is);
                //生产SQLSession对象
                session = factory.openSession();
                userDao = session.getMapper(UserDao.class);
            }
            @After
            public void close() throws IOException {
                session.commit();
                session.close();
                is.close();
            }
            @Test
            public void finAllAccount() {
        
                List<User> users = userDao.findAll();
                for (User user : users) {
                    System.out.println("user = " + user);
                }
            }
        }

         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值