Mybatis查询多条记录并返回List集合

实体对象如下:

public class Employee {
    private Integer employeeId;

    private String employeeName;

    private String employeeEmail;

    private String employeePhone;

    private Integer employeeAge;

    private String employeeGender;

    private String employeeBelong;

    private String employeeLevel;

    private String employeeAddress;

    private Date createData;

    private Date updateData;
}
//省略getter.setter方法

接口方法定义如下:

/**
     * 多条件查询
     * @param baseQuery
     * @return
     */
    public List<T> selectByParams(BaseQuery baseQuery) throws DataAccessException;

XML映射文件如下:

<select id="selectByParams" parameterType="com.rqt.PMSystem.query.EmployeeQuery" resultType="com.rqt.PMSystem.vo.Employee">
#     多条件查询 根据员工名和部门名
    select
        <include refid="Base_Column_List"/>
    from t_employee
    <where>
      <if test="employeeName!=null and employeeName!=''">
        employee_name = #{employeeName}
      </if>
      <if test="employeeBelong!=null and employeeBelong!=''">
        and employee_belong = #{employeeBelong}
      </if>
    </where>
  </select>

执行方法:

List<Employee> employees = employeeMapper.selectByParams(employeeQuery);

结论:
(1)XML中只需resultType属性值为实体对象别名或全路径名。
(2)mybatis会通过接口文件的返回值类型来判断返回的是集合还是对象。如果是对象,则按常规查询并返回;如果是List集合,mybatis则会将查询到的多条记录设置进集合中并返回。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 MyBatis 插入多条数据时,有两种常见的方式: 1. 使用 `foreach` 标签 使用 `foreach` 标签可以将多条数据一次性插入到数据库中。在 `foreach` 标签中,可以使用 `${}` 或者 `#{}` 占位符来获取集合中的数据。以下是一个示例: ```xml <insert id="batchInsert" parameterType="java.util.List"> insert into user (name, age) values <foreach collection="list" item="item" separator=","> (#{item.name}, #{item.age}) </foreach> </insert> ``` 在 Java 代码中,你可以将多条数据封装到一个 `List` 中,然后调用 `batchInsert` 方法插入数据: ```java List<User> userList = new ArrayList<>(); userList.add(new User("张三", 18)); userList.add(new User("李四", 20)); userMapper.batchInsert(userList); ``` 2. 使用 `insert into table select` 语句 另一种方式是使用 `insert into table select` 语句。首先,你需要创建一个临时表,然后将多条数据插入到临时表中,最后再将临时表中的数据插入到目标表中。以下是一个示例: ```xml <insert id="batchInsert" parameterType="java.util.List"> create temporary table temp_user (name varchar(20), age int); <foreach collection="list" item="item"> insert into temp_user (name, age) values (#{item.name}, #{item.age}); </foreach> insert into user (name, age) select name, age from temp_user; drop temporary table if exists temp_user; </insert> ``` 在 Java 代码中,你可以将多条数据封装到一个 `List` 中,然后调用 `batchInsert` 方法插入数据: ```java List<User> userList = new ArrayList<>(); userList.add(new User("张三", 18)); userList.add(new User("李四", 20)); userMapper.batchInsert(userList); ``` 以上两种方式都可以批量插入多条数据,你可以根据实际情况选择合适的方式。需要注意的是,在使用 `foreach` 标签插入数据时,需要注意 SQL 注入问题,建议使用 `#{}` 占位符来获取集合中的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值