Well,
Im trying to validate a NotNull attribute
#Temporal(TemporalType.DATE)
#Column(name = "DATA_PAGAMENTO")
#NotNull
private Date dataPagamento;
So I created a custom message instead showing the default one
ValidationMessages.properties
javax.validation.constraints.NotNull.message={0} cannot be null!
this {0} would suppose to bring dataPagamento and show something like:
"dataPagamento cannot be null!"
but it keeps showing this:
{
"Validations": [
"{0} cannot be null!"
]
}
Related
I'm creating an entity which has a ManyToOne relation to another one, it being multiple customers can belong to one company. Now I have my Customer entity defined as follows:
#Entity
#Table(name = "Customers")
data class Customer(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
var customerId: Long? = null,
var firstName: String,
var lastName: String,
var gender: String,
#Column(insertable = false, updatable = false)
var companyId: Long,
#ManyToOne(targetEntity = Company::class, fetch = FetchType.LAZY)
#JoinColumn(name = "companyId", referencedColumnName = "companyId")
var company: Company? = null,
var profilePicture: String,
var email: String,
var phone: String,
var birthDay: String,
var bio: String,
var notifyByPhone: Boolean,
var notifyByEmail: Boolean,
var notifyBySms: Boolean,
#UpdateTimestamp
var updatedAt: LocalDateTime,
#CreationTimestamp
var createdAt: LocalDateTime
)
I use the following function from CustomerResource as an endpoint to persist the Customer:
#Transactional
#POST
fun post(#Valid entity: Customer): Response = try {
repository.persist(entity)
created(entity)
} catch (exc: Exception) {
serverError(exc)
}
Using Postman, I use the following JSON object to fire a request to the endpoint:
{
"firstName": "Ricardo",
"lastName": "de Vries",
"gender": "male",
"companyId": "200",
"profilePicture": "test",
"email": "mail#gmail.com",
"phone": "0612536263",
"birthDay": "28-12-1995",
"bio": "Nothing",
"notifyByPhone": true,
"notifyByEmail": true,
"notifyBySms": true
}
I have a property called "company" which is being mapped to the Company the user belongs to, based on the companyId. I have a separate companyId field which is being mapped to the companyId field in the database.
When I want to create a new Customer, I'm including the companyId in the request. This succeeds and the Customer is being successfully created.
Now when I try to fetch that specific customer, I get the following
error: "org.hibernate.PropertyAccessException: Null value was assigned to a property [class org.acme.domains.core.models.entities.Customer.companyId] of primitive type setter of org.acme.domains.core.models.entities.Customer.companyId".
I don't really get why this error occurs. I would think that the Company which belongs to the Customer gets added afterwards whenever I fetch a specific Customer.
Does anybody know how to be able to add an entity this way?
Do you have the proper getter and setters generated? It seems like the first request is failing to set the fields properly. I suggest you put a breakpoint to the controller that creates your customer and check if the field is being set like it should. Maybe you are passing the data in a wrong format etc. I can't say that from this information but you should debug that.
You can also put #NotNull validation on your fields to see if it fails to be set in object creation.
You have mapped companyId as not insertable and not updatable, so it won't appear in the query.
Try change it to:
#Column(insertable = true, updatable = true)
Long companyId
What's happening, I think, it's that Hibernate ORM is creating the insert query with all the other values, except for this one.
I would recommend enabling the log to check. You can do it in the configuration by setting:
hibernate.show_sql = true
hibernate.format_sql = true
I have two tables notification and message.
Message.java
...
...
#Table(name = "message",
uniqueConstraints = {#UniqueConstraint(name = "UniqueMessage",
columnNames = { "message_id" })})
public class Message implements Serializable {
#Id
#Column(name = “message_id")
private int messageId;
#Column(name = "description")
private String description;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "start_time")
private Date startTime;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "end_time")
private Date endTime;
#PrePersist
#PreUpdate
public void generateMessageId(){
this.messageId = Math.abs(Objects.hash(this.getDescription(),
this.getStartTime().getTime() / 1000));
}
My use case is -- I will be creating a message with certain description and start time. If I get same message again, I should be able to update the endTime. MessageId is calculated separately under method generateMessageId as this will act as an identifier to find if message has already been saved. If yes, I will update the message. It works well for first message but when I try to save again with updated endTime, I get
ERROR: duplicate key value violates unique constraint “message_pkey”
Steps:
I tried:
Message m1 = new Message();
m1.setDescription(“fake”);
m1.setStartTime(“2022-01-03T12:05:00”)
messageRepository.save(m1);
This works well. I can see a row in database with
Message_id description start_time end_time
46536723 fake 2022-01-03T12:05:00 null
Message m2 = new Message();
m2.setDescription(“fake”);
m2.setStartTime(“2022-01-03T12:05:00”);
m2.setEndTime(“2022-01-05T12:00:00)
messageRepository.save(m2);
I get ERROR: duplicate key value violates unique constraint error.
Isn’t jpa should find the existing id and do an update to the row instead of inserting?
Please suggest if this method looks like a work-around.
You are trying to update the message endTime, First time, it works because there is no entry of that message now when you are trying to update but you are not setting the id by default id is zero and if Id is zero it will try to save the message instead of updating.
For resolving this issue you can check (by finding the message by message because the message is unique) if that message is present then update the endTime.
I am using Jackson API in Vert.x core bundle to decode a JSON string to a java object. Normally this works in almost all cases but for one particular use case. I am constructing the JSON string from the user entered form data and using below line to map it to a java object.
MyClass myClass = io.vertx.core.json.Json.mapper.readValue(jsonString, MyClass.class)
MyClass.java
public class MyClass{
private String ID;
private String description;
//getter and setter methods
}
Input string
{
"description": "“success”,\n “data”: [\n {\n “severity”: “2\",\n “createdby”: “Online user\",\n “product”: “Google map”,\n “description”: “test”,",
"ID": "74085652"
}
When the value of the field description is another JSON string then the mapping fails with an exception.
com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('“' (code 8220 / 0x201c)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name
I have tried adding these com.fasterxml.jackson.core.JsonParser.Feature configurations but it didn't work.
Json.mapper.configure(ALLOW_UNQUOTED_CONTROL_CHARS, true);
Json.mapper.configure(ALLOW_UNQUOTED_FIELD_NAMES, true);
Json.mapper.configure(ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
I am using Vert.x 3.4.1 and Java 8
Am I missing anything here? Any help is greatly appreciated!
this is my code
var myObj =
{
"id": 0,
"createdDate": "12-12-2014 12:00:00",
"fromEmail": "abc#gmail.com",
"sampleBooleanValue": false,
"extraDescrition":"ssfsvgsf",
"sampleArraay":[{"arrayElem1"}, {"arrayElem2"}]
};
console.log(downtime1);
$rootScope.httpPost('createMyObj/', myObj).success(function (successdata) {
console.log(successdata);
}).error(function (errordata) {
console.log(errordata);
});
I have my REST endpoint created with URI createMyObj but as soon As I hit submit I get 400-bead request - the request submitted is syntactically incorrect error.
Is my JSON in correct format?
EDIT:
Here is my corrosponding Java bean
public class MyObj {
#Id
private int id;
private String fonEmail;
#ElementCollection
private List<String> sampleArraay;
private ZonedDateTime createdDate;
private Boolean sampleBooleanValue;
private String extraDescription;
Your array from the sampleArraay field is invalid. Try:
var myObj = {
"id": 0,
"createdDate": "12-12-2014 12:00:00",
"fromEmail": "abc#gmail.com",
"sampleBooleanValue": false,
"extraDescrition":"ssfsvgsf",
"sampleArraay":["arrayElem1", "arrayElem2"]
};
console.log(downtime1);
$rootScope.httpPost('createMyObj/', myObj).success(function (successdata) {
console.log(successdata);
})
.error(function (errordata) {
console.log(errordata);
});
"sampleArraay":[{"arrayElem1"}, {"arrayElem2"}]
Looks to be wrong. Were you planning for the elements of sampleArraay to be nested objects?
Also at the risk of being flippant, the spelling in your example, words like "Array" and "Description" are wrong. Could it be a case of being spelled wrong in one place and not in the other?
One thing I like to do when I get 400 errors like this is progressively simplify the object I am trying to send by commenting out elements until I get to the culprit.
I did this on JSFiddle.com (a great resource) with your code and a simple alert statement to confirm the array problem.
I am using JPA to retrieve data from an Oracle XMLType column. I created a customizer:
#Override
public void customize(final ClassDescriptor descriptor) throws Exception {
descriptor.removeMappingForAttributeName("content");
DirectToXMLTypeMapping mapping = new DirectToXMLTypeMapping();
mapping.setAttributeName("content"); //name of the atribute on the Entity Bean
mapping.setFieldName("CONTENT"); //name of the data base column
mapping.getField().setColumnDefinition("XMLTYPE");
descriptor.addMapping(mapping);
}
and the column in my entity class is:
#Basic(optional = false)
#NotNull
#Lob
//#Column(name = "CONTENT", columnDefinition="XMLTYPE")
private String content;
However, when I run my program I get the error "java.lang.ClassCastException: oracle.xdb.XMLType cannot be cast to java.lang.String
at entities.Sqdocument._persistence_set(Sqdocument.java)
at org.eclipse.persistence.internal.descriptors.PersistenceObjectAttributeAccessor.setAttributeValueInObject(PersistenceObjectAttributeAccessor.java:46)
at org.eclipse.persistence.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1532)
at org.eclipse.persistence.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1423)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:448)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:803)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:607)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:564)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:777)
at org.eclipse.persistence.queries.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:462)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1150)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:852)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1109)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:421)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2946)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1602)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1584)
at org.eclipse.persistence.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolicy.java:323)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2135)
at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternal(OneToOneMapping.java:1716)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:2024)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1369)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:448)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:803)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:719)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:672)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:605)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:564)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:777)
at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:783)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:434)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1150)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:852)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1109)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:393)
"
What could be the problem? Thanks.
Eclipselink is successfully retrieving the XML type. The problem is that XMLType is not an instance of String so it can't be automatically converted.
You need to write a Converter to convert between XMLType and String. You'll also need to write the other side of the converter which goes from String to XMLType, if you want to alter the data in any way.
Take a look at Conversions and Converters for help writing a converter.