简体   繁体   中英

Using jdbcTemplate.query with parameters

I have 3 tables in Database Lecture--< LectureGroups >-- Groups. And I want to get schedule for a certain group on a certain day. I try to do it in this way:

@Repository
public class Schedule {

    private static final String GET_GROUP_DAY_SCHEDULE = "SELECT * FROM LECTURES " +
            "INNER JOIN LECTUREGROUPS ON LECTURES.ID = LECTUREGROUPS.LECTUREID " +
            "INNER JOIN GROUPS ON GROUPS.ID = LECTUREGROUPS.GROUPID " +
            "WHERE GROUPID = :GROUPID AND DATE = :DATE";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Lecture> getGroupDayLectures(int groupId, LocalDateTime dateTime) {
        MapSqlParameterSource parameters =  new MapSqlParameterSource()
                .addValue("groupid", groupId)
                .addValue("date", dateTime);
        return jdbcTemplate.query(GET_GROUP_DAY_SCHEDULE, new BeanPropertyRowMapper<>(Lecture.class), parameters);
    }
}

But I get an exception in query raw

Caused by: org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use.

How I can fix it? I also used variant with

private static final String GET_GROUP_DAY_SCHEDULE = "SELECT * FROM LECTURES " +
            "INNER JOIN LECTUREGROUPS ON LECTURES.ID = LECTUREGROUPS.LECTUREID " +
            "INNER JOIN GROUPS ON GROUPS.ID = LECTUREGROUPS.GROUPID " +
            "WHERE GROUPID = ? AND DATE = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Lecture> getGroupDayLectures(int groupId, LocalDateTime dateTime) {
        return jdbcTemplate.query(GET_GROUP_DAY_SCHEDULE, new Object[]{groupId, dateTime}, new BeanPropertyRowMapper<>(Lecture.class));
    }

and it works but return only 1 Lecture in list (it must be 3)

There is a signature with parameters in the jdbcTemplate class:

public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args)

So it is very easy to use it in this way

private static final String GET_GROUP_DAY_SCHEDULE = "SELECT * FROM LECTURES " +
            "INNER JOIN LECTUREGROUPS ON LECTURES.ID = LECTUREGROUPS.LECTUREID " +
            "INNER JOIN GROUPS ON GROUPS.ID = LECTUREGROUPS.GROUPID " +
            "WHERE GROUPID = ? AND DATE = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Lecture> getGroupDayLectures(int groupId, LocalDate date) {
        return jdbcTemplate.query(GET_GROUP_DAY_SCHEDULE, new BeanPropertyRowMapper<>(Lecture.class), groupId, date);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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