文章内容速览
一.DAO开发(回顾上一节内容)
1. 在entity下新建类DiscussPost
- 数据库的表discuss_post中有什么属性,就在这个类中定义什么属性。
- 生成Getter and Setter方法。
- 生成toString()方法,方便打印测试数据。
2. 在dao下新建接口DiscussPostMapper
- 一张表对应一个Mapper接口。
- 在Mapper接口中定义与该表有关的增删查改的方法。
3. 在mapper下新建配置文件discusspost-mapper.xml
<!--List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit);-->
<select id="selectDiscussPosts" resultType="DiscussPost">
select
<include refid="selectFields"></include>
from discuss_post
where status != 2
<if test="userId!=0">
and user_id = #{userId}
</if>
order by type desc, create_time desc
limit #{offset}, #{limit}
</select>
- 按照帖子类型排序,0是普通贴,1是置顶帖,倒序排序的话,置顶帖就在前面;如果帖子类型相同,按照创建时间的倒序排序,最新的帖子排在前面。
- 分页用关键字limit实现
4. 测试
@Autowired
private DiscussPostMapper discussPostMapper;
@Test
public void testSelecPosts(){
List<DiscussPost> list = discussPostMapper.selectDiscussPosts(0, 0, 10);
for(DiscussPost post : list){
System.out.println(post);
}
int rows = discussPostMapper.selectDiscussPostRows(0);
System.out.println(rows);
}
二.Service开发
1. 在Service下新建类DiscussPostService(业务组件)
@Service
public class DiscussPostService {
@Autowired
private DiscussPostMapper discussPostMapper;
public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit){
return discussPostMapper.selectDiscussPosts(userId, offset, limit);
}
public int findDiscussPostRows(int userId){
return discussPostMapper.selectDiscussPostRows(userId);
}
}
- 业务组件前要加注解@Service
- 把DiscussPostMapper注入进来,即定义对象discussPostMapper
- 定义两个方法findDiscussPosts和findDiscussPostRows
2. 把文件放入static和template下
- static: css, img, js
- template: site(其他页面), index.html(首页),mail
三.Controller开发
1. 注入两个对象
@Autowired
private DiscussPostService discussPostService;
@Autowired
private UserService userService;
2. getIndexPage方法
- 首先返回帖子集合list
- 然后根据每篇帖子post的用户id,返回该用户的所有信息user。每一对装在一个map里,最终构成一个集合discussPosts
- 将最终要展现的数据,即discussPosts,封装到model中
3. Page类
在entity下新建类Page,用来封装分页的相关信息
四.总结
- index.html文件内容看不懂
- 最终运行报错:[THYMELEAF][http-nio-8080-exec-4] Exception processing template “/index”: An error happened during template parsing (template: “class path resource [templates//index.html]”)
(没能解决,有没有朋友知道问题出在哪里了哇) - Page类中的变量从哪里传进来的