SSM框架通过姓名和学号进行查找
接口文件StudentDao和映射文件StudentDao.xml
public interface StudentDao {
public List<Student> findStudent(Map<String, Object> map);
}
通过姓名和学号进行查询
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" column="address" select="com.itheima.dao.AddressMapper.findById"></association>
</resultMap>
<!--根据id查询客户信息 -->
<select id="findStudent" parameterType="Map" resultMap="StudentResult">
select * from student
<where>
<if test="name !=null and name!=''">
and name like concat('%',#{name},'%')
</if>
<if test="classId!=null and classId!=''">
and classId=#{classId}
</if>
</where>
</select>
地址接口文件和映射文件AddressMapper和AddressMapper.xml
`public interface AddressMapper {
public Address findById(Integer id);
}`
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.AddressMapper">
<resultMap type="Address" id="AddressResult">
<result property="id" column="id"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</resultMap>
<select id="findById" parameterType="Integer" resultType="Address">
select * from address where id=#{id}
</select>
</mapper>
接口文件StudentService和定义查询的方法
public interface StudentService {
public List<Student> findStudent(Map<String, Object> map);
}
``
@Autowired
private StudentDao studentdao;
public List<Student> findStudent(Map<String, Object> map) {
List<Student> students=studentdao.findStudent(map);
return students;
}
控制器类StudentController
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/info")
public String findStudentById(Model model,Student student) {
Map<String,Object> map=new HashMap<String,Object>();
String name=student.getName();
String classId=student.getClassId();
map.put("name", "%"+name+"%");
map.put("classId", classId);
List<Student> student1 = studentService.findStudent(map);
model.addAttribute("student",student1);
return "student";
}
}
index.jsp和student.jsp页面
<body>
<form action="${pageContext.request.contextPath }/info" method="post">
查询学生信息和住址:<br/>
姓名:<input type="text" name="name"><br/>
学号:<input type="text" name="classId"><br/>
<input type="submit" value="查询">
</form>
</body>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>
<table border=1>
<tr>
<td>id</td>
<td>姓名</td>
<td>性别</td>
<td>班级</td>
<td>学号</td>
<td>住址</td>
</tr>
<c:forEach items="${student }" var="s" >
<tr>
<%-- <td>${s} </td> --%>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.sex}</td>
<td>${s.classname}</td>
<td>${s.classId}</td>
<td>${s.address.shi}</td>
</tr>
</c:forEach>
</table>
<a href="index.jsp">返回</a>
</body>
</html>
运行结果