1

我正在尝试在我的 Spring JdbcDaoSupport 类中创建一个“从插入中选择”,并且无法弄清楚如何从选择语句中获取数据并将其返回。

我的 EventJdbcTemplate(我的 DaoImpl):

@Service
public class EventJdbcTemplate extends JdbcDaoSupport implements EventDao {

private static final Logger LOGGER = Logger.getLogger(EventJdbcTemplate.class);

private static final String SQL_INSERT_EVENT = "SELECT EVENT_ID FROM FINAL TABLE " +
        "(INSERT INTO EBT10DBB.SB0401T0 (EVENT_NAME, HOST_NAME, USER_ID) " +
        "VALUES(?, ?, \'EMP0321\'))";

@Autowired
public EventJdbcTemplate(DataSource pDataSource) {
    super.setDataSource(pDataSource);
}


@Override
public Integer createEvent(EventBean pEventBean) { //(Integer id, String eventName)
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Entering create(Event event) of EventJDBCTemplate.");
    }
    // This SQL works, but is for an INSERT only. 
    /*this.getJdbcTemplate().query(SQL_INSERT_EVENT, new Object[]{
        pEventBean.getEventName(),
        pEventBean.getHostName()
    });*/

    final List eventList = this.getJdbcTemplate().query(SQL_INSERT_EVENT, new Object[]{
        pEventBean.getEventName(),
        pEventBean.getHostName()
        }, new EventRowMapper()
    );

    Event event = null;
    for (int i = 0; i < eventList.size(); i++) {
        event = (Event)eventList.get(i);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Exiting create(Event event) of EventJDBCTemplate.");
    }
    //return statement -- should return either the entire "pEventBean", or
    //just the unique key, "EVENT_ID".
            return event.getId();
}

EventRowMapper 类(不确定我是否需要这个来进行选择):

public class EventRowMapper implements RowMapper<Event> {

    @Override
    public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
        final EventBuilder event = new EventImpl.EventBuilder();
        event.setId(rs.getInt("EVENT_ID"));
        event.setEventName("EVENT_NAME");
        event.setHostName("HOST_NAME");
        return event.build();
    }

}

所以我的目标是返回一个整数值,它是从 INSERT SQL 创建的唯一键 (EVENT_ID)。

4

1 回答 1

0

您可以使用 Spring 提供的 SimpleJdbcInsert 来取回生成的密钥,请参阅 Spring 部分提供的以下文档

13.5.2 使用 SimpleJdbcInsert 检索自动生成的密钥

这是链接

于 2013-07-25T14:09:15.720 回答