简体   繁体   中英

How can I run custom SQL with Spring Data JDBC without @Query?

Is there a possibility to run some custom SQL query generated via 3rd party tools like eg jOOQ and still benefit from Spring Data JDBC mapping features ie @Column annotations? I don't want to use @Query annotation.

class Model { @Id private Long id; @Column("column") private String prop; }

class MyRepo {
  public Model runQuery() {
    val queryString = lib.generateSQL()
    // run query as if it has been generated by Spring Data JDBC and map
    // results to Model automatically
  }
}

Perhaps JdbcTemplate can solve your problem? Specifically, one of the queryForObject() methods may be of interest since your are requesting a single object:

class MyRepo {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    MyRepo(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }        

    public Model runQuery() {
        val query = lib.generateQuery();
        return jdbcTemplate.queryForObject(query, Model.class);
    }
}

More information and other use cases can be found in the Spring Guide Accessing Relational Data using JDBC with Spring

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