简体   繁体   English

如何在不使用 nativeQuery 的情况下在 JPA 上转换它?

[英]How can I convert this on JPA without using nativeQuery?

on my database I have a column where ack_date_time is stored(but in string), Im not the one who start this model and he saves the date on string on gmt example: Tue Aug 04 16:58:27 GMT+08:00 2015 , now we have large amount of data so I dont want to change it as date field as much as possible.在我的数据库中,我有一列存储 ack_date_time(但在字符串中),我不是启动此模型的人,他将日期保存在 gmt 示例中的字符串上: Tue Aug 04 16:58:27 GMT+08:00 2015 ,现在我们有大量数据,所以我不想尽可能地将其更改为日期字段。 how can I change this query statement on jpa without using native query?如何在不使用本机查询的情况下更改 jpa 上的此查询语句? I manage to order by it on mysql but not on jpa.我设法在 mysql 上通过它订购,但不在 jpa 上订购。 im a little bit new to it.我对它有点陌生。 thanks in advance.提前致谢。

select *, STR_TO_DATE(CONCAT(SUBSTR(ack_date_time,1,20),SUBSTR(ack_date_time,31,34)),'%W %M %D %H:%i:%s %Y') as acktime from DEMI order by acktime desc;

If I understood correctly, the DB level data type of ack_date_time column is VARCHAR , isn't it?如果我理解正确, ack_date_time列的数据库级别数据类型是VARCHAR ,不是吗?

If it is, you can try AttributeConverter , see example here: http://www.thoughts-on-java.org/jpa-21-how-to-implement-type-converter/如果是,您可以尝试AttributeConverter ,请参见此处的示例: http : //www.thoughts-on-java.org/jpa-21-how-to-implement-type-converter/

You can define your own attribute converter as follows:您可以按如下方式定义自己的属性转换器:

@Converter
public class DemiDateConverter implements AttributeConverter<Timestamp, String> {

 /**
  * Convert Timestamp object to a String.
  */
 @Override
 public String convertToDatabaseColumn(Timestamp ts) {
  // here you should implement the logic which converts the Timestamp to DB compatible format
 }

 /**
  * Convert a String to a Timestamp object.
  */
 @Override
 public Timestamp convertToEntityAttribute(String str) {
  // here you should implement the logic that parses string from DB and transforms it to regular timestamp.
 }
}

Then you need to use the converter in your entity class:然后你需要在你的实体类中使用转换器:

@Entity
public class DemiEntity {

   // id and other fields

   @Column(name = "ack_date_time")
   @Convert(converter = DemiDateConverter.class)
   private Timestamp acktime;

   // getters and setters
   ...
}

BTW, have you already tried to use JPA entity for DEMI table?顺便说一句,您是否已经尝试将 JPA 实体用于DEMI表?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM