I want to execute sql statement inside my spring boot controller class with out defining any method in the jpa repository. The statement i want to use is
SELECT UUID();
This statement is database related and is not associated with a particular entity.
It would be nice if any one can provide solution for the execution of the above statement via
update
controller:
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping(value = "/UUID", method = RequestMethod.GET)
public ResponseEntity<String> getUUID() {
String uuid = getUUID();
return buildGuestResponse(uuid);
}
public String getUUID(){
UUID uuid = (UUID)jdbcTemplate.queryForObject("select UUID()", UUID.class);
return uuid.toString();
}
In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.
The JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSet s and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.
You can use JdbcTemplate in your code.
The bean you will need in your configuration class is:-
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource)
{
return new JdbcTemplate(dataSource);
}
And the code to run the query is:-
@Autowired
private JdbcTemplate JdbcTemplate;
public String getUUID(){
UUID uuid = (UUID)jdbcTemplate.queryForObject("select UUID()", UUID.class);
return uuid.toString();
}
or may be like this:-
public UUID getUUID(){
UUID uuid = (UUID)jdbcTemplate.queryForObject("select UUID()", UUID.class);
return uuid;
}
This is generally architecturally bad design to execute any SQL (do any persistence) on presentation layer (controller or view) in JEE applications.
The best option is make controller to use service layer, when service layer calling the persistence layer for: obtaining, saving or updating data.
In any case, you can use Spring Data JDBC. Something like:
import org.springframework.jdbc.core.JdbcTemplate;
....
UUID uuid = (UUID)jdbcTemplate.query("SELECT UUID()", UUID.class);
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With