1. 程式人生 > >mybatis - 關於多表查詢 結果的兩種封裝方式(註解版 , xml版)

mybatis - 關於多表查詢 結果的兩種封裝方式(註解版 , xml版)

需求: 一對多查詢,查詢使用者,同時查詢賬號的集合!

案例分析:
       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

<?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.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

<?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>
    <!-- 引入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);
}