Upload excel file content to mysql using Spring boot and UI - mysql

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
}

Related

rest service based on Spring return html instead of json

i am using keycloak and spring to get the user list in a rest service, however the rest return the html instead of json data.
here is the service.
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService{
#Autowired
KeycloakInstance keycloakInstance;
public List<UserRepresentation> loadUsers(String realm) {
return keycloakInstance.getInstance()
.realm(realm)
.users()
.list();
}
}
here is the controller.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.keycloak.representations.idm.UserRepresentation;
import java.util.List;
#RestController
#RequestMapping("/api/admin/users")
public class UserController {
#Autowired
private UserService userService;
#GetMapping(value = "", produces="application/json")
public List<UserRepresentation> loadUsers() {
String realm = "abc";
return userService.loadUsers(realm);
}
}
any idea how to fix this?
You would need to add the path to #GetMapping, this should work
#ResponseBody
#GetMapping(value = "/api/admin/users", produces="application/json")
public List<UserRepresentation> loadUsers() {
String realm = "abc";
return userService.loadUsers(realm);
}
or using this way
#GetMapping (value = "/api/admin/users", produces = MediaType.APPLICATION_JSON_VALUE)
As #ConstantinKonstantinidis commented, add to RequestMapping produces JSON to apply to your method (and all methods):
#RequestMapping(value = "/api/admin/users", produces = MediaType.APPLICATION_JSON_VALUE
Supported at the type level as well as at the method level
Another option is to add the path to #GetMapping ,e.g.
#RequestMapping("/api/admin")
public class UserController {
#GetMapping(value = "/users", produces="application/json")

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;

Migrating from Mysql to Cassandra Spring boot

I am totally new to Cassandra, this is the very first time, never used it before, so far we have been using Spring Boot and MySql as our DB, but now we are planning to migrate our database to Cassandra with the minimum code or no change.
here is a sample demo of code that we have been using.
config class
package com.example.demo.config;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Generated;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.HashMap;
import static org.hibernate.cfg.AvailableSettings.*;
#Configuration
#EnableTransactionManagement
#EnableJpaAuditing
#EnableJpaRepositories(entityManagerFactoryRef = "orclEntityManagerFactory", transactionManagerRef = "orclTransactionManager", basePackages = {"com.example.demo.repository"})
#Generated
public class DataSourceConfig {
#Value("${spring.datasource.driver-class-name}")
private String orclDbDriver;
#Value("${spring.datasource.url}")
private String orclDbConnUrl;
#Value("${spring.datasource.username}")
private String orclDbUsername;
#Value("${spring.datasource.password}")
private String orclDbPassword;
#Value("${spring.datasource.poolName}")
private String dataSourcePoolName;
#Value("${spring.jpa.properties.hibernate.dialect}")
private String orclHibernateDialect;
#Value("${spring.jpa.hibernate.ddl-auto}")
private String hibernateDDL;
#Value("${spring.jpa.show-sql}")
private boolean showSql;
#Value("${spring.datasource.packagesToScan}")
private String[] packagesToScan;
public DataSourceConfig() {
}
#Bean
#Primary
public DataSource orclDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(this.orclDbDriver);
dataSource.setJdbcUrl(this.orclDbConnUrl);
dataSource.setUsername(this.orclDbUsername);
dataSource.setPassword(this.orclDbPassword);
dataSource.setPoolName(this.dataSourcePoolName);
return dataSource;
}
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean orclEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(this.orclDataSource());
factory.setPackagesToScan(this.packagesToScan);
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(Boolean.TRUE);
jpaVendorAdapter.setShowSql(showSql);
jpaVendorAdapter.setDatabasePlatform(orclHibernateDialect);
factory.setJpaVendorAdapter(jpaVendorAdapter);
HashMap<String, Object> properties = new HashMap();
properties.put(HBM2DDL_AUTO, this.hibernateDDL);
properties.put(DIALECT, this.orclHibernateDialect);
properties.put(STATEMENT_BATCH_SIZE, "500");
properties.put(ORDER_UPDATES, "true");
properties.put(ORDER_INSERTS, "true");
properties.put(GENERATE_STATISTICS, "true");
factory.setJpaPropertyMap(properties);
return factory;
}
#Bean
#Primary
public JpaTransactionManager orclTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(this.orclEntityManagerFactory().getObject());
return transactionManager;
}
}
controller class
import com.example.demo.entity.Child;
import com.example.demo.repository.ChildRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Timestamp;
import java.util.List;
#RestController
public class HelloController {
#Autowired
private ChildRepository childRepository;
#GetMapping("put")
public Child getHello() {
Child child = new Child();
child.setName("shrikant");
child.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
return childRepository.save(child);
}
#GetMapping("get")
public List<Child> hello() {
return childRepository.findAll();
}
}
repository
package com.example.demo.repository;
import com.example.demo.entity.Child;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ChildRepository extends JpaRepository<Child, Long> {
}
application.dev
spring.datasource.url=jdbc:mysql://localhost:3306/student_db?jdbcCompliantTruncation=false&sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&useSSL=false&useServerPrepStmts=false&rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.poolName=springHikariCp
spring.jpa.generate-ddl=true
spring.jpa.database.schema=student_db
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.datasource.packagesToScan=com.example.demo.entity
spring.profiles.active=dev
build.gradle
plugins {
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
compile 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
I have installed Cassandra with the help of google and able to login using cqlsh.
created keyspace
CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};
added Cassandra dependency in Gradle
compile 'org.springframework.boot:spring-boot-starter-data-cassandra'
but what should be the configuration properties in the application.properties, I couldn't find any of the examples on Google creating a custom data source, all are using Spring Boot auto-config, but I can't do that, because that will be a major code change.
You need to use the CassandraRepository instead of JpaRepository interface
public interface ChildRepository extends CassandraRepository<Child, Long> { }
You need to have these properties in your application.properties
spring.data.cassandra.contact-points=127.0.0.1 (or your corresponding connection uri)
spring.data.cassandra.username=<username, if any>
spring.data.cassandra.password=<password, if any>
spring.data.cassandra.keyspace=default
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=NONE
Then you will be relatively fine. But like the other guys said in the comments section, it is quite important that you should understand the nature of Cassandra. If you don't implement your data model based on your queries, it won't be successful.

Saving Date and Time in MySQL in Hibernate Spring Boot

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.

Hibernate lazy initialization not working with Jackson Mapper

I am using Spring 4 and Hibernate 4. I am using java jpa to use hibernate. I want to load few data lazily. And I have also configured Jackson mapper to convert my java object to json and vice versa. But it's throwing exception while converting the java to json. I have created custom object mapper but still it's not working.
Please see the following classes and see what I am missing here
I am using annotations. Hibernate configuration file:
MvcConfiguration.java
package com.ampdev.platform.module.common.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.ampdev.platform.framework.dataaccess.config.HibernateAwareObjectMapper;
import com.ampdev.platform.framework.rest.security.AuthenticationService;
import com.ampdev.platform.framework.rest.security.AuthenticationServiceDefault;
import com.ampdev.platform.module.user.util.EncryptionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
#Configuration
#ComponentScan(basePackages = "com.ampdev")
#EnableWebMvc
#EnableTransactionManagement
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Autowired
#Bean(name = "authenticationService")
public AuthenticationService getAuthencticaionService()
{
return new AuthenticationServiceDefault();
}
#Autowired
#Bean(name = "passwordEncoder")
public PasswordEncoder getPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
#Autowired
#Bean(name = "encrypyionUtil")
public EncryptionUtil getEncryptionUtil(PasswordEncoder passwordEncoder)
{
return new EncryptionUtil(passwordEncoder);
}
#Autowired
#Bean(name = "objectMapper")
public ObjectMapper getObjectMapper()
{
return new HibernateAwareObjectMapper();
}
#Autowired
#Bean(name = "jsonMessageConverter")
public MappingJackson2HttpMessageConverter getMessageConvertor()
{
return new MappingJackson2HttpMessageConverter();
}
#Autowired
private ObjectMapper objectMapper;
#Autowired
private MappingJackson2HttpMessageConverter jsonMessageConverter;
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
jsonMessageConverter.setObjectMapper(objectMapper);
converters.add(jsonMessageConverter);
}
}
I have created a custom object mapper to include Hibernate4Module
HibernateAwareObjectMapper.java
package com.ampdev.platform.framework.dataaccess.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper
{
/**
*
*/
private static final long serialVersionUID = -4013528320937607847L;
public HibernateAwareObjectMapper()
{
Hibernate4Module hibernateModule = new Hibernate4Module();
registerModule(hibernateModule);
}
}
Here is my Data object in which I am using the lazy loading:
UserMovieReviewData .java
package com.ampdev.platform.module.movie.review.user.dataobject;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.ampdev.platform.module.common.dataobject.PersistedDataObject;
import com.ampdev.platform.module.movie.dataobject.MovieData;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.user.dataobject.UserData;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#Table(name = "movie_review_user")
#JsonInclude(Include.NON_NULL)
public class UserMovieReviewData extends PersistedDataObject
{
/**
*
*/
private static final long serialVersionUID = -5644749600929596177L;
#Id
#GeneratedValue
#Column(name = "review_id")
private long id;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "movie_id")
private MovieData movieData;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private UserData userData;
#Column(name = "rating")
private int rating;
#Column(name = "title")
private String title;
#Column(name = "review")
private String review;
#Column(name = "create_date")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name = "update_date")
#Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
#Override
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public MovieData getMovieData()
{
return movieData;
}
public void setMovieData(MovieData movieData)
{
this.movieData = movieData;
}
public UserData getUserData()
{
return userData;
}
public void setUserData(UserData userData)
{
this.userData = userData;
}
public int getRating()
{
return rating;
}
public void setRating(int rating)
{
this.rating = rating;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getReview()
{
return review;
}
public void setReview(String review)
{
this.review = review;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
}
Here is my web service resource which I am using as rest resource:
ReviewResource.java
package com.ampdev.platform.module.movie.review.resource;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ampdev.platform.framework.rest.BaseExecutor;
import com.ampdev.platform.framework.rest.RestBaseResource;
import com.ampdev.platform.module.common.constants.URIConstants;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData;
#Controller
#RequestMapping(value = "/ws/movie/review")
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ReviewResource extends RestBaseResource
{
#Autowired
private BaseExecutor<UserMovieReviewData, UserMovieReviewData> createMovieReviewExecutor;
#Autowired
private BaseExecutor<String, List<UserMovieReviewData>> getMovieReviewExecutor;
#RequestMapping(value = ReviewConstants.ADD, method = RequestMethod.POST)
public ResponseEntity<UserMovieReviewData> createMovieReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type,
RequestEntity<UserMovieReviewData> requestEntity)
{
createMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
return performTask(requestEntity, createMovieReviewExecutor);
}
#RequestMapping(value = URIConstants.GET_IDS, method = RequestMethod.GET)
public ResponseEntity<List<UserMovieReviewData>> getReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type, #PathVariable(value = "ids") String reviewIds)
{
getMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
getMovieReviewExecutor.setAttribute(ReviewConstants.REVIEW_IDS, reviewIds);
return performTask(null, getMovieReviewExecutor);
}
}
I am using spring 4 + hibernate 4.
I am getting the following error when I am trying to get data from Rest web service call:
I am getting the following error when I am trying to fetch the data from Rest web service:
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData["movieData"]->com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5["id"])
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:652)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5.getId(MovieData_$$_jvst49f_5.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.get(BeanPropertyWriter.java:726)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:506)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
You're trying to access a lazy collection outside of the hibernate session. There are a few ways to solve this, the most clear is to access the size() of each collection you're going to be serializing in your service class, which causes the collection to be loaded and therefore available outside the session.
Another alternative is to annotate the collection with FetchType.EAGER, but this will affect all uses of your model, which might not be what you want. Finally, you can use the OpenSessionInView pattern, which maintains an open hibernate session for the duration of the request (and therefore allows you to load lazy collections outside where the session boundary would otherwise be). This last alternative is generally considered an anti-pattern.