Home  >  Article  >  Database  >  SSH注解插入数据库时间类型 时分秒丢失的问题

SSH注解插入数据库时间类型 时分秒丢失的问题

WBOY
WBOYOriginal
2016-06-07 15:48:231607browse

做一个CS结构的应用时,从客户端传一个时间的字符串到服务器端,结果发现时分秒丢失了。客户端是Android开发的,服务器端是SSH注解做的。 于是在百度中找了各种答案,第一种是说要在实体类的get方法上面添加@Temporal(TemporalType.TIMESTAMP)注解,果断添加

做一个CS结构的应用时,从客户端传一个时间的字符串到服务器端,结果发现时分秒丢失了。客户端是Android开发的,服务器端是SSH注解做的。

于是在百度中找了各种答案,第一种是说要在实体类的get方法上面添加@Temporal(TemporalType.TIMESTAMP)注解,果断添加上去,结果又报了错误。

<span style="font-size:18px;">org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property: com.hpsvse.traffic.entity.Income.incomeDate</span>

错误原因是说@Temporal 只支持java.util.Date 或 java.util.Calendar的参数。便又把返回值为java.sql.Timestamp的类型换成java.util.Date的类型,结果是虽然没报错,但是时分秒还是没有插入到数据库。

………………

纠结很久,突然眼前一亮,发现是不是长度设置不够长或者是我传入的日期格式有问题,因为我之前传的是 2015-03-24 10:22(缺少了秒),变将两种可能都尝试了一下:

第一种是吧length的属性值改为了50,发现并没有任何效果,如下:

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "income_date", length = 50)
然后,尝试第二种:

把之前请求服务器的时间字符串2015-03-24 10:22在后面补了两个零,变成2015-03-24 10:22:00标准的yyyy-MM-dd HH-mm-ss的格式,结果奇迹就出现了。总结起来,其实之前都是一场闹剧,就是因为在时间后面少补了两个零。


最后在总结一下,让数据插入数据库其实很简单:

第一种方法,定义一个java.util.Date的类型,然后在生成的get方法上面加上一句@Temporal(TemporalType.TIMESTAMP)的注解,然后把属性length的长度改的长一点,感觉19就够用了。代码如下:

<span style="white-space:pre">	</span>private Date incomeDate;
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "income_date", length = 19)
	public Date getIncomeDate() {
	<span style="white-space:pre">	</span>return this.incomeDate;
	}

	public void setIncomeDate(Date incomeDate) {
		this.incomeDate = incomeDate;
	}
 第二种方法,直接定义一个java.sql.Timestamp的类型,如下:
<span style="white-space:pre">	</span>private Timestamp incomeDate;
	
	@Column(name = "income_date", length = 19)
	public Timestamp getIncomeDate() {
		return this.incomeDate;
	}

	public void setIncomeDate(Timestamp incomeDate) {
		this.incomeDate = incomeDate;
	}
特别注意的是,传入的值一定要是标准的yyyy-MM-dd HH-mm-ss(如:2015-03-24 10:22:00)的格式,不能缺少任何一部分,要不然时分秒还是会丢失哦~

在此,非常感谢另一位牛人的博客指点,在此受小弟一拜了。http://blog.sina.com.cn/s/blog_82a09f100101a76j.html

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn