java - 将 SQL 更改为条件或 HQL

标签 java mysql sql spring hibernate

更改此查询

SELECT 
    * 
FROM 
    Authors 
WHERE 
    born <= DATE_ADD(CURDATE(), interval -55 year) 

到条件查询。 这是我的糟糕尝试

 List<Book> bookList = session.createQuery("from Book where born <= DATE_SUB(current_date , INTERVAL 10 year)").list();

最佳答案

问题是 Spring 将请求作为 json 对象发送,然后尝试将它们转换为您传入的模型。在本例中,“Author”将birth 定义为 Date,但发送的字符串不是没有采用要转换为日期的正确日期格式。

有两种不同的方法可以处理这个问题。

1) 创建一个 Author POJO,将日期定义为字符串,然后在指定日期格式时手动转换为 Author 实体

2) 创建一个 Date desearlizer 类,该类将获取字符串并将其反earlize 为指定字段的日期:

这是使用 jackson 库:

public class DateTimeStampDeserializer extends JsonDeserializer<Date> {

  private static final String DEFAULT = "MM/dd/yyyy";
  private static final String EXPANDED = "MM/dd/yyyy HH:mm:ss z";
  private static final String EXPANDED_WITH_TIMEZONE = "MMM d, yyyy HH:mm:ss z";
  private static final String EXPANDED_WITH_AM_PM = "MMM d, yyyy h:mm:ss a";

  private static final String FORMAT_1 = "yyyy-dd-MM";
  private static final String FORMAT_2 = "yyyy/dd/MM";
  private static final String FORMAT_3 = "yyyy.dd.MM";
  private static final String FORMAT_4 = "yyyyddMM";

  private static final String[] formats = new String[] {
      DEFAULT,
      EXPANDED,
      EXPANDED_WITH_TIMEZONE, 
      EXPANDED_WITH_AM_PM,
      FORMAT_1,
      FORMAT_2,
      FORMAT_3,
      FORMAT_4
  };

  private static final Integer[] styles = new Integer[] {
      SimpleDateFormat.LONG,
      SimpleDateFormat.FULL,
      SimpleDateFormat.MEDIUM,
      SimpleDateFormat.SHORT
  };

  @Override
  public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String value = p.getText();

    Date date = null;
    //First try to see if the value can be parsed into a long
    try {
      date = new Date(Long.parseLong(value));
      return date;
    } catch (Exception ex) { }

    //Next iterate over the built in styles to see if it can be converted
    for (Integer style: styles) {
      date = formatDate(style, value);
      if (date != null) {
        return date;
      }
    }

    //Lastly iterate over the custom styles specified in format to see if it can be converted
    for (String fmt : formats) {
      date = formatDate(fmt, value);
      if (date != null) {
        return date;
      }
    }

    //Return null if date format can't be converted
    return null; 
  }

  /**
   * Convert a string value to a date object
   * @param format The format to use in reference to the source 
   * @param source the source to convert
   * @return Date object if the conversion was success; null otherwise
   */
  private static Date formatDate(String format, String source) {
    try {
      return new SimpleDateFormat(format).parse(source);
    } catch (Exception ex) {
      return null;
    }
  }

  /**
   * Convert a string value to a date object using SimpleDateFormats 
   * built in styles
   * @param style The style to use
   * @param source the source to convert
   * @return Date object if the conversion was success; null otherwise
   */
  private static Date formatDate(Integer style, String source) {
    try {
      return SimpleDateFormat.getDateInstance(style).parse(source);
    } catch (Exception ex) {
      return null;
    }
  }
}

然后在您的实体中使用它,您只需简单地做

@JsonDeserialize(using=DateTimeStampDeserializer.class)
@Column(name = "born")
@Temporal(TemporalType.DATE)
private java.util.Date born;

Jackson 库可以通过 Maven 添加到您的项目中(如果使用 Maven)

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.6</version>
</dependency>


<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version>
</dependency>

关于java - 将 SQL 更改为条件或 HQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363844/

相关文章:

java - 使用get方法时不同的实例变量显示相同的值

mysql - 无法在 store 方法中传入数据

mysql - Spring-Boot、mySQL、使用 select

javascript - 通过 PHP 将数据从 SQL 数据库移动到 JavaScript 中的数组

php - 创建表并向其中添加数据不起作用

sql - 是否可以使用行号和列号进行SQL更新?

java - 如果仅通过测试,则 testng 中的 @AfterClass/Suite

java - 在 JButton 32x32 上设置 1 个或 2 个字符的文本

java - Facebook AnE Android : Login Activity - . ApiException:代码 1:发生未知错误

mysql - 从另一个表 `title`引用 `title`