my scenario is this:
My entity has a relation:
#ManyToOne
#JsonIgnoreProperties(value = "currency2dossiers", allowSetters = true)
private Currency originalCurrency;
in my service, I first save a new entity with all field set to null to have the id and then, in a new Object I set all fields except the originalCurrency that is nullable.
during the 'setting fase' I need to fetch a related entity (with findAll) and I get:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : it.openway.technital.co.domain.Dossier.originalCurrency -> it.openway.technital.co.domain.Currency
at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:380)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
I don't understand why the exception is related to Currency -> originalCurrency which is not required and will not be set.
I've already tried CascadeType.ALL and other solution to similar questions with no success.
Related
I need to persist an Entity named RevenueParty that has OneToMany relationship with another Entity RevenueAccount that further has OneToOne unidirectional relationship with another "reference" data Entity named RevenueCategory
At moment, I have defined the above relationships as follows:
In RevenueParty Entity
#OneToMany(mappedBy = "revenueParty", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RevenueAccount> revenueAccounts= new ArrayList<>();
And in RevenueAccount, I have defined the following relationship:
#OneToOne
#JoinColumn(name="REVENUE_CATEGORY_ID")
private RevenueCategory revenueCategory;
My dilemma is as follows:
When I create a RevenueParty,the record in the corresponding table get created as expected, but nothing gets persisted in the table denoting the RevenueAccount Entity.
What can I do to make the records appear/persist for RevenueAccount Entity?
Thanks
i have a transactional entity and one of the fields is an association with a tenant.
#Entity
public class transactionalClass
....
#OneToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
So this is generate a tenant_id (String) column in my transactionalClass but the type of my field is a object tenant type.
Now, i want to set directly a contextualised string (already have) on tenant_id column when create a new object. I have to do a getTenant and after set field(tenant object) in transactionalClass or is also possible to set string directly once i'm sure the key exists.
Thanks
Currently I am following this URL & implemented the similar kind of code at my end.
But it gives an error at my end something likewise,
null value in column "file_id" violates not-null constraint
Here, category_id is one of my parent_entities primary key.
Following lines where parent entity I am passing properly & checked through Debug,
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new FileHistory(target, action));
UPDATE -
Here, instead of the following config,
#ManyToOne
#JoinColumn(name = "file_id", foreignKey = #ForeignKey(name = "FK_file_history_file"))
I've used,
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "file_id")
Also, I used #PostPersist instead of #PrePersist these are the changes only I did against this article.
I have an Account entity and I'm trying to persist it using save function. My code:
#Override
public Account createAccount(String pin) {
Account account = new Account();
account.setBalance(0L);
account.setPin(pin);
return accountRepository.save(account);
}
Now my entity class has an autogenerated field called accountNumber. My entity class:
#Entity
#Table(name = "accounts")
#Data
public class Account {
#Column(name = "account_number", length = 32, insertable = false)
private String accountNumber;
private Long balance;
}
Now after calling save, the entity returned has accountNumber as null but i can see in the intellij database view that it is actually not null. All the other auto-generated fields like id etc are there in the returned entity just the accountNumber is null. Default value for accountNumber is set in the sql file :
ALTER TABLE accounts
ALTER COLUMN account_number SET DEFAULT DefaultValueSerializer(TRUE, TRUE, 12);
Here, DefaultValueSerializer is the function which is generating the account number.
I've tried other solutions available here like using saveAndFlush() etc, nothing worked in my case. What can be an issue?
As mentioned in comment Hibernate is not aware about what happens in database engine level so it does not see the value generated.
It would be wise to move generation of account number to JPA level instead of using db defaults.
I suggest you to study annotations #GeneratedValue and related stuff like #SequenceGenerator. That way the control of generating account number is in JPA level and there is no need for stuff like refreshing entity after save.
One starting point: Java - JPA - Generators - #SequenceGenerator
For non-id fields it is possible to generate value in method annotated with #PrePersist as other answer suggests but you could do the initialization already in the Accounts constructor .
Also see this answer for options.
You can create an annotated #PrePersist method inside the entity in which you set its fields to their default value.
That way jpa is going to be aware of the default.
There are other such annotation avaiable for different entity lifecycle event https://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/listeners.html
P.s. if you decide to go this way remember to remove the insertable = false
Use
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
for your IDs. And also leave your saving to saveAndFlush so you can immediately see the changes, If any. I'd also recommend separating IDs and account numbers. They should not be the same. Try debugging your program and see where the value stops passing around.
I hope someone can help me solve this problem
I am using spring and JPA to save data.
When I try to save calling my DAO, not all the data gets saved.
Consider the following structure
class User
var name
var surname
#OneToMany(mappedBy = "rule",cascade = CascadeType.PERSIST)
#Fetch(FetchMode.SUBSELECT)
set<Address> address;
#OneToMany(mappedBy = "rule",cascade = CascadeType.PERSIST)
#Fetch(FetchMode.SUBSELECT)
set<Job>job;
class Address
List<AddressList>addressList;
class Job
List<JobList>jobList;
What basically happens is that name and surname changes but if I make any change related to the address or job class, these aren't committed.
However, if I delete the user, it works,if I retrieve the user information(addresses,jobs),these are retrieved correctly.
Any advice on what could be the issue?
You're only cascading the persist operation. When you update an already persisted entity, a merge operation will be performed. So, I suggest to cascade merge operation as well: CascadeType.MERGE if you want to save the related entities on update, too.
Try cascade type all --- CascadeType.ALL.
For orphan removals you should use :
CascadeType.DELETE_ORPHAN - if you are using hibernate
orphanRemoval = true - if you are using jpa 2.0
manual removal - if none of the above apply
Have decalre your transient object #Transient ? ok BTw --
follw below steps:
declare your teansient objects as #Transient
Use cascade type all --- CascadeType.ALL.
try to flush your entitymanager by using entityManager.flush() then perform persist() or merge() operation.