mybatis + 首页开发

起因

  1. 其实这个看了半天也不没啥可说的,就是些零零散散的配置,不过还是记录一下吧;况且只是稍微会用,可不能称之为会用啊;

mybatis

  • 这货是java的一个持久化框架;我这里用的是mybatis-spring-boot-starter 不知道和只使用mybatis有啥区别不;
spring.datasource.url=jdbc:mysql://localhost:3306/wenda
spring.datasource.data-username=root
spring.datasource.data-password=86271325
mybatis.config-location=classpath:mybatis-config.xml
  • 让我们先看看java的项目架构
    首先是 mvc,实体+控制类+页面; 数据又需要从数据库中来,所以控制类还要持有服务类,服务类又要持有DAO类;这样整体的架构就出来了;

  • DAO + Mybatis

@Mapper
@Component
public interface QuestionDAO {
    String TABLE_NAME = " question ";
    String INSERT_FIELDS = " title, content, created_date, user_id, comment_count ";
    String SELECT_FIELDS = " id, " + INSERT_FIELDS;

    /**
     * 通过mybatis 的注解书写的DAO,减少了许多代码<br>
     * 一定要注意string之间的空格,通过#{}的方式可以直接取得对象中的属性<br>
     * 一定要注意#{}内是字段名字
     * @param question 问题对象
     * @return  int
     */
    @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELDS,
            ") values (#{title},#{content},#{createdDate},#{userId},#{commentCount})"})
    int addQuestion(Question question);

    /**
     * 这个不是通过注解的方式,而是通过xml来实现的<br>
     * Param注解 表示需要传过去的参数,真正的sql语句在xml中定义
     * @param userId    用户Id
     * @param offset    开始位置
     * @param limit     限制
     * @return
     */
    List<Question> selectLatestQuestions(@Param("userId") int userId, @Param("offset") int offset,
                                         @Param("limit") int limit);

}
  • 基于xml的数据库操作
    一定要将xml放在resource的同包中
<mapper namespace="cn.colining.dao.QuestionDAO">
    <sql id="table">question</sql>
    <sql id="selectFields">id, title, content, comment_count,created_date,user_id
    </sql>
    <select id="selectLatestQuestions" resultType="cn.colining.model.Question">
        SELECT
        <include refid="selectFields"/>
        FROM
        <include refid="table"/>

        <if test="userId != 0">
            WHERE user_id = #{userId}
        </if>
        ORDER BY id DESC
        LIMIT #{offset},#{limit}
    </select>
</mapper>

ViewObject

  • 这个其实就是为了方便传值,所以model添加对象时,只需要将viewobject整个扔进去就行了
    /**
     * 通过model 将vos 传递给页面,进行首页展示
     * @param model model
     * @return  页面
     */
    @RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET})
    public String index(Model model) {
        List<ViewObject> vos = getViewObjects(0,0,10);
        model.addAttribute("vos", vos);
        return "index";
    }

freemarker 日期

我们可以通过下面这种方式从freemarker中获取对象

${vo.user.id}

日期有点搞怪,因为定义是util的日期类,所以需要声明格式才行

${vo.question.createDate?string("yyyy-MM-dd HH:mm")}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值