Saving Date and Time in MySQL in Hibernate Spring Boot - mysql

I am trying to save date and times in mysql in Spring Boot. My classes are
ReservationController.java
package com.Test.controller;
import com.Test.service.ReservationService;
import com.Test.model.reservation.Reservation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Map;
#RestController
#RequestMapping("/api")
public class ReservationController {
#Autowired
private ReservationService reservationservice;
// Create a new reservation
#RequestMapping(value = "/me/reservations", method = RequestMethod.POST)
public ResponseEntity<Reservation> createReservation(
#Valid #RequestBody Reservation reservation,
UriComponentsBuilder ucb){
int newReservationId = reservationservice.createReservation(reservation);
HttpHeaders newHeaders = new HttpHeaders();
newHeaders.setLocation(ucb.path("/api/me/reservations/").path(String.valueOf(newReservationId)).build().toUri());
return new ResponseEntity<Reservation>(
reservation, headers, HttpStatus.CREATED);
}
}
Reservation.java
package com.Test.model.reservation;
import javax.persistence.*;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.sql.Time;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
#Entity(name="Reservation")
#Table(name="reservation")
public class Reservation{
#Id
#Column(name="reservation_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int reservationId;
#Column(name="date_reserved")
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
#Temporal(TemporalType.DATE)
#NotNull
private Date dateReserved;
#Column(name="time_reserved_start")
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
#Temporal(TemporalType.TIME)
#NotNull
private Date timeReservedStart;
#Column(name="time_reserved_end")
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="HH:mm:ss")
#Temporal(TemporalType.TIME)
#NotNull
private Date timeReservedEnd;
public Reservation(){
}
public Reservation(Date dateReserved,
Date timeReservedStart,
Date timeReservedEnd){
this.dateReserved = dateReserved;
this.timeReservedStart = timeReservedStart;
this.timeReservedEnd = timeReservedEnd;
}
public Integer getReservationId(){
return this.reservationId;
}
public void setDateReserved(Date dateReserved){
this.dateReserved = dateReserved;
}
public Date getDateReserved(){
return this.dateReserved;
}
public void setTimeReservedStart(Date timeReservedStart){
this.timeReservedStart = timeReservedStart;
}
public Date getTimeReservedStart(){
return this.timeReservedStart;
}
public void setTimeReservedEnd(Date timeReservedEnd){
this.timeReservedEnd = timeReservedEnd;
}
public Date getTimeReservedEnd(){
return this.timeReservedEnd;
}
}
ReservationRepository.java
package com.Test.repository;
import com.davide.Ubgrill.model.reservation.Reservation;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
#Repository("reservationRepository")
public interface ReservationRepository extends JpaRepository<Reservation, Integer>{}
ReservationService.java
package com.Test.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Test.model.reservation.Reservation;
import com.Test.repository.ReservationRepository;
#Service
public class ReservationService{
#Autowired
private ReservationRepository reservationrepository;
public int createReservation(Reservation reservation){
Reservation newReservation = reservationrepository.save(reservation);
reservationrepository.flush();
return newReservation.getReservationId();
}
}
schema.sql
create table reservation (
reservation_id integer not null AUTO_INCREMENT,
date_reserved date not null,
time_reserved_start time not null,
time_reserved_end time not null,
primary key(reservation_id)
);
application.properties
spring.datasource.url=jdbc:mysql://localhost/ubgrillData?useSSL=false&useLegacyDatetimeCode=false
spring.datasource.username=made
spring.datasource.password=tools
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jackson.serialization.indent_output=true
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
server.port=9090
server.ssl.enabled=false
management.port=8500
management.security.enabled=false
TestApplication.java
package com.Test;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestApplication {
#PostConstruct
void setUTCTimezone(){
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Everytime I save the the date, it saves in UTC but it always saves one day earlier. These are the results of my previous tries:
This image is my making a request to the api with httpie.
This image is Hibernate generated trace.
This image is what is saved in mysql.
My questions is thus:
How do I solve this with java.util.Date/java.sql.Date? I have parts of the api that uses it (mainly jwt autentication) that works? Thanks.

Thanks to #DipakThoke and #Patrick. The answer is to add the timezone to the json format annotation.

Related

Why does my method with #Query to perform a PostMapping or save me generate an error type: java.sql.SQLException: Not a navigable ResultSet

I am trying to perform a CRUD with JPA and mysql through #Query, for this in my database I have a stored procedure that registers me in a table.
When I hit the service from the postman, it generates a 500 Internal Server Error and in the console of my IDEA it responds with the error:
java.sql.SQLException: Create breakpoint Not a navigable ResultSet.
I leave here the complete flow of what I am doing, from the database to the controller
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_ticket_procedure`( IN codigo VARCHAR(45),
IN user_id int,
IN cost float,
IN seats_amount int,
IN laggage_amount int,
IN total_seats_amount int,
IN driver_id int
)
BEGIN
INSERT INTO tickets (code, user_id, cost, seats_amount, laggage_amount, total_seats_amount, driver_id)
values(codigo, user_id, cost, seats_amount, laggage_amount, total_seats_amount, driver_id );
END
In my application I have two DTOs:
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Getter
#Setter
#Entity
public class Tickets{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer ticket_id;
private String code;
private Integer driver_id;
private Integer user_id;
private Float cost;
private Integer seats_amount;
private Integer laggage_amount;
private Integer total_seats_amount;
}
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
#Getter
#Setter
#Entity
public class Users {
#Id
private Integer user_id;
private String complete_name;
private String mail;
private String password;
private String number;
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="user_id")
private List<Tickets> ticketsList;
}
The relationship is that a user can have many tickets
import com.terminals.demo.dto.Tickets;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface TicketsRepository extends JpaRepository<Tickets, Integer> {
#Query(value = "{call insert_ticket_procedure(:code, :driver_id, :user_id, :cost, :seats_amount, :laggage_amount, :total_seats_amount)}", nativeQuery = true)
void insertTickets(
#Param("code")String code,
#Param("driver_id")Integer driver_id,
#Param("user_id")Integer user_id,
#Param("cost")Float cost,
#Param("seats_amount")Integer seats_amount,
#Param("laggage_amount")Integer laggage_amount,
#Param("total_seats_amount")Integer total_seats_amount
);
}
This repository is called by a implementation or "service" that implements an interface
import com.terminals.demo.Repository.TicketsRepository;
import com.terminals.demo.dto.Tickets;
import com.terminals.demo.interfaces.ITickersImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class TicketsImpl implements ITickersImpl {
#Autowired
private TicketsRepository ticketsRepository;
#Override
public void saveTickets(Tickets tickets) {
ticketsRepository.insertTickets(tickets.getCode(),tickets.getDriver_id(),tickets.getUser_id(), tickets.getCost(),tickets.getSeats_amount(), tickets.getLaggage_amount(),tickets.getTotal_seats_amount());
}
}
And the controller:
import com.terminals.demo.dto.Tickets;
import com.terminals.demo.interfaces.ITickersImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/terminals")
public class TicketsController {
#Autowired
ITickersImpl iTickers;
#PostMapping("/addticket")
public ResponseEntity<?> insertTicket(#RequestBody Tickets tickets){
iTickers.saveTickets(tickets);
return new ResponseEntity<>("Registro Exitoso", HttpStatus.CREATED);
}
}
My request:
"code": "sdf23f",
"driver_id": 1,
"user_id": 2,
"cost": 23.0,
"seats_amount": 20,
"laggage_amount": 2,
"total_seats_amount": 2
}```

Spring - can't save an entity with CRUD Repository

I am making simple program that have to get some info from OpenWeatherMap API and save it in MySQL database:
package com.example.restTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
package com.example.restTemplate.Model;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
#NoArgsConstructor
#AllArgsConstructor
#Entity
#javax.persistence.Table(name="Weather")
#Getter
#Setter
#ToString
public class WeatherScore {
#Id
private int id;
private String city;
private double temperature;
private int pressure;
private long currentDate;
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface WeatherCRUDRepository
extends CrudRepository<WeatherScore, Long> {
WeatherScore save (WeatherScore score);
}
package com.example.restTemplate.Controller;
import com.example.restTemplate.Model.WeatherScore;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Random;
#RestController
public class ConsumeWebService {
#Autowired
RestTemplate restTemplate;
WeatherCRUDRepository repository;
ApplicationContext context;
#RequestMapping(value = "/weather")
public void printWeather() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String text = restTemplate.exchange("http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=mykey",
HttpMethod.GET, entity, String.class).getBody();
int pressureStartIndex = text.indexOf("pressure")+10;
int pressureEndIndex = text.indexOf(",", pressureStartIndex);
int tempStartIndex = text.indexOf("temp")+6;
int tempEndIndex = text.indexOf(",", tempStartIndex);
int pressure = Integer.parseInt(text.substring(pressureStartIndex, pressureEndIndex));
double temperature = Double.parseDouble(text.substring(tempStartIndex, tempEndIndex));
WeatherScore score = new WeatherScore();
score.setCity("London");
score.setPressure(pressure);
score.setTemperature(temperature);
Random generator = new Random();
score.setId(generator.nextInt(1000));
score.setCurrentDate(System.currentTimeMillis());
WeatherCRUDRepository repo = context.getBean(WeatherCRUDRepository.class);
repository.save(score);
}
}
When i tap http://localhost:8080/weather i get an error:
Cannot invoke
"org.springframework.context.ApplicationContext.getBean(java.lang.Class)"
because "this.context" is null
Blockquote
How i could fix that?
You have to autowire all the beans within controller, like so:
#Autowired
RestTemplate restTemplate;
#Autowired
WeatherCRUDRepository repository;
#Autowired
ApplicationContext context;

Upload excel file content to mysql using Spring boot and UI

I'm trying to upload excel file content to mysql using Spring boot with the help of upload file UI. Need help with that.
But i'm facing Whitelabel Error Page. I've tried couple of things but no luck yet.
Project View
ReadFileApplication.java
package com.springboot.file.parsefiles;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages= {"com.springboot.file.parsefiles.controller"})
#SpringBootApplication
#Component
public class ReadFileApplication {
public static void main(String[] args) {
SpringApplication.run(ReadFileApplication.class, args);
}
}
ReadFileConrtroller.java
package com.springboot.file.parsefiles.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.springboot.file.parsefiles.model.User;
#RestController
public class ReadFileController
{
#Autowired private ReadFileService readFileService;
#GetMapping(value="/ ")
public String home(Model model)
{
model.addAttribute("user", new User());
List<User> users = ReadFileService.findAll();
model.addAttribute("users", users);
return "view/users";
}
#PostMapping(value="/fileupload")
public String uploadFile(#ModelAttribute User user, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(user.getFile());
return "redirect:/";
}
}
ReadFileRepository.java
package com.springboot.file.parsefiles.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.springboot.file.parsefiles.model.User;
#Repository
public interface ReadFileRepository extends CrudRepository<User, Long>
{
}
ReadFileService.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
public interface ReadFileService
{
List<User> findAll = null;
static List<User> findAll()
{
return null;
}
boolean saveDataFromUploadFile(MultipartFile file);
}
ReadFileServiceImpl.java
package com.springboot.file.parsefiles.service;
import java.util.List;
import com.springboot.file.parsefiles.service.ReadFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.file.parsefiles.model.User;
import com.springboot.file.parsefiles.repository.ReadFileRepository;
#Service
#Transactional
public class ReadFileServiceImpl implements ReadFileService
{
#Autowired private ReadFileRepository readFileRepository;
public List<User> findAll()
{
return (List<User>) readFileRepository.findAll();
}
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
#SuppressWarnings("unused")
boolean isFlag = false;
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if(extension.equalsIgnoreCase("json"))
{
isFlag = realDataFromJson(file);
}else if(extension.equalsIgnoreCase("csv"))
{
isFlag = realDataFromCsv(file);
}
return false;
}
private boolean realDataFromCsv(MultipartFile file)
{
return false;
}
private boolean realDataFromJson(MultipartFile file)
{
return false;
}
}
Applicatiopn.properties
spring.datasource.url = jdbc:mysql://localhost:3306/sampledatabase
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=500MB
Edit:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field readFileService in com.springboot.file.parsefiles.controller.ReadFileController required a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.springboot.file.parsefiles.service.ReadFileService' in your configuration.
Update your controller as below
#PostMapping(value="/fileupload")
public String uploadFile(#RequestParam MultipartFile file, RedirectAttributes redirectAttributes)
{
#SuppressWarnings("unused")
boolean isFlag = readFileService.saveDataFromUploadFile(file);
return "redirect:/";
}
Next i used apache-poi library to convert excel file to list of model object in service class. So my service method is as below
#Autowired
private IPoiji poijiImpl;
#Override
public boolean saveDataFromUploadFile(MultipartFile file) {
List<UserDTO> uploadedUserList = = poijiImpl.fromExcel(file.getOriginalFilename(), file.getInputStream(),UserDTO.class);
// here i can call repository methods to save data in database
}

How to convert Array Result to JSON format when selecting particular column in Query

For converting Query result(Array) to JSON format,
I tried with #ResponseBody annotation and also with produces="application/json" but no changed in output format.
I also tried with ObjectMapper() but that output in string format not in key value.I removed my trial which not working.Now I added here my current code.
Here is my code snippet.
InvestigatorModel
package com.demo.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="investigator")
public class InvestigatorModel implements Serializable{
private static final long serialVersionUID = 1L;
#Id
public Integer ninvestigatorid;
public String sinvestigatorname;
public Integer ninstid ;
public String stitle;
public Integer ntempinvestigatorid;
public Integer nempid;
//getter and setter
InvestigatorController
package com.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.demo.model.InvestigatorModel;
import com.demo.services.InvestigatorService;
#RestController
#RequestMapping("/SpaceStudy/SpaceAdmin")
public class InvestigatorController {
#Autowired
InvestigatorService investService;
#CrossOrigin(origins="*")
#GetMapping("/AccountMaintenance/LoadInvestigator")
public List<InvestigatorModel> findInvestigatorName()
{
return investService.findInvestigatorName();
}
}
InvestigatorService
package com.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.model.InvestigatorModel;
import com.demo.repository.InvestigatorRepository;
#Service
public class InvestigatorService
{
#Autowired
InvestigatorRepository investRepo;
public List<InvestigatorModel> findInvestigatorName()
{
return investRepo.findBySinvestigatorname();
}
}
InvestigatorRepository
package com.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.demo.model.InvestigatorModel;
#Repository
public interface InvestigatorRepository extends JpaRepository<InvestigatorModel, Integer>
{
#Query("select invest.sinvestigatorname from InvestigatorModel as invest where invest.ninstid=60")
List<InvestigatorModel> findBySinvestigatorname();
}
My output is like This
Sample output
[
{
"sinvestigatorname": "Bargman",
}
]
How to convert This output into JSON format(key,value)
Can any one help me how to do that
As you are using JPA, simplest solution would be:
#Query("select new map(invest.sinvestigatorname as sinvestigatorname) from InvestigatorModel invest where invest.ninstid=60")
List<InvestigatorModel> findBySinvestigatorname();
This would give you the desired result.
See docs here

Unable to release connection from mysql after some time in spring boot application

I am using Jdbc template and DataSource to connect mysql.
the configuration that I am using is given in application.properties
spring.datasource.url=jdbc:mysql://hostname/databasename
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.max-active=1
And My Main Class in Which all configurations are called is below:
package com.es.producer;
import javax.jms.ConnectionFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.es.producer.config.Config;
import com.rabbitmq.jms.admin.RMQConnectionFactory;
#EnableWebSecurity
#SpringBootApplication
#SpringBootConfiguration
#ComponentScan("com.es.producer")
#EnableAutoConfiguration
#EnableSwagger2
public class EsProducerApplication {
#Autowired
DataSource dataSource;
JdbcTemplate template;
EsProducerApplication() {
}
#Bean
ConnectionFactory connectionFactory() {
RMQConnectionFactory connectionFactory = new RMQConnectionFactory();
connectionFactory.setUsername(Config.getRabbitmqusername());
connectionFactory.setPassword(Config.getRabbitmqpassword());
connectionFactory.setVirtualHost(Config.getRabbitmqvhost());
connectionFactory.setHost(Config.getRabbitmqhost());
return connectionFactory;
}
#Bean
public JdbcTemplate connection(){
return template = new JdbcTemplate(dataSource);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(EsProducerApplication.class, args);
}
}
and The Controller class is below:
package com.es.producer.controller;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.es.producer.EsProducerApplication;
#EnableAutoConfiguration
#Controller
public class DBTOQueueController {
JdbcTemplate template;
#Autowired
JmsTemplate jmsTemplate;
#Autowired
EsProducerApplication esProducerApplication;
#PostConstruct
public void init() {
template =esProducerApplication.connection();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#CrossOrigin
#RequestMapping(method = RequestMethod.POST, path = "/senddata")
#ResponseBody
public ResponseEntity<String> sendDataQueue(
#RequestHeader("tableName") String tableName) throws JSONException {
try {
String selectSql = "select * from " + tableName;
List<Map<String, Object>> employees = template.queryForList(selectSql);
// doing some operations
}}
when I am starting my spring application and after one minute if I try to terminate my application then connection with sql gets released.But if the application is in running state for more minutes and trying to terminate it the termination takes place but the connection is not released from mysql.
Any Help will be appreciated.
Thanks.