如果有问题,可以参考前面的博客 ###1. 普通的方式 ####1.1 接口文件添加方法
public List<Employeer> findEmployeer();
####1.2 添加***mapper.xml文件的sql语句
<select id="findEmployeer" resultType="Employeer">
select* from `t_employeer`
</select>
####1.3 编写测试类
public static void main(String[] args) {
//test1();
SqlSession session = null;
try {
session = sqlSessionFactory.openSession();
EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
List<Employeer> lists=employeerMapper.findEmployeer();
for (Employeer employeer : lists) {
System.out.println(employeer.toString());
}
session.commit() ;
} finally {
session.close();
}
}
###2.使用resultMap
2.1 编写resultMap
其实可以多表来关联查询,只需要修改实体类和sql就可以了
<!-- 定义数据库字段与实体对象的映射关系 -->
<resultMap type="Employeer" id="resultMap">
<id property="employeer_id" column="employeer_id"/>
<result property="employeer_name" column="employeer_name"/>
<result property="employeer_age" column="employeer_age"/>
<result property="employeer_department" column="employeer_department"/>
<result property="employeer_worktype" column="employeer_worktype"/>
</resultMap>
id、result是最简单的映射,id为主键映射;result其他基本数据库表字段到实体类属性的映射。
2.2 编写查询语句
<!-- 返回list 的select 语句,注意 resultMap 的值是指向前面定义好的 -->
<select id="findEmployeerByName" parameterType="string" resultMap="resultMap">
select * from `t_employeer` where employeer_name like #{employeer_name}
</select>
2.3 在EmployeerMapper 接口中增加方法
/**
* 注意要和Employeer.xml的方法名对应
*/
public List<Employeer> findEmployeerByName(String employeer_name);
2.4 编写测试类
/**
* 查询列表
*/
public static List<Employeer> getEmployeerList(String employeer_name){
SqlSession session = null;
List<Employeer> employeers=null;
try {
session = sqlSessionFactory.openSession();
EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
employeers = employeerMapper.findEmployeerByName(employeer_name);
session.commit() ;
} finally {
session.close();
}
return employeers;
}
public static void main(String[] args) {
List<Employeer> employeers=getEmployeerList("张三");
for(Employeer employeer:employeers){
System.out.println(employeer);
}
}