简体   繁体   中英

Execute stored procedures with multiple parameters and map ResultSet to non-entity class using spring data jpa

We moved to spring data JPA recently (using Spring-boot 2.1.5-RELEASE) and in need to execute stored procedures with multiple input parameters and map to the non-entity POJO (I will be setting the value to the entity class while saving the objects). Can anyone please provide an example/description on how can it be achieved? I didn't get much out of documentation or may be I missed.

Any help would be appreciated.

The most direct, and simplest solution is to user SimpleJDBCCall and forget about JPA for this data resource. The documentation covers parameters extensively.

Something like this will work:

public class MyDao implements SomeDao {

    private JdbcTemplate jdbcTemplate;
    private SimpleJdbcCall procReadStuff;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
        this.procReadStuff = new SimpleJdbcCall(dataSource)
                .withProcedureName("my_procedure");
    }

    public void readStuff(Long id) {
        SqlParameterSource in = new MapSqlParameterSource()
                .addValue("in_id", id);
        Map out = procReadStuff.execute(in);
        Stuff stuff = new Stuff();
        stuff.setId(id);
        stuff.setSomeString((String) out.get("out_some_string"));

        // ...do something with Stuff POJO
    }

}

This sample was pulled/modified from the sample in the docs: Documentation

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