mybatis级联

数据库准备

数据库表
数据库表

表二表二外键user_id对应表一主键id

JSP准备: 运用了JSTL标签库,目的是迭代出role对象的各个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!--使用JSTL core标签库-->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:if test="${empty role}">
<h3>没有相关的元素</h3>
</c:if>
<c:if test="${!empty role}">
<table border="1" align="center">
<tr>
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
<td>入职日期</td>
<td>密码</td>
<td>账号</td>
</tr>
<c:forEach items="${role}" var="role">
<tr>
<td>${role.id}</td>
<td>${role.name}</td>
<td>${role.age}</td>
<td>${role.hiredate.toLocaleString()}</td>
<td>${role.roleLogin.password}</td>
<td>${role.roleLogin.username}</td>
<td><a href="/delete/${role.id}">删除</a></td>
<td><a href="/update.jsp">更新</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

POJO类准备:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Role {
private Long id;
private String name;
private Integer age;
private RoleLogin roleLogin;
private Date hiredate;
//省略getter/setter
}
public class RoleLogin {
private String password;
private String username;
//省略getter/setter
}

这个时候如果我们需要使用mybatis从中获取password和username 那么则需要使用自定义一个resultMap我们知道在级联中有一对一、一对多、多对多等关系,association主要是用来解决一对一关系的那么上面那种情况我们便可以使用association来处理

  • 我们需要创建一个接口,为了创建一个方法,通过id(主键)找到对应的RoleLogin对象
1
2
3
public interface LoginMapper {
RoleLogin findRoleLoginByid(Long id);
}

并创建其对应的Mapper.xml方法

1
2
3
4
5
<mapper namespace="com.ssm.Dao.LoginMapper">
<select id="findRoleLoginByid" parameterType="long" resultType="com.ssm.pojo.RoleLogin">
SELECT * FROM t_login WHERE user_id = #{id}
</select>
</mapper>
  • 我们需要创建一个接口,返回一个role对象(因为返回多个对象,所以此处需用List)
1
2
3
public interface RoleMapper {
List<Role> getAllmsg();
}

并创建其对应的Mapper.xml方法

1
2
3
4
5
6
7
8
9
<mapper namespace="com.ssm.Dao.RoleMapper">
<resultMap id="roleResultMapper" type="com.ssm.pojo.Role">
<id column="id" property="id"/>
<association property="roleLogin" column="id" select="com.ssm.Dao.LoginMapper.findRoleLoginByid"/>
</resultMap>
<select id="getAllmsg" resultMap="roleResultMapper">
SELECT * FROM t_user
</select>
</mapper>
  • 我们需要在service层定义一个接口方法
1
2
3
public interface RoleService {
List<Role> getAllmsg();
}
  • 并写出其实现类
1
2
3
4
5
6
7
8
9
10
11
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
//注入dao层
@Autowired
private RoleMapper roleMapper = null;

public List<Role> getAllmsg() {
return roleMapper.getAllmsg();
}
}
  • 最后写一个controller类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller
public class RoleController {

@Autowired
private RoleService roleService = null;

@RequestMapping(value = "/allmsg",method = RequestMethod.GET)
public ModelAndView allmsg(){
List<Role> allmsg = roleService.getAllmsg();
ModelAndView mv = new ModelAndView("AllMsg");
mv.addObject("role",allmsg);
return mv;
}
}

最后效果

效果

赏个🍗吧
0%