Spring Data Rest - resource becomes unavailable when subclassed - spring

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...

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.

Spring Boot JPA EntityListener query causes "don't flush the Session after an exception occurs"

Problem:
I create object A with an EntityListener with #PostPersist-method that will create object B, this works like a charm!
I need to introduce some logic before creating object B, I need to query the database and see if a similar B object already exists in the database. But when I run my query
#Query("select case when count(n) > 0 then true else false end from Notification n where student = :student and initiator = :initiator and entityType = :entityType and entityId = :entityId")
boolean alreadyNotified(#Param("student") Student student, #Param("initiator") Student initiator, #Param("entityType") EntityType entityType, #Param("entityId") Long entityId);
I get the following error:
ERROR org.hibernate.AssertionFailure.<init>(31) - HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in se.hitract.model.Likes entry (don't flush the Session after an exception occurs)
org.hibernate.AssertionFailure: null id in se.hitract.model.Likes entry (don't flush the Session after an exception occurs)
Background:
I have a Spring Boot project with Hibernate and MySql DB and I'm building a simple social media platform where students can upload posts/images and other user can like/comments.
When someone like/comment an object a notification should be sent to the other user. The like object:
#SuppressWarnings("serial")
#Entity
#Table(uniqueConstraints=#UniqueConstraint(columnNames = {"entityType", "entityId", "studentId"}))
#EntityListeners(LikeListener.class)
public class Likes extends CommonEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long likeId;
#NotNull
#Enumerated(EnumType.STRING)
private EntityType entityType;
private Long entityId;
...
}
The LikeListener:
#Component
public class LikeListener {
#PostPersist
public void doThis(Likes like) {
NotificationService notificationService = BeanUtil.getBean(NotificationService.class);
if(like.getEntityType().equals(EntityType.INSPIRATION)) {
InspirationService inspirationService = BeanUtil.getBean(InspirationService.class);
Inspiration inspiration = inspirationService.get(like.getEntityId());
notificationService.createLikeNotification(inspiration.getStudent(), like.getStudent(), EntityType.INSPIRATION, inspiration.getId());
}
if(like.getEntityType().equals(EntityType.COMMENT)) {
CommentService commentService = BeanUtil.getBean(CommentService.class);
Comment comment = commentService.get(like.getEntityId());
notificationService.createLikeNotification(comment.getStudent(), like.getStudent(), EntityType.COMMENT, comment.getId());
}
}
}
and the problem:
public Notification createLikeNotification(Student student, Student initiator, EntityType entityType, Long entityId) {
if(student.equals(initiator) || alreadyNotified(student, initiator, entityType, entityId)) {
return null;
}
Notification notification = createNotification(student,
initiator,
NOTIFICATION_TYPE.LIKE,
entityType,
entityId,
null);
return repository.save(notification);
}
public boolean alreadyNotified(Student student, Student initiator, EntityType entityType, Long entityId) {
return repository.alreadyNotified(student, initiator, entityType, entityId);
}
If I remove the alreadyNotified-call no error is thrown. What am I missing?
It seems that Hibernate flushes the Likes-save before my query is run but then it fails. Do I need to do some manual flush/refresh? I think Hibernate should solve this for me.

Sending POST request with Postman with #DBref

I want to send a POST request with Postman that creates a Purchase object and save it in the database.
My class Purchase:
#Document(collection = "purchases")
public class Purchase {
#Id
private String id;
#DBRef
private User buyer;
#DBRef
private List<File> FilesToPurchase;
private Long timestamp;
public Purchase() { }
public Purchase(User buyer, List<File> filesToPurchase) {
this.buyer = buyer;
FilesToPurchase = filesToPurchase;
}
// Getters and setters not posted here.
I want to insert in the database a new purchase done by an already existing User "buyer" who wants to purchase a list of already exsting Files "FilesToPurchase".
I have in my controller a POST function that receives a Purchase object using the annotation #RequestBody, but so far I've got NullPointerExceptions because of the empty Purchase object received.
I don't know how to handle #DBRef annotation. In Postman I try sending a JSON like this:
{
"buyer": {
"$ref":"users",
"$id" : "ObjectId('5bb5d6634e5a7b2bea75d4a2')"
},
"FilesToPurchase": [
{ "$ref":"files",
"$id" : "ObjectId('5bb5d6634e5a7b2bea75d4a5')"
}
]
}
Rename field "FilesToPurchase" and setter to "filesToPurchase" to match java conventions and try this
{ "buyer": { "id" : "5bb5d6634e5a7b2bea75d4a2" }, "filesToPurchase": [ { "id" : "5bb5d6634e5a7b2bea75d4a5" } ] }
By marking controller parameter with #RequestBody you ask Spring to deserialize input json to java object(Jackson ObjectMapper is used by default). It will not automaticly populate the whole #Dbref field, you should do it yourself by querying mongo if you want, however the only field you need in referred object to save object that reffers it is 'id'.

Error to convert objects using #SqlResultMapping and #ConstructorResult to NamedNativeQuery

guys.
I'm facing this problem for a day and I couldn't find a solution.
I have this scenario:
Spring Boot
JPA 2.1
Hibernate
I'm using Repository
The app is a JSON REST service
and this code, my entity Ticket.java:
#Entity
#Table(name = "tickets")
#SqlResultSetMapping(
name="SummaryReport",
classes=#ConstructorResult(
targetClass=ValidatedTicketsVO.class,
columns={#ColumnResult(name="quantity",
type=BigInteger.class),
#ColumnResult(name="quarter", type=String.class)
}))
#NamedNativeQuery(
name="Ticket.findShowSummaryReport",
query="SELECT COUNT(*) AS quantity, DATE_FORMAT( FROM_UNIXTIME(UNIX_TIMESTAMP(validation_time) - UNIX_TIMESTAMP(validation_time)%(15*60)), \"%d/%m/%Y %H:%i\" ) AS quarter " +
" FROM tickets " +
" WHERE show_id = :showId " +
" GROUP BY quarter " +
" ORDER BY quarter ")
public class Ticket implements Serializable {
I also tried using #EntityResult instead of #ConstructorResult:
#SqlResultSetMapping(
name="SummaryReport",
entities=#EntityResult(
entityClass=ValidatedTicketsVO.class,
fields={#FieldResult(name="quantity", column="quantity"),
#FieldResult(name="quarter", column="quarter")
}))
but I got the same error.
and my POJO / VO class that query result has to be mapped to:
import java.math.BigInteger;
public class ValidatedTicketsVO {
private BigInteger quantity;
private String quarter;
public ValidatedTicketsVO(BigInteger quantity, String timeQuarter) {
super();
this.quantity = quantity;
this.quarter = timeQuarter;
}
[ getters and setters ]
}
PS: the field quantity was initially defined as Integer but as I got a [java.math.BigInteger] exception I changed it to Long and now to BigInteger to see if it solves my problem, but stills the same.
And here is my Repository method:
List<ValidatedTicketsVO> findShowSummaryReport(#Param("showId") Long showId);
The query is well executed and I can't see any other log rather than the query itself. I get no exception in the log, but I get this response when I try to execute it through Postman:
{
"code": 5001,
"description": "Unexpected server error",
"timestamp": 1499782989890,
"errors": 1,
"fieldErrors": [
{
"field": "",
"message": "No converter found capable of converting from type [java.math.BigInteger] to type [br.com.company.validator.model.entity.vo.ValidatedTicketsVO]"
}
]
}
When I debug it on Eclipse the exception occurs when I call this method:
List<ValidatedTicketsVO> list = repository.findShowSummaryReport(showId);
Can someone help me, please?

Spring Rest with Angular 2

I am having problems with inserting new rows into database with my Angular 2 application.
The problem occures when i try to insert a new entry in database that has a foreign key to another table in the database. My two models defined in Spring are:
#Entity
public class A{
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToMany(mappedBy = "A")
private List<B> b = new ArrayList<B>();
...
}
#Entity
public class B{
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotNull
#ManyToOne
#JoinColumn(name="aId")
private A a;
...
}
Those two models in backend have their counterparts in the frontend. I added the _links part because Spring Rest api gives links instead of foreign keys:
export class A{
id: number;
b: B[];
_links:{...}
...
}
export class B{
id: number;
a: A;
_links:{...}
...
}
I created these models based on what information i get from api. For example, a get request on localhost:8080/api/b/1 gives:
{
"id" : 1,
"_links" : {
"self" : {
"href" : "http://localhost:4200/api/b/1"
},
"b" : {
"href" : "http://localhost:4200/api/b/1"
},
"a" : {
"href" : "http://localhost:4200/api/b/1/a"
}
}
}
I can easily insert new rows into table A (since it doesn't contain foreign keys) with my angular 2 service method shown bellow:
createA(a: A): Observable<A[]>{
return this.http.post(this.AUrl, a)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
}
Similarly, service method for creating a new model B looks like:
createB(b: B): Observable<B[]>{
return this.http.post(this.BUrl, b)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
}
My repositories in Spring are defined as:
#RepositoryRestResource(collectionResourceRel="a", path="a", itemResourceRel="a")
public interface ARepository extends JpaRepository<A, Integer>{
}
#RepositoryRestResource(collectionResourceRel="b", path="b", itemResourceRel="b"))
public interface BRepository extends JpaRepository<B, Long>{
}
My repository configuration in Spring is:
#Configuration
public class MyRestConfiguration extends RepositoryRestMvcConfiguration{
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config){
config.setBasePath("/api");
config.exposeIdsFor(A.class);
config.exposeIdsFor(B.class);
}
}
When i try to insert a new row into the table B i get the following error in spring:
javax.validation.ConstraintViolationException: Validation failed for classes [......model.B] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=a, rootBeanClass=class ........model.B, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
I would like to know what exactly is the request payload for http post request supposed to look like, in order for the application to insert a new row of B into the database. Any help is greatly appreciated.
Edit:
I have made a spring rest controler with this mapping:
#PostMapping("/api/b")
#ResponseBody
public String createServis(#RequestBody B b){
}
If I make a http post request with this payload (using curl or by some other means, but thats not the point):
{
id:1,
aId:1
}
or this one:
{
id:1,
a:{id:1}
}
or even this one:
{
id:1,
aId:1,
a:{id:1}
}
The property a of the object b remains null / is not properly initialized.
I got my answer here Spring Rest: Cannot insert rows that have #ManyToOne column
Basicaly you need to post:
{
id: 1
a: "http://localhost:4200/api/a/1"
}
to url localhost:4200/api/b

Resources