Spring Data JPA - cannot insert to the databse - annotation problem? - spring

I can't resolve the problem with inserting values into my database.
I've two very basic and simple classes - Car and Model. I want to store the model ID value for each vehicle in the car class. You know, for the sake of simplicity I assume every car has no brand, only model (eg. Auris, Civic, F150, Challenger etc.).
#Data
#Entity
public class Car {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#ManyToOne
private Model model;
}
#Entity
#Data
#NoArgsConstructor(access=AccessLevel.PRIVATE, force=true)
#RequiredArgsConstructor
public class Model {
#Id
private final Long id;
private final String name;
private final int price;
}
But the problem is I got that error
Field error in object 'car' on field 'model': rejected value [Model(id=2, name=Civic)]; codes [typeMismatch.samochod.model,typeMismatch.model,typeMismatch.com.CarDealer.Model,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [car.model,model]; arguments []; default message [model]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.CarDealer.Model' for property 'model'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Model(id=2, name=Civic)'; nested exception is java.lang.NumberFormatException: For input string: "Model(id=2,name=Civic)"]]
I'd appreciate any help.

Related

Failed parsing for a LocalDate value while using Spring Data Rest

I am still a newbie with Spring Data Rest and I'm having some issues with it while I have to parse a LocalDate value to an endpoint. I have searched info's in other topics too but I'm still stucked, this is the problem:
I have one Entity with this code .
#Entity
#Table(name="calendario_parcheggio")
#Setter
#Getter
public class CalendarioParcheggio {
#Id
#Column(name="data_parcheggio")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE )
#JsonFormat(pattern="yyyy-MM-dd")
private LocalDate data;
#Column(columnDefinition = "ENUM('ATTIVO', 'ARCHIVIATO')")
#Enumerated(EnumType.STRING)
private Stato stato;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="data_parcheggio")
private List<Parcheggio> parcheggio;
public enum Stato {
ATTIVO,
ARCHIVIATO,
}
}
It's an Entity linking the Date and its status for a Parking that works hourly.Matching this table on MySQL
CREATE TABLE calendario_parcheggio (
data_parcheggio DATE PRIMARY KEY,
stato ENUM ('ATTIVO','ARCHIVIATO') NOT NULL DEFAULT ('ATTIVO')
);
When I start the server everything is ok , but when i try (by browser or Postman) to check the data of a particular instance (in my case : "http://localhost:8080/parkingsystem/api/calendario-parcheggio/2022-10-18") ,I get this problem :
{"cause":
{"cause":
{"cause": null,
"message": "Text '2022-10-18' could not be parsed at index 2"
},
"message": "Parse attempt failed for value [2022-10-18]"
},
"message": "Failed to convert from type [java.lang.String] to type [java.time.LocalDate] for value '2022-10-18';
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2022-10-18]"
}
And this is the Repository
#RepositoryRestResource(collectionResourceRel="calendarioParcheggio", path="calendario-parcheggio")
public interface CalendarioParcheggioRepository extends JpaRepository<CalendarioParcheggio, LocalDate> {
}
Can you help me to find the solution please?I hope I have explained the problem well enough, my English is still in training :)

Spring JPA naming query with orderBy doesn't work

I'm using Spring Boot 2, Spring JPA, Spring Data.
I'm trying to get the first result from a table in which I want to sort results by a int property asc.
This is my bean:
#Entity
public class DatabaseInstance extends AbstractEntity {
#NotNull
#Enumerated(EnumType.STRING)
#Column(nullable = false)
private Supplier supplier;
NotNull
#Column(nullable = false, columnDefinition = "INT DEFAULT 0.0")
private int databaseCount = 0;
and this is my repository:
#Transactional
public interface DatabaseInstanceRepository extends JpaRepository<DatabaseInstance, Long> {
public Optional<DatabaseInstance> findFirstOrderByDatabaseCountAsc();
}
According to Spring manual I can order by property name + asc word. At the same time I want the first result (so i get the instance with the lower databaseCount value).
I get this error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property asc found for type int! Traversed path: DatabaseInstance.databaseCount.
I am not able to figure out what's wrong with my method name. Some advice?

modifying query not working : no property found exception

i am trying to modify the card entity with below mentioned code.
public interface CardRepository extends JpaRepository<Card, Integer>{
#Modifying
#Query(name="update Card c set c.status=4 where c.id=?1")
public void setCardStatus(int id);
}
Card Class is associated with status.
#Entity
#Table(name="card")
public class Card {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="card_no")
private String cardNo;
#ManyToOne
#JoinColumn(name="status_id",nullable=false,insertable=true,updatable=true)
private Status status;
... getter setters...
}
Below mentioned is the exception generated.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property set found for type Card!
Changing method name to modify also does not work also.
any help is appreciated please...
Don't use the name setCardStatus! Change the name to something like changeCardStatus

spring bind date field of command object

I have a form that inserts/updates data. The command object (Bean) class has a Date field that is placed in the form as follows:
<form:hidden path="createdDate">
when I submit the form, the BindResult.hasErrors() is validated as true.
I think I need to bind the date object, but how is it done for Command object field?
The form bean code is as follows
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue
#Column(name="id")
private int id;
#Column(name="EmployeeName")
private String employeeName;
#Column(name="CreatedDate")
private Date createdDate;
//Setter and getter methods
}
Error:
[Field error in object 'employee' on field 'CreatedDate': rejected value [Mon Sep 17 20:35:26 IST 2012]; codes [typeMismatch.employee.CreatedDate,typeMismatch.CreatedDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [subject.CreatedDate,CreatedDate]; arguments []; default message [CreatedDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'CreatedDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'CreatedDate': no matching editors or conversion strategy found]]
Add this annotation to your date fields:
#Column(name="CreatedDate")
#DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss") //whatever format is appropriate to you..
private Date createdDate;
Ensure that you have joda time as a dependency and the library is present in classpath. It will automatically register a converter to take care of the transformation.
I found your problem. In your Employee model class the createdDate field is not defined correctly.
You need to use the #Temporal annotation to define that the field is of type date.
Please put the following annotation also on top of the field declaration of createdDate
#Temporal(TemporalType.TIMESTAMP)
I think this should solve your problem. Cheers.

How can I validate a complex model object in Spring 3 using #Valid annotations?

I have a model object modelling a purchase order. The purchase order has a few fields (such as ID and date) and a list of line-items as ArrayList. I can validate the parent purchase order ok, but it chokes when validating the line-items.
Can anyone help me with validation of complex objects? If I cannot validate complex objects auto-magically, how can I write a custom validator that relies upon the constraint annotations in the parent and then iterates over the child line-items? This Validator instance needs to be able to call something.validate(purchaseOrder) and (for each line-item) something.validate(lineItem). Where do I get "something" from?
I have specified <mvc:annotation-driven /> in dispatcher-servlet. I am not using #InitBinder. And I am using #Valid annotation for validation in controller's method like
#RequestMapping(params="confirmPurchaseOrder")
public String confirm(
#ModelAttribute("purchaseOrder") #Valid PurchaseOrder purchaseOrder,
BindingResult result,
#RequestParam("account") String accountString,
#RequestParam("division") String divisionString,
Model model)
{
if (result.hasErrors()) {
return PURCHASE_ORDER_CREATE_VIEW;
}
The domain classes look like this: -
public class PurchaseOrder implements Comparable<PurchaseOrder> {
/** Based on GUID */
private String id;
/** SOP */
#NotNull
private Integer SOP;
/** Reference from client */
#NotBlank
private String purchaseOrderReference;
/** PO date */
#DateTimeFormat(style="S-")
#NotNull
private Date date;
#Valid
private final Collection<LineItem> lineItems = new ArrayList<LineItem>();
And
public class LineItem {
...Elided
/** Generated from GUID */
private String id;
#NotNull
#DateTimeFormat(style="S-")
#Future
private Date expiry;
private String softwareVersion;
#NotNull
#NumberFormat(style = Style.NUMBER)
#Min(1)
private Integer licenceCount;
When committing a Purchase Order with an empty expiry date, I get the following exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'lineItems[]' of bean class [com.nit.ols.domain.PurchaseOrder]: Invalid index in property path 'lineItems[]'; nested exception is java.lang.NumberFormatException: For input string: ""
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:730)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
In your PurchaseOrder class, try changing your lineItems collection to a List. It looks like you are having the same problem addressed in this question.
It's like David said, declaring lineItems of type List should do the trick. In Hibernate Validator 4.2.0 CR1 (not yet released atm, you could use the latest snapshot build if you are interested) also Collection should work, see HV-468 for more details.

Resources