【问题标题】:Perform select of data from multiple tablea using JDBC template使用 JDBCtemplate 从多个表中选择数据
【发布时间】:2017-11-24 03:29:23
【问题描述】:

我需要在我的 Spring Boot Web 应用程序中从我的数据库中按日期进行选择。到目前为止,我所拥有的是一份体育比赛列表以及相应的信息。

问题:我无法弄清楚我的选择查询如何将我的字符串类型(dateFrom = '2017-05-02' 和 dateTo = '2017-05-06')转换为日期,如 '2017-02-12' ?

还有如何在一些有多个日期的比赛中用然后一个日期填充我的 RowMapper。

我的数据库架构:

CREATE TABLE competition ( 
  competition_id integer PRIMARY KEY,
  nom varchar(128) NOT NULL,
); 

CREATE TABLE date ( 
  id integer PRIMARY KEY,
  date_time timestamptz,
  competition_id integer REFERENCES competition (competition_id)
);

Json 数据:

{
    "id": "420",
    "name": "SOCCER",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
        "2016-05-12T05:00:00.000Z"
    ]
},
{
    "id": "220",
    "name": "BASKETBALL",
    "dates": [
        "2016-05-12T03:00:00.000Z"
        "2016-05-12T04:00:00.000Z"
    ]
}

我的比赛班:

public class Competition{
    private int id;
    private String name;
    private String[] dates;
    // setters ... getters
}

我的 RowMapper 类:

public class RowMapper implements RowMapper
{
  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    Competition competition  = new Competition();
    competition.setId(rs.getInt("id"));
    competition.setName(rs.getString("name"));
    competition. // How to fill dates
    return competition;
  }

}

数据选择功能:

private static final String SELECT_STMT =
      " select * from competition INNER JOIN date ON
    + " competition.competition_id = date.competition_id"
    + " WHERE date(date.date_time) BETWEEN ? AND ?"
    ;  

public List<Competition> findByOptionsAll(String dateFrom, String dateTo ){

  List<Competition> competitions = jdbcTemplate.query(SELECT_STMT, new 
     RowMapper(), dateFrom, dateTo);          

    return competitions ;
}

【问题讨论】:

  • 您想将日期保留为String,还是使用Date?在 Java 应用程序中?在数据库中?
  • 不,在 DB 中日期是 timestampz,但我只用 date(...) 提取日期。我还是有更换的麻烦吗? ?通过适当的值。

标签: java spring jdbc


【解决方案1】:

日期转换

现在,您的数据库和域模型中的所有日期都是String。要将字符串转换为日期,您需要 date formatter:

private static final String DATE_FORMAT = "dd-MM-yy";
// parsing date; Note you should handle ParseException
java.util.Date date = new SimpleDateFormat(DATE_FORMAT).parse(dateAsString);
// converting date to string
String dateAsString = new SimpleDateFormat(DATE_FORMAT).format(date);

请注意,SimpleDateFormat 不是线程安全的,因此最好使用static final String DATE_FORMAT 而不是static final DateFormatter

在某些情况下转换日期和时间很棘手(时区呢?java.util.Date vs joda.time vs Java 8 的 LocalDate)但超出了范围。我建议尽可能使用 LocalDate ,因为它是一种没有旧问题的新方法。

映射

您的数据库中有两个实体(竞争和竞争日期),域模型中只有一个类 Competition。很可能,稍后您会想要在比赛日期(布尔完成、取消、分数等)中添加其他信息,因此最好立即创建 CompetitionInstance 类。

因为你有一对多的关系,你必须写一些额外的东西来映射对象。通常这就是像 Hibernate 这样的 ORM 所做的,而不是你。首先,在您的 sql 语句中添加一个“GROUP BY Competition_id”。 然后按照here 的描述使用 RowSetExtractor 而不是 RowMapper:

private static final class CompetitionMapExtractor implements ResultSetExtractor<List<Competition>> {
@Override
public List<Competition> extractData(ResultSet rs) throws SQLException {
  List<Competition> result = new ArrayList<>(rs.getCount());
  int previousCompetitionId = NEVER_EXIST; // normally -1 is good enough
  while (rs.next()) {
     // we have some dates with the same competition_id 
     // dates are grouped thanks to GROUP BY clause        
     if ( rs.getInt("id") != previousCompetitionId) {
       Competition currentCompetition = new Competition(rs.getInt("id"),
                     rs.getString("name");
       /* I prefer constructor initializers "o = new O(propertyValue)"
        instead of snippet "o = new O(); o.setProperty(value)"
       */
       result.add(currentCompetition);
       previousCompetitionId = currentCompetition.getid();
     } else {
       currentCompetition.addDate(new CompetitionInstance(rs.getString("date")));
     }
  }
  return result;
}

我想Competition 有方法public void addDate(String date),它只是将新的 CompetitionInstance 添加到列表中。

更新:

1。 DB 和 MapExtractor 中的列名不同。我更喜欢更改查询:

SELECT c.id, c.name, d.date_time as date
from competition c 
INNER JOIN date d ON c.competition_id = d.competition_id
WHERE date(d.date_time) BETWEEN ? AND ?"

2。我无法重现您在日期方面遇到的问题。很可能你混淆了java.util.Datejava.sql.Datejava.sql.Timestamp——这是一个常见的错误。 answers 已经有很多了,你可能会发现 onethem 有用。

【讨论】:

  • 我没有使用 Hibernate,但是这段代码 List Competitions = jdbcTemplate.query(SELECT_STMT, new RowMapper(), dateFrom, dateTo);仍然导致我错误()(索引列超出限制)。当我添加两个参数时。
  • @DavidEdgar 这是因为在 DB 中有列“timestamptz”,而在我的代码中它称为“date”。更好的方法是更改​​ SELECT 查询
猜你喜欢
  • 2022-12-09
  • 2014-01-05
  • 1970-01-01
  • 2021-02-06
  • 2020-07-04
  • 2016-06-28
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多