Mybatis框架(8) —— Java與數據庫的數據匹配方式

方式一:修改 JavaBean變量

  • 在 JavaBean中,將 變量名 設置爲 數據庫的字段名

MySQL數據庫

  • 字段
    • id
    • username
    • birthday
    • sex
    • address

Java實體類

  • 變量名
    • id
    • username
    • birthday
    • sex
    • address

映射配置文件

<select id="findAll" resultType="cn.water.domain.User">
	SELECT 
    	id,
        username,
        address,
        sex,
        birthday 
    FROM 
    	user;
</select>

方式二:修改 SQL語句

  • 在SQL語句中,爲 數據庫字段 設置 別名

MySQL數據庫

  • 字段
    • id
    • username
    • birthday
    • sex
    • address

Java實體類

  • 變量名
    • userId
    • username
    • userBirthday
    • userSex
    • userAddress

映射配置文件

<select id="findAll" resultType="cn.water.domain.User">
	SELECT 
    	id AS userId,
        username,
        address AS userAddress,
        sex AS userSex,
        birthday AS userBrithday 
    FROM 
    	user;
</select>

方式三:設置 對應關係

  • 在 映射配置文件 中,設置 JavaBean變量 與 數據庫字段 的對應關係。

變量:數據類型

MySQL數據庫

  • 字段
    • id
    • username
    • birthday
    • sex
    • address

Java實體類

  • 變量名
    • userId
    • username
    • userBirthday
    • userSex
    • userAddress

映射配置文件

<!-- 設置對應關係 -->
<resultMap id="userMap" type="cn.water.domain.User">
	<!-- 主鍵字段的對應 -->
    <id property="userId" column="id" ></id>
	<!-- 非主鍵字段的對應 -->
    <result property="username" column="username" ></result>
	<result property="UserBirthday" column="birthday" ></result>
	<result property="UserSex" column="sex" ></result>
	<result property="UserAddress" column="address" ></result>
</resultMap>

<select id="findAll" resultMap="userMap">
	SELECT id * FROM user;
</select>

變量:JavaBean(多表查詢)

MySQL數據庫

  • 用戶表
    • 字段
      • id
      • username
      • birthday
      • sex
      • address
  • 賬戶表
    • 字段
      • id
      • uid
      • money

Java實體類

  • 賬戶類
    • 變量名
      • id
      • uid
      • money
      • User

映射配置文件

 <resultMap id="userAccountsMap" 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>
        <collection property="accountList" ofType="account">
            <id property="id" column="aid"></id>
            <result property="uid" column="uid"></result>
            <result property="money" column="money"></result>
        </collection>
</resultMap>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章