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
Related
I have some fields marked with #Column(name = "column1", updatable = false) in entities in jpa repository, and it works as intended but when saving the entity a warning message like this is show:
2020-04-23 18:48:34.358 WARN 1112 --- [nio-8080-exec-6] o.h.p.entity.AbstractEntityPersister : HHH000502: The [column1] property of the [com.nodobanka.core.data.model.Entity1] entity was modified, but it won't be updated because the property is immutable.
I just want to know How Can I stop this warning from printing in log?.
You can set logging level for org.hibernate.persister.entity package to ERROR. That way it'll only display logs with ERROR and FATAL levels.
You can do this in Spring by adding following line in application.properties file:
logging.level.org.hibernate.persister.entity: ERROR
You can use relation for updates (instead of FK field).
Kotlin example:
data class ... (
...
) {
#Column(name = "market_id", nullable = false, insertable = false, updatable = false)
var marketId: Long = 0
/**
* This field is used for updates instead of [marketId] to avoid warning about immutability
*/
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "market_id")
lateinit var market: NiceHashMarket
}
...
entity.market = Market(...)
I have a probléme when i want to persist 2 objet in database
In Request class:
#OneToMany(cascade = CascadeType.PERSIST, mappedBy = "request")
private List documents;
In Document class:
#JoinColumn( referencedColumnName = "ID_REQUEST")
#ManyToOne
Request request
the problem is that when I add request the I find that the 2 object are persisted but in the table Document lD_REQUEST IS ALWAYS NULL
THANK YOU IN ADVANCE and sorry for my English
You need to declare what is the column on the document table that contains the request Id:
#JoinColumn(name = "PARENT_REQUEST")
where PARENT_REQUEST is the name of the column on your Document table
While persisting new data into the database, you've probably added documents to Request's list but forgot to set Request's object to all of your documents on the other side.
Check that you did both things (the following is the example):
Request request = new Request();
//initialization of request
for (...) { //iterate over all document candidates
Document document = new Document();
//initialization of document
document.setRequest(request); //check this!
request.getDocuments().add(document);
}
Also, it seems that you don't have a not-null constraint on ID_REQUEST column. Add this so you won't have this broken data with nullable ID_REQUEST field in the future (constraint violation exception will be raised instead in this kind of situations).
The problem I have is with the querying of data from a chain of 3 tables via the JPA entity framework in a Spring Boot v1.5.3 application. The models are defined as follows:
ValidationField {
#Id id,
name,
#OneToMany(
orphanRemoval = true,
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "validationMessage")
Set<ValidationFieldMessage> messages
}
ValidationFieldMessage {
#Id id,
#ManyToOne(fetch = FetchType.LAZY)
ValidationField validationField
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "validation_message_id")
ValidationMessage validationMessage;
}
ValidationMessage {
#Id id,
text
}
The Spring Data repository method is defined as follows:
List<ValidationField> findByName(String name);
Data example:
Validation_Field
id | name
0 first_name
Validation_Field_Message
id | validation_message_id | validation_field_id
0 0 0
1 1 0
2 2 0
Validation_Message
id | text
0 "There should be no spaces"
1 "No special characters are allowed"
The result from the execution however yields the following:
field {
id:0,
name:first_name,
messages: {
[
id:0,
validationMessage: [
id:1,
text: "No special characters are allowed"
], [
id:1,
text: "No special characters are allowed"
]
]
}
}
The messages are duplicated instead of individually listed.
I've tried with #Query using joins as well, but without success.
Is there something I'm missing in the model definition?
I have a existing database.Need to add new not null column with default value.The same can be done in hibernate 4.3 using ValueGenerator interface.But my project has hibernate 3.6 which does not provide this functionality.Is there any way to do this using hibernate.
You can acchive with #Column with nullable attribute
e.g:
#Column(nullable = false)
private String name = "Jhon Doe";
Also a little bit of a hack using the columnDefinition property of the #Column annotation, for example:
#Column(columnDefinition="double precision default '96'")
private Double grolsh;
You can do this by sql itself.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[WITH VALUES]
E.g:https://www.w3schools.com/sql/sql_default.asp
An example from the hibernate docu (for the default):
#Column(name = "INITIAL_PRICE",
columnDefinition = "number(10,2) default '1'")
#org.hibernate.annotations.Generated(
org.hibernate.annotations.GenerationTime.INSERT
)
private BigDecimal initalPrice;
And for the nullable you can use
#Column(nullable = false)
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.