MyBatisMyBatis 关系映射XML配置

一对一


 

关键在于

<collection property="groups" ofType="com.entity.Group">将ofType变成javaType
推荐个网址

mybatis关系映射之一对多和多对一

 

 
 【版本声明】本文为博主原创作品,转发请申明出处

 

一对多


 

<mapper namespace="com.entity.UserMapper">
<!--一对多关联查询  -->
<resultMap id="user_info" type="com.entity.User">
  <result property="id" column="id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
  <collection property="userInfos" ofType="com.entity.UserInfo" column="uid">
          <result property="id" column="id"/>
          <result property="address" column="address"/>
  </collection>
</resultMap>
  <select id="getUser"  resultMap="user_info">
    select * from user u,userinfo i where u.id=i.uid and u.id=#{id}
  </select>
</mapper>

实体类,给出字段,自己get和set

/**
 * 
 * @author 坚持到你GL
 *
 */
public class User {
    private int id;
    private String username;
    private String password;
    private List<UserInfo> userInfos;


/**
 * 
 * @author 坚持到你GL
 *
 */
public class UserInfo {
    private int id;
    private String address;
    private int uid;

多对多


MyBatis, 

<mapper namespace="com.entity.UserMapper">
<!--多对多  -->
<resultMap id="ug" type="com.entity.User">
  <result property="id" column="id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
  <collection property="groups" ofType="com.entity.Group">
          <id property="id" column="gid"/>
          <result property="info" column="info"/>
  </collection>
</resultMap>
  <select id="getUserGroup"  resultMap="ug">
    select * from user u,    `group` g,user_group ug where g.id=#{id} and u.id=ug.uid and g.id=ug.gid
  </select>
  </mapper>

实体类

/**
 * 
 * @author 坚持到你GL
 *
 */
public class User {
    private int id;
    private String username;
    private String password;
    private List<Group> groups;

/**
 * 
 * @author 坚持到你GL
 *
 */
public class Group {
    private int id;
    private String info;
    private List<User>users;

/**
 * 中间表
 * @author 坚持到你GL
 *
 */
public class UserGroup {
    private int id;
    private int uid;
    private int gid;

论及映射


在我看来那个实体类就没啥太大关系关系,不就是一个sql语句解决的题材,直接多表查询就马到功成,程序将它设置关联就好

xml里面配备也是安插了sql语句,下边给出多少个事关的小毛驴(xml)

网站地图xml地图