mybatis select 查询标签

model

public class User implements Serializable {
    private Integer userId;
    private String userName;
    private String userAddress;
}

interface

public interface IUserDao {
    User findById(Integer userId);
}

mybatis.xml

<select id="findById" resultType="com.User" parameterType="int"> 
  select * from user where id = #{uid} 
</select> 

resultType 属性:指定结果集的类型
parameterType 属性:指定传入参数的类型
sql 语句中使用#{}字符:占位符,相当于原来 jdbc 部分所学的?

测试

  @Test 
  public void testFindOne()  {   
    //6.执行操作 
    User user = userDao.findById(41); 
    System.out.println(user); 
  } 
### 绑定 resultMap 在 MyBatis Select 标签中的方法 在 MyBatis 中,`<select>` 标签用于定义查询操作。为了将查询结果映射到复杂的 Java 对象结构中,可以使用 `resultMap` 属性来指定自定义的结果映射规则。 #### 定义 resultMap 首先,在 XML 配置文件中创建一个 `<resultMap>` 来描述对象属性与数据库字段之间的对应关系: ```xml <resultMap id="userResultMap" type="User"> <id property="id" column="USER_ID"/> <result property="username" column="USERNAME"/> </resultMap> ``` 这段代码片段展示了如何设置基本的 `resultMap`[^1]。 #### 使用 resultMap 进行关联加载 对于涉及多表联结或多级嵌套的对象模型,可以通过配置 `association` 和 `collection` 子标签实现更复杂的关系映射: ```xml <!-- 用户实体类 --> <resultMap id="detailedUserResultMap" type="DetailedUser"> <!-- 主键映射 --> <id property="userId" column="USER_ID"/> <!-- 单向一对多关联:订单集合 --> <collection property="orders" ofType="Order" select="findOrdersByUserId" column="{ userId = USER_ID }"/> <!-- 双向一对一关联:地址信息 --> <association property="address" javaType="Address" select="findAddressById" column="ADDRESS_ID"/> </resultMap> <select id="findUsersWithDetails" resultMap="detailedUserResultMap"> SELECT * FROM users WHERE ... </select> ``` 这里展示了一个更加详细的例子,其中包含了两个不同类型的关联方式——单向的一对多(`collection`)以及双向的一对一(`association`)。 需要注意的是,当涉及到大量数据时,延迟加载特性可以帮助优化性能表现;但如果频繁触发懒加载,则可能会带来额外开销[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值