简体   繁体   中英

How to make an SQL Query in Spring Boot that returns an Integer at runtime?

I've been trying to figure out a way to make an SQL Query in my spring boot application and have it return an integer type to be used later. I'll be upfront and say I have no idea how Spring Boot works and am trying to get a quick app running for work, so please excuse my ignorance.

Currently what I'm trying to do is have a user enter in details into a webpage and have that info be sent as an SQL request to a server, then return the result as an integer that I can display on a results page. I have the webpage components of the program working but I can't figure out how to get an SQL query sent. I've scoured the internet for answers but all the questions/answers I've been finding are for Entity models, mappings, or etc. I'm not trying to re-create the database objects locally in my program I'm trying to do an SQL query in the background get a result and display it. How would I do that?

Currently this is what I have for the function, but when I try to use it I get a null pointer exception for the jdbcTemplate .

@Autowired
private JdbcTemplate jdbcTemplate;


public int getTotalResults(String startDate, String endDate)
{

    String sql = "SELECT COUNT (DISTINCT object) FROM place WHERE property >= '";
    sql += Utility.parseDateToQueryDate(startDate);
    sql += "' AND planning_test_case.modified < '";
    sql += Utility.parseDateToQueryDate(endDate);
    sql += "'";

    if(jdbcTemplate != null) return (int)jdbcTemplate.queryForObject(sql, int.class);
    else return -1;
}

Main Class:

@SpringBootApplication
public class Application{

    public static void main(String[] args) throws Exception {
         SpringApplication.run(ArtifactCountingToolApplication.class, args);
    }
}

So from the function what I want to do is get the count of objects from the database given the dates and return the result as an integer. There is something probably really simple I'm forgetting but I'm at a loss as to what to do. There is more background classes for the web controller but I don't think its relevant to this post.

You need to configure datasource first. For instance for H2 database:

spring.datasource.url=jdbc:h2:file:C:/temp/test 
spring.datasource.username=sa 
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Read more in official documentation - https://docs.spring.io/spring-boot/docs/2.1.11.RELEASE/reference/html/boot-features-sql.html

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