Doing custom query by a one of multiple primary keys throw me errors - spring-boot

My custom #Query of a table with multilple “primary keys” doen'twork.
In (image1) i show the basic structure i used to build my backend.
I start declaring my entity “Absentismos” and a other file to declare their primary keys “AbsentismoPrimaryData” with #Embeddable annotation.
#Entity
#Table(name="absentismo_incidencias")
#Getter
#Setter
public class Absentismos {
#EmbeddedId
public AbsentismoPrimaryData absentismoPrimaryData;
#Column(name="FECHA_INICIO")
public String fechaInicio;
#Column(name="FECHA_FINAL")
public String fechaFinal;
#Column(name="CANTIDAD")
public Integer cantidad;
}
#Embeddable
#Getter
#Setter
public class AbsentismoPrimaryData implements Serializable {
#Column(name="COD_TRABAJADOR")
public String codTrabajador;
#Column(name="CONCEPTO")
public String concepto;
//#DateTimeFormat(pattern = "dd-MM-yyyy")
#Column(name="FECHA_REGISTRO", insertable = false, updatable = false)
public String fechaRegistro;
}
Second, defined my repository with JPA.
#Repository
public interface AbsentimosRepository extends JpaRepository<Absentismos, AbsentismoPrimaryData> {
#Query(value="SELECT u FROM Absentismos u WHERE to_char( u.fechafiltro ,'yyyymmdd') = ?1",nativeQuery = true)
List<Absentismos> findAbsentismosByFechaRegistro(String fechaRegistro);
List<Absentismos> findByCantidad(Integer fechaRegistro);
}
Third, built my services
#Service
public class AbsentismoService {
#Autowired
private AbsentimosRepository repository;
public List<Absentismos> getAbsentismos(String fechaRegistro){
return repository.findAbsentismosByFechaRegistro(fechaRegistro);
}
public List<Absentismos> getByCantidad(Integer codTrabjador){
return repository.findByCantidad(codTrabjador);
}
}
and the controller.
#RestController
#RequestMapping("/absentismo")
public class AbsentismoController {
#Autowired
private AbsentismoService service;
#GetMapping()
public ResponseEntity<List<Absentismos>> getAbsentismos(#RequestParam("fechaRegistro") String fechaRegistro){
return new ResponseEntity<List<Absentismos>>(service.getAbsentismos(fechaRegistro), HttpStatus.OK);
}
Finally, my object in JSON format have this shape:
{
"absentismoPrimaryData": {
"codTrabajador": "10000576",
"concepto": "1413",
"fechaRegistro": "2009-07-16 00:00:00"
},
"fechaInicio": "2009-07-16 00:00:00",
"fechaFinal": "2009-07-31 00:00:00",
"cantidad": 16
}
In a table with unique primary key #Id, it works good. But, In this case i need to do a query by date with the field “fechaRegistro”.
However, After i try calle findAbsentismosByFechaRegistro function, the console show me this error:
Hibernate: SELECT u FROM Absentismos u WHERE to_char( u.fechafiltro ,'yyyymmdd') = ?
2022-03-29 14:10:38.432 WARN 14308 --- [nio-8082-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 942, SQLState: 42000
2022-03-29 14:10:38.433 ERROR 14308 --- [nio-8082-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00942: la tabla o vista no existe
2022-03-29 14:10:38.450 ERROR 14308 --- [nio-8082-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
oracle.jdbc.OracleDatabaseException: ORA-00942: la tabla o vista no existe
image1

Related

Compilation error using both HashKey and RangeKey in dynamoDB with Springboot

I am using dynamDb with my springboot application. I am trying to save data in the table which has hashKey and sortKey. Initially I tried to annotate my HaskKey and sortKey with #DynamoDBHashKey and #DynamoDBRangeKey respectively. However this was giving me compilation issues. Upon search I found this article https://github.com/derjust/spring-data-dynamodb/wiki/Use-Hash-Range-keys which explains how in springboot we need to create a composite key/id with annotation #id. This id will not be part of the table.
I implemented the same however I still get compilation error:
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eventRepository' defined in com.accuity.kyc.hep.repository.EventRepository defined in #EnableDynamoDBRepositories declared on DynamoDBConfig: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/core/support/ReflectionEntityInformation\r\n\tat org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)\r\n\tat org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)\r\n\tat org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)\r\n\tat org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)\r\n\tat org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)\r\n\tat org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)\r\n\tat org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)\r\n\tat org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)\r\n\tat org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)\r\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:302)\r\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1301)\r\n\tat org.springframework.boot.SpringApplication.run(SpringApplication.java:1290)\r\n\tat com.accuity.kyc.hep.HepApplication.main(HepApplication.java:16)\r\nCaused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'historyEventRepository' defined in com.accuity.kyc.hep.repository.HistoryEventRepository defined in #EnableDynamoDBRepositories declared on DynamoDBConfig: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/core/support/ReflectionEntityInformation\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)\r\n\tat org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)\r\n\tat org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)\r\n\tat org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)\r\n\tat org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)\r\n\tat org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)\r\n\tat org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)\r\n\tat org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)\r\n\t... 19 common frames omitted\r\nCaused by: java.lang.NoClassDefFoundError: org/springframework/data/repository/core/support/ReflectionEntityInformation\r\n\tat java.base/java.lang.ClassLoader.defineClass1(Native Method)\r\n\tat java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)\r\n\tat java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)\r\n\tat java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)\r\n\tat java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)\r\n\tat org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBEntityMetadataSupport.getEntityInformation(DynamoDBEntityMetadataSupport.java:125)\r\n\tat org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBRepositoryFactory.getEntityInformation(DynamoDBRepositoryFactory.java:104)\r\n\tat org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBRepositoryFactory.getDynamoDBRepository(DynamoDBRepositoryFactory.java:128)\r\n\tat org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBRepositoryFactory.getTargetRepository(DynamoDBRepositoryFactory.java:150)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:322)\r\n\tat org.springframework.data.util.Lazy.getNullable(Lazy.java:230)\r\n\tat org.springframework.data.util.Lazy.get(Lazy.java:114)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:328)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)\r\n\tat org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)\r\n\t... 30 common frames omitted\r\nCaused by: java.lang.ClassNotFoundException: org.springframework.data.repository.core.support.ReflectionEntityInformation\r\n\tat java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)\r\n\tat java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)\r\n\tat java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)\r\n\t... 50 common frames omitted\r\n"}
My entity class looks like this:
#DynamoDBTable(tableName = "Event")
#NoArgsConstructor
public class Event {
#Id
private EventId eventId;
#DynamoDBHashKey(attributeName = "id")
#DynamoDBAutoGeneratedKey
public String getId() {
return eventId != null ? eventId.getId() : null;
}
public void setId(String id) {
if (eventId == null) {
eventId = new eventId();
}
eventId.setId(id);
}
#DynamoDBRangeKey(attributeName = "eventDate")
public Date getEventDate() {
return eventId != null ? eventId.getEventDate() : null;
}
public void setEventDate(Date eventDate) {
if (eventId == null) {
eventId = new eventId();
}
eventId.setEventDate(eventDate);
}
}
Composite key class:
#NoArgsConstructor
#AllArgsConstructor
public class EventId {
private String id;
private Date eventDate;
#DynamoDBHashKey(attributeName = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBRangeKey(attributeName = "eventDate")
public Date getEventDate() {
return eventDate;
}
public void setEventDate(Date eventDate) {
this.eventDate = eventDate;
}
}
Repository:
#EnableScan
#Repository
public interface EventRepository extends CrudRepository<Event, EventId> {
}
For dependency I am using:
id 'org.springframework.boot' version '2.6.1' and
com.github.derjust:spring-data-dynamodb:5.1.0
I have followed the similar example from couple of other sources. I can not see what am I missing.
Please help.
There is an open issue for this, https://github.com/derjust/spring-data-dynamodb/issues/279. It appears the library is not compatible with Spring Boot 2.2. Per one of the commenters there is a fork available that may support this, but I haven't found this yet.
EDIT: The repository where this supposedly works now is at https://github.com/boostchicken/spring-data-dynamodb.

Duplicate or Null error when trying to send POST request for JSON Object with Foreign Key using Spring JPA

Here's my parent entity:
#Entity(name = "DrivingInstructor")
#Table(name = "driving_instructor")
#Getter
#Setter
#NoArgsConstructor
public class DrivingInstructor {
#Id
#Column(name = "driving_instructor_id")
private long drivingInstructorId;
#Column(name = "driving_instructor_name")
#Size(max = 128)
private String drivingInstructorName;
#Column(name = "specialization")
#Size(max = 200)
private String specialisation;
}
And here's my supposed child entity:
#Entity(name = "DrivingStudent")
#Table(name = "driving_student")
#Getter
#Setter
#NoArgsConstructor
public class DrivingStudent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "driving_student_id")
private long drivingStudentId;
#Column(name = "driving_student_name")
#Size(max = 128)
private String drivingStudentName;
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
}
Here's the relevant chunk of my service class for inserting/saving an instance of a DrivingStudent into the database:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
return drivingStudentServiceImpl.insertOrUpdateDrivingStudent(drivingStudent);
}
}
DrivingStudentServiceImpl is just an abstraction layer for Repository class that extends JpaRepository<DrivingStudent, Long>, so insertOrUpdateDrivingStudent() is practically just using the save() method from CrudRepository.
An instance of DrivingInstructor is already pre-inserted with drivingInstructorId of 1, and so I tried to execute a POST request via Postman using this JSON object:
{
"drivingStudentName": "Peter Parker",
"drivingInstructor": {"drivingInstructorId": 1}
}
And I'm getting this exception:
2021-08-27 20:03:37.554 ERROR 16108 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
2021-08-27 20:03:37.590 ERROR 16108 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] :
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException:
could not execute statement; SQL [n/a];
constraint [driving_instructor_pkey];
nested exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "driving_instructor_pkey"
Detail: Key (driving_instructor_id)=(1) already exists.
I also tried revising my RestController's PostMapping to look like this, but still nothing changes:
#RequestMapping(path = "api/v0/driving-school")
#RestController
#AllArgsConstructor
public class DrivingStudentRestController {
private final DrivingInstructorRepository drivingInstructorRepository;
private final DrivingStudentServiceImpl drivingStudentServiceImpl;
#PostMapping
Long insertOrUpdateDrivingStudent(#Valid #RequestBody DrivingStudent drivingStudent) {
Optional<DrivingInstructor> drivingInstructor = drivingInstructorRepository.findById(drivingStudent.getDrivingInstructor().getDrivingInstructorId());
if (drivingInstructor.isPresent()) {
drivingStudent.setDrivingInstructor(drivingInstructor.get());
return drivingStudentServiceImpl.insertOrDrivingStudent(drivingStudent);
}
return null;
}
}
The error I am getting then changed to:
2021-08-27 21:36:58.622 ERROR 11388 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper :
ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
2021-08-27 21:36:58.632 ERROR 11388 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] :
Servlet.service() for servlet [dispatcherServlet] in context with path []
threw exception [Request processing failed;
nested exception is org.springframework.dao.DataIntegrityViolationException:
could not execute statement; SQL [n/a];
constraint [driving_instructor_number" of relation "driving_student];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: null value in column "driving_instructor_number" of relation "driving_student" violates not-null constraint
Detail: Failing row contains (Peter Parker, null).
There are stuff I've tried but most exceptions simply end up with either of those two. All I really wanted to do was insert an instance of DrivingStudent into the database using POST request, with a foreign key connecting it to a DrivingInstructor instance, and then of course, be able to retrieve those data.
I am able to do insert data manually into the database using the statement:
INSERT INTO driving_student VALUES ('Peter Parker', 1);
And I am able to retrieve that data in JSON format using GET method. So far, my only problem really is how to deal with the POST method.
Ok, I just changed/simplified the annotations in DrivingStudent's drivingInstructor JoinColumn field from this:
#ManyToOne(cascade = CascadeType.ALL, targetEntity = DrivingInstructor.class)
#JoinColumn(name = "driving_instructor_id", referencedColumnName = "driving_instructor_name", insertable = false, updatable = false)
private DrivingInstructor drivingInstructor;
to this:
#ManyToOne
#JoinColumn(name = "driving_instructor_id")
private DrivingInstructor drivingInstructor;
and it somehow worked... I have no idea why though.

Impossible to return a list / collection of projection

I made a spring-boot project to access to my datas.
My main class is Patient.java:
#Entity
public class Patient {
private Long id;
private String numeroSs;
private String profession;
// lot of stuff...., getters, setters, ...
}
In order to improve my requests, I've made a very simple projection of my class Patient. I've called this projection PatientCustom :
public interface PatientCustom {
String getNumeroSs();
Timestamp getDateProchainRdv();
}
And in my repository "PatientRepo.java", I created two custom methods :
#Transactional
#RepositoryRestResource(collectionResourceRel = "patient", path = "patient")
public interface PatientRepo extends JpaRepository<Patient, Long> {
PatientCustom findOneByNumeroSs(String numeroSs);
Collection<PatientCustom> findByNumeroSs(String numeroSs);
}
When I use the first method, no problem : it returns a PatientCustom :
{
numeroSs: "150505617017002",
dateProchainRdv: null
}
But When I want a list or a collection, it sends me an error :
{
cause: null,
message: "Couldn't find PersistentEntity for type class com.sun.proxy.$Proxy165!"
}
And the traces in my terminal :
2019-03-12 10:32:34.671 ERROR 2072 --- [nio-8090-exec-2] o.s.d.r.w.RepositoryRestExceptionHandler : Couldn't find PersistentEntity for type class com.sun.proxy.$Proxy165!
java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class com.sun.proxy.$Proxy165!
at org.springframework.data.mapping.context.PersistentEntities.lambda$getRequiredPersistentEntity$2(PersistentEntities.java:96) ~[spring-data-commons-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at java.util.Optional.orElseThrow(Optional.java:290) ~[na:1.8.0_181]
at org.springframework.data.mapping.context.PersistentEntities.getRequiredPersistentEntity(PersistentEntities.java:95) ~[spring-data-commons-2.1.5.RELEASE.jar:2.1.5.RELEASE]
I understand very well that spring wants to add a proxy class to my interface, but when it want to add this proxy to a list or a collection, it's unhappy because list and collection are not interfaces but classses.
What can I do to solve this ?

Spring Data Rest - resource becomes unavailable when subclassed

After having debugged my head off, I am out of ideas and would need some help. What really intrigues me badly is the simplicity of what I am trying to do and still the impossibility of achieving it...
I am trying to make a small demo of spring rest data, by creating some entities, exposing them as rest resources and persisting them in an in-memory h2 database.
The following code works:
#Entity
#Table(name="info")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="INFO_TYPE", discriminatorType=DiscriminatorType.STRING)
public class ItemInfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
public long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
#RepositoryRestResource(collectionResourceRel="itemInfos", path="itemInfos")
public interface ItemInfoRepository extends PagingAndSortingRepository<ItemInfo, Long> {
}
When I issue a curl request for curl http://localhost:8080/itemInfos I get the following correct response:
{
"_embedded" : {
"itemInfos" : [ ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/itemInfos"
},
"profile" : {
"href" : "http://localhost:8080/profile/itemInfos"
}
},
"page" : {
"size" : 20,
"totalElements" : 0,
"totalPages" : 0,
"number" : 0
}
}
However, as soon as I add a subclass entity of ItemInfo, the /itemInfos resource will not be available anymore.
So adding the class:
#Entity
#Table(name="info")
#DiscriminatorValue(value="COMMENT")
public class UserComment extends ItemInfo {
private String from;
private String comment;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
Will result in the same curl command as earlier to produce an error:
{"timestamp":1488282548770,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.InvalidDataAccessResourceUsageException","message":"could not prepare statement; SQL [select iteminfo0_.id as id2_0_, iteminfo0_.comment as comment3_0_, iteminfo0_.from as from4_0_, iteminfo0_.info_type as info_typ1_0_ from info iteminfo0_ limit ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","path":"/itemInfos"}
Furthermore, trying to add a new itemInfo causes a similar error:
{"timestamp":1488282718547,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.InvalidDataAccessResourceUsageException","message":"could not prepare statement; SQL [insert into info (id, info_type) values (null, 'ItemInfo')]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","path":"/itemInfos"}
Adding a UserCommentRepository also doesn't solve the problem in any way:
public interface UserCommentRepository extends PagingAndSortingRepository<UserComment, Long> { }
In this case, if i try to add a new user comment:
curl -i -X POST -H "Content-Type:application/json" -d "{ \"from\" : \"Ana\", \"comment\" : \"some comment\" }" http://localhost:8080/userComments
I get a further error:
{"timestamp":1488282968879,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.InvalidDataAccessResourceUsageException","message":"could not prepare statement; SQL [insert into info (id, comment, from, info_type) values (null, ?, ?, 'COMMENT')]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","path":"/userComments"}
It seems that adding inheritance for my entities completely ruins my resources. Did anyone of you had a similar problem?!
Ok...I figured it out (mostly by mistake) and it is even more frustrating.
The problem was the use of the variable name "from". It seems that spring data rest uses this as a keyword. As soon as I refactored the name of this variable, everything worked as expected. Unfortunately the exceptions and error messages didn't help at all.
Hopefully others will not go through the same debugging hell...

Spring Data REST getting exception when trying to save the data

I new to using Spring data rest , so even though this might be a very basic thing I would appreciate it if someone could point what is the mistake that i made or point me in the right direction .
I have an EmployeeRepository which contains the employee entities.
public interface EmployeeRepository extends CrudRepository<Employee,Long>{
#Query("select emp from Employee emp where emp.employeeId=?1")
Employee findById(String employeeId);
#Query("select emp from Employee emp where emp.officialEmailId = ?1")
Employee findByOfficialEmailId(String officialEmailId);
}
Below is a part of the employee entity delcaration .
public class Employee extends AbstractAuditingEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Version
private Long version;
#Size(min = 3, max = 30)
#NotBlank
#Column(unique=true,nullable=false)
private String employeeId;
#Size(min=3,max = 25)
#NotBlank
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
private String lastName;
#Size(min=3,max = 25)
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
#NotBlank
private String firstName;
#Size(min=3,max = 25)
#Field(index=Index.YES, analyze=Analyze.NO, store=Store.YES)
private String middleName;
}
In my service class I needed to get list of employee entities based on a condition and set a common property to all those .I tried it and it did not work so I tried something much simpler , I'm trying to set the middle name of all employees to a common value and save it to the db . Here is the code for it
#Transactional
public void tempFunction(){
Iterable<Employee> empList = employeeRepository.findAll();
for(Employee e : empList){
e.setMiddleName("newMiddleName");
employeeRepository.save(e);
}
}
I'm getting the below exception 2016-02-20 17:59:08.545 ERROR 533 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause
java.lang.NullPointerException: null
And the stack trace shows the root cause to be a NullPointerException which I know is not present anywhere near where I'm invoking this code from either in my controller or service . Could someone point if there is any mistake in my code , thanks in advance .

Resources