广告
返回顶部
首页 > 资讯 > 后端开发 > Python >mybatis中string和date的转换方式
  • 504
分享到

mybatis中string和date的转换方式

2024-04-02 19:04:59 504人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

实体里用的java.util.date,数据库用的是datetime,页面是字符串<input type="date">。将页面标签<input type="dat

实体里用的java.util.date,数据库用的是datetime,页面是字符串<input type="date">。将页面标签<input type="date">的内容添加到数据库

实体


public class BaseInfORMation {
 
    //信息主键
    private String id;
    //信息标题
    private String title;
    //信息类型id(需要在数据字典定义)
    private String typeCode;
    //属性id(需要在数据字典定义)
    private String propertityId;
    //信息可视范围,部门可见或者整个单位可见,值是组织结构的id
    private String scope;
    //内容
    private String content;
    //发布人id
    private String releaseId;
    //是否发布,1发布,0保存
    private Integer released;
    //接收人id,对应tb_base_information_receiver的主键
    private String receiver;
    //创建时间就是发布时间
    
    private Date createDate;
    //更新时间
    
    private Date updateDate;
    //开始时间
    
    private Date beginDate;
    //结束时间
    
    private Date endDate;
    //定时器,规定什么时候发布信息
   
    private Date timer;

。。。。。省略getter和setter


CREATE TABLE `tb_base_information` (
  `id` varchar(48) NOT NULL,
  `title` varchar(128) DEFAULT NULL COMMENT '标题',
  `type_code` varchar(48) DEFAULT NULL COMMENT '类型id(需要在数据字典定义),公告、新闻等',
  `propertity_id` varchar(48) DEFAULT NULL COMMENT '属性id(需要在数据字典定义)',
  `scope` varchar(255) DEFAULT NULL COMMENT '信息可视范围,部门可见或者整个单位可见,值是组织结构的id',
  `content` text COMMENT '内容',
  `release_id` varchar(48) DEFAULT NULL COMMENT '发布人id',
  `released` int(11) DEFAULT NULL COMMENT '是否发送,1发送0保存为草稿',
  `create_date` datetime DEFAULT NULL COMMENT '创建时间',
  `update_date` datetime DEFAULT NULL COMMENT '更新时间',
  `begin_date` datetime DEFAULT NULL COMMENT '信息有效期的起始时间',
  `end_date` datetime DEFAULT NULL COMMENT '信息有效期的结束时间',
  `timer` datetime DEFAULT NULL COMMENT '定时器,指定发送信息的时间',
  `expiry_date` datetime DEFAULT NULL COMMENT '是否永久有效,1是0否',
  `to_top` int(1) DEFAULT NULL COMMENT '信息是否置顶,1置顶,0否',
  `mark_star` int(1) DEFAULT NULL COMMENT '做星标标记用,1在星标公告里显示,0否',
  `receiver` varchar(48) DEFAULT NULL COMMENT '接收人id,对应tb_base_information_receiver的主键',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='信息发布表';

页面


<form name="form" method="post" action="/information/test" enctype="multipart/form-data">  
    类型:<input type="text" name="typeCode" ><br/>
    标题:<input type="text" name="title" ><br/>
    内容:<textarea name="content"  cols="30" rows="10"></textarea><br/>
    创建时间:<input type="date" name="createDate"/><br/>
    更新时间:<input type="date" name="updateDate"/><br/>
    有效期开始时间:<input type="date" name="beginDate"/><br/>
    有效期结束时间:<input type="date" name="endDate"/><br/>
    定时器:<input type="date" name="timer"/><br/>  
    <input type="submit" value="提交"> 
</form>

controller


@RequestMapping("/test")
public String test(BaseInformation baseInformation, httpservletRequest request) throws Exception {
 
    String id = UUID.randomUUID().toString();
    baseInformation.setId(id);
    //baseInformation.setId(UUID.randomUUID().toString().replaceAll("-",""));
    System.out.println("request.getParameter(createDate)" + request.getParameter("createDate"));
 
    Date createDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("createDate"));
    Date updateDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("createDate"));
    Date beginDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("beginDate"));
    Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("endDate"));
    Date timer = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("timer"));
    baseInformation.setCreateDate(createDate);
    baseInformation.setUpdateDate(updateDate);
    baseInformation.setBeginDate(beginDate);
    baseInformation.setEndDate(endDate);
    baseInformation.setTimer(timer);
 
    service.save(baseInformation);
    return "information/test";
}

运行结果


Field error in object 'baseInformation' on field 'createDate': rejected value [2018-11-08]; codes [typeMismatch.baseInformation.createDate,typeMismatch.createDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [baseInformation.createDate,createDate]; arguments []; default message [createDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2018-11-08'; nested exception is java.lang.IllegalArgumentException]
    at org.springframework.WEB.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:117)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.Http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)

修改方法

修改实体

string和date的类型转换失败,此时在实体中,对需要进行转换的类型添加如下注解,实现java.lang.String和java.util.Date之间自动转换


@DateTimeFormat(pattern="yyyy-MM-dd")//页面写入数据库时格式化   
@JSONField(format="yyyy-MM-dd")//数据库导出页面时json格式化

修改contoller

既然java.lang.String和java.util.Date之间可以自动转换了,后台就不需要通过request获取参数来进行转换,可以将红方格中的注释掉

依赖添加

1.注解@JsonFormat


      <!--JsonFormat-->
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.8</version>
        </dependency>
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
 
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

2.注解@DateTimeFormat

@DateTimeFormat的使用和@jsonFormat差不多,首先需要引入是spring还有jodatime,spring我就不贴了


  <!-- joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.3</version>
        </dependency>

关于@DateTimeFormat和@JsonFormat还可以参考https://www.jb51.net/article/176268.htm

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: mybatis中string和date的转换方式

本文链接: https://www.lsjlt.com/news/131994.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作