MyBatis的测试代码根据性别分组统计平均薪资
// 定义一个接口 public interface EmployeeMapper { // 根据性别分组统计平均薪资 @Select("SELECT gender, AVG(salary) AS averageSalary FROM employee GROUP BY gender") List<Map<String, Object>> getAverageSalaryByGender(); }
// 测试代码 public class MyBatisTest {
public static void main(String[] args) {
// 创建一个MyBatis的配置对象
Configuration configuration = new Configuration();
// 设置数据库连接信息
configuration.setJdbcUrl("jdbc:mysql://localhost:3306/test");
configuration.setJdbcUsername("root");
configuration.setJdbcPassword("password");
// 创建一个SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
// 创建一个SqlSession对象
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
// 获取EmployeeMapper接口的实现类对象
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
// 调用接口方法获取结果
List<Map<String, Object>> result = employeeMapper.getAverageSalaryByGender();
// 打印结果
for (Map<String, Object> row : result) {
System.out.println("Gender: " + row.get("gender") + ", Average Salary: " + row.get("averageSalary"));
}
}
}
原文地址: https://www.cveoy.top/t/topic/ihWZ 著作权归作者所有。请勿转载和采集!