使用JDBC模板

时间:2017-06-21 09:44:24

标签: java spring jdbc

我需要在我的春季启动webapp中从我的数据库中按日期选择。到目前为止我所拥有的是一系列体育比赛和各自的信息。

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

Alos如何在一些比赛中使用更多然后一个日期来填充我的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 ;
}

1 个答案:

答案 0 :(得分: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课程是个好主意。< / p>

由于你有一对多的关系,你必须写一些额外的东西来映射对象。通常情况下,像Hibernate这样的ORM会对你造成什么影响。首先,添加&#39; GROUP BY competition_id&#39;在你的sql语句中。 然后使用RowSetExtractor而不是RowMapper,如here所述:

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,您可能会发现one them有用。