mybatis写7查询入职两年到三年之间员工的最高薪资和最低薪资的员工信息
在MyBatis中,可以使用XML或注解方式编写SQL语句进行数据库操作。以下是使用XML方式编写的MyBatis查询入职两年到三年之间员工的最高薪资和最低薪资的员工信息的示例。
首先,创建一个EmployeeMapper.xml文件,定义查询语句:
<!-- EmployeeMapper.xml -->
<mapper namespace="com.example.mapper.EmployeeMapper">
<!-- 查询入职两年到三年之间员工的最高薪资 -->
<select id="getMaxSalaryByYears" resultType="com.example.model.Employee">
SELECT * FROM employee
WHERE DATEDIFF(CURDATE(), hire_date) >= 730 AND DATEDIFF(CURDATE(), hire_date) < 1095
ORDER BY salary DESC
LIMIT 1
</select>
<!-- 查询入职两年到三年之间员工的最低薪资 -->
<select id="getMinSalaryByYears" resultType="com.example.model.Employee">
SELECT * FROM employee
WHERE DATEDIFF(CURDATE(), hire_date) >= 730 AND DATEDIFF(CURDATE(), hire_date) < 1095
ORDER BY salary ASC
LIMIT 1
</select>
</mapper>
接下来,创建一个EmployeeMapper接口,定义对应的方法:
// EmployeeMapper.java
package com.example.mapper;
import com.example.model.Employee;
public interface EmployeeMapper {
Employee getMaxSalaryByYears();
Employee getMinSalaryByYears();
}
最后,在MyBatis配置文件中配置Mapper接口和数据库连接信息:
<!-- mybatis-config.xml -->
<configuration>
<!-- 配置数据库连接信息 -->
<!-- 配置Mapper接口 -->
<mappers>
<mapper resource="com/example/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
现在,就可以在代码中使用EmployeeMapper接口进行查询操作了:
// 使用Spring整合MyBatis的示例代码
package com.example.service;
import com.example.mapper.EmployeeMapper;
import com.example.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
private final EmployeeMapper employeeMapper;
@Autowired
public EmployeeService(EmployeeMapper employeeMapper) {
this.employeeMapper = employeeMapper;
}
public Employee getMaxSalaryByYears() {
return employeeMapper.getMaxSalaryByYears();
}
public Employee getMinSalaryByYears() {
return employeeMapper.getMinSalaryByYears();
}
}
上述代码示例中,使用@Autowired注解将EmployeeMapper注入到EmployeeService中,然后可以调用EmployeeMapper接口中定义的方法来执行查询操作。
请注意,示例中使用了CURDATE()函数获取当前日期,DATEDIFF()函数计算入职时间与当前时间的天数差。同时,根据实际的数据库表结构和字段名进行调整
原文地址: https://www.cveoy.top/t/topic/ihYy 著作权归作者所有。请勿转载和采集!