Mybatis多表查询 结果的两种封装方式


 
需求: 一对多查询,查询用户,同时查询账号的集合!
案例分析:       
1.一个用户可以有多个账号 , 也可以没有账号.       
2.所以sql语句使用左表查询 ( 以左表为主 )
在这里插入图片描述
 
 

一、配置文件XML的使用!

准备数据:       
1.创建数据库 并 初始化数据 !       
2.创建表对应的JavaBean 类.
 
User类:
public class User implements Serializable {
    private int id;
    private String username;
    private String sex;
    private String address;
    private Date birthday;

    // 用户表中添加账号集合.
    private List<Account> accountList;
    // 提供get / set 方法  和 toString方法. 
}
 
Account类:
public class Account {
    private int id;
    private int uid;
    private double money;
    
    // 提供get / set 方法  和 toString方法. 
}
 
UserMapper接口:
public interface UserMapper {
    //  一对多查询:  查询用户,同时查询账号的集合
    public List<User> findUserAndAccountList();
}
 
UserMapper.xml
<mapper namespace="com.aaa.dao.UserMapper">
    <!--  一对多查询,  查询用户,同时查询账号的集合  -->
    <resultMap id="aaa" type="User">
        <!-- 主键字段 -->
        <id property="id" column="user_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>
        <!-- 关联账号的集合属性 collectoin -->
        <collection property="accountList" column="account_id" ofType="Account">
            <id property="id" column="account_id"></id>
            <result property="uid" column="uid"></result>
            <result property="money" column="money"></result>
        </collection>
    </resultMap>
    
    <select id="findUserAndAccountList" resultMap="aaa">
        select u.*,a.*,a.UID account_id,u.id user_id
        from user u left join account a
        on u.id = a.uid
    </select> 
</mapper>
 
主配置文件: mybatis-config.xml
<configuration>
    <!-- 引入jdbc的配置文件.  -->
    <properties resource="jdbc.properties"></properties>

    <!-- 设置 -> 返回类型的别名 -->
    <typeAliases>
        <!-- 扫描包:这个包下的所有类都以类名为别名   -->
        <package name="com.aaa.domain"></package>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
    <mappers>
        <!-- 扫描包:
               前提: 接口的包名必须要和关联sql语句的配置文件包名一致.
         -->
        <package name="com.aaa.dao"></package>
    </mappers>
</configuration>
 
测试类:
public class UserMapperTest {
    InputStream in = null;
    SqlSession sqlSession= null;
    UserMapper mapper = null;

    @Before
    public void init() throws Exception {
        // 1.读取主配置文件的输入流.
        in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        // 2.获取sql对象.
        sqlSession = sqlSessionFactory.openSession();
        // 3.获取dao接口的实现类对象(代理)
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void destory() throws Exception {
        // 提交事务.
        sqlSession.commit();

        // 5.释放资源.
        sqlSession.close();
        in.close();
    }
   
    @Test
    public void findUserAndAccountAndRoleList() {
        User user = mapper.findUserAndAccountAndRoleList(41);
        System.out.println(user);
    }
}

 

 

二、注解版的使用

注: 使用注解版 , 就不能使用xml配置文件了.
 
UserMapper.java
public interface UserDao {
    /**
     *  一对多查询:
     *     查询用户信息 并且 查询账号集合信息.
     */
    @Select("select * from user ")
    @Results(id = "findUserAndAccontResult" , value = {
    @Result(id = true , property = "userId" , column = "id"),
    @Result(property = "username" , column = "username"),
    @Result(property = "userBirthday" , column = "birthday"),
    @Result(property = "userSex" , column = "sex"),
    @Result(property = "userAddress" , column = "address"),
    // 封装账户集合信息.
    @Result(property = "accountList" , column = "id" ,
            many = @Many(select = "com.aaa.dao.AccountDao.findByUserId" , 
            fetchType = FetchType.LAZY))
    })
    public List<User> findUserAndAccount();
 
AccountDao.java
public interface AccountDao {
    // 根据uid查询账号信息.
    @Select("SELECT * FROM account WHERE uid=#{user_id}")
    public List<Account> findByUserId(@Param("user_id") int user_id);
}

 

 
 
 
 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM