org.hibernate.AnnotationException: mappedBy reference an unknown target entity property - jpa

I am trying to do a "many to many" jpa mapping.
I have a table called "Account":
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "account_user",
joinColumns = { #JoinColumn(name = "account_id") },
inverseJoinColumns = { #JoinColumn(name = "user_id") })
private Set<User> users = new HashSet<>();
I have table called "User":
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "user")
#JsonIgnore
private Set<Account> accounts = new HashSet<>();
I get the following error:
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.bank.account.model.Account.user in com.bank.account.model.User.accounts
A join "many to many" table called "AccountUser" is supposed to be created by the mapping.
Any help or hint would be greatly appreciated it!!

MappedBy must refer to the attribute name in the target class. In your case it's users not user.
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "users")
#JsonIgnore
private Set<Account> accounts = new HashSet<>();

Related

How to save a copy of a entity

I use spring boot 3, I have this entity structure
#Data
#Entity
#Table
public class Repo {
#Id
#NotNull
private Long repoId;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "repo", cascade = {CascadeType.ALL})
private List<Pub> pubs = new ArrayList<>(0);
...
}
#Data
#Entity
#Table
public class Pub {
#Id
#Column
#NotNull
protected Long pubId;
#ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
#JoinColumn(name = "type_id")
protected TypeDoc typeDoc;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pub", cascade = {CascadeType.ALL}, orphanRemoval = true)
protected List<Person> persons = new ArrayList<>(0)
#ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
#JoinTable(name = "pub_cat", schema = "", joinColumns = { #JoinColumn(name = "pub_id", nullable = true, updatable = false) }, inverseJoinColumns = { #JoinColumn(name = "cat_pub_id", nullable = true, updatable = false) })
private List<CatPub> catPub = new ArrayList<>(0);
}
A repo has a lit of pub, in reality they can have only 2.
So I feed a Pub object..... put it it the list of depot, and i need to create exactly the same and put it in the list of depot.
what is the most effective way to do it?

jpa OneToMany / ManyToOne how to save data

I'm learnig jpa and have a general question to saving data.
Suppose we have two entities:
Parent entity: Person
#JsonIgnore
#OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Car> cars = new HashSet<Car>();
Child entity: Car
#ManyToOne(fetch = FetchType.EAGER)
#JoinTable(name = "customer_car", joinColumns = #JoinColumn(name = "car_id"),
inverseJoinColumns = #JoinColumn(name = "person_id"))
private Person person;
The question is: What is the correct way to save data:
Person-Controller: I should use a #PostMapping to post a person with many cars.
Car-Controller: I should use a #PostMapping to post a car with many persons.
Option 1 and option 2 are possible

How to delete entities in a chained one-to-many and many-to-many JPA relationship

I have a chain of entities as follows:
#Entity
#Table(name = "Patients")
public class Patient extends TimeStampedPersistable{
private static final long serialVersionUID = 1L;
#OneToMany(mappedBy="patient", cascade = CascadeType.ALL)
#PrivateOwned
private List<Insurance> insurances;
}
#Entity
#Table(name = "insurance")
public class Insurance extends PersistableEntity {
private static final long serialVersionUID = 1L;
#ManyToOne(optional=false)
#JoinColumn(name="patient_id", nullable=false)
private Patient patient;
#Column(name = "policy_number", unique = false, nullable = true)
private String policyNumber;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "insurance_companycodes", joinColumns = {
#JoinColumn(name = "insurance_id", referencedColumnName = "id", nullable = false, updatable = false) }, inverseJoinColumns = {
#JoinColumn(name = "insuranceCompanyCode_id", referencedColumnName = "id", nullable = false, updatable = false) })
private Set<InsuranceCompanyCode> insuranceCompanyCodes = new HashSet<>();
}
#Entity
#Table(name = "insurance_company_codes")
public class InsuranceCompanyCode extends PersistableEntity {
private static final long serialVersionUID = 1L;
#Column(name = "identifier", unique = true, nullable = true)
private String identifier;
#ManyToMany(mappedBy = "insuranceCompanyCodes", fetch = FetchType.LAZY)
private Set<Insurance> insurances = new HashSet<>();
}
I need to remove insurance items from the Patient object. I am using the following code:
for (Iterator<Insurance> iterator = patient.getInsurances().iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
This seems to work for child entities that don't have child entities, however in this situation the Insurance entity has child entities and is not actually removed (no exceptions are displayed). Note, I am using the EclipseLink specific annotation #PrivateOwned which I expected would have forced the removal of the Insurance entities.
Any guidance, suggestions appreciated!

detached entity passed to persist: A class with ManyToOne relation to 2 more classes

Comment class
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_id")
private User user;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "image_id")
private Image image;
User class
#OneToMany(mappedBy = "user", cascade = CascadeType.MERGE, fetch =
FetchType.EAGER)
private List<Comment> comments = new ArrayList<>();
Image class
#OneToMany(mappedBy = "image",cascade = CascadeType.MERGE,fetch =
FetchType.EAGER)
private List<Comment> comments = new ArrayList<Comment>();
These are the ManyToOne and OneToMany relations I have. I am unable to persist the Comment object due to "detached entity passed to persist: ImageHoster.model.Comment" error.
I kind of figured out the issue. In the CommentRepository class where I am persisting the Comment object, I used .merge instead of .persist
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
try{
transaction.begin();
em.merge(newComment);
instead of em.persist(newComment);

Entity Object Not Getting Persisted: New object was found through a relationship that was not marked

I am trying to persist the following entity:
public class CommentEntity {
#Id
#ManyToOne(optional=false,cascade=CascadeType.REFRESH, targetEntity=UserEntity.class)
#JoinColumn(name="USERID",referencedColumnName="USERID")
private UserEntity userEntity;
#ManyToOne(optional=false,cascade=CascadeType.REFRESH, targetEntity=PostEntity.class)
#JoinColumn(name="POSTID",referencedColumnName="POSTID")
private PostEntity postEntity;
}
But the error comes out:
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: entity.PostEntity#16afec.
when I try to persist PostEntity, it is persisted. No such exception is thrown:
public class PostEntity {
#ManyToOne(optional = false, cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, targetEntity = UserEntity.class)
#JoinColumn(name = "USERID", referencedColumnName = "USERID")
private UserEntity userEntity;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "postEntity", fetch = FetchType.LAZY)
private List<CommentEntity> commentEntityList;
}
Why it is happening? UserEntity is:
public class UserEntity {
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntity")
private List<PostEntity> postEntityList;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntity")
private List<CommentEntity> commentEntityList;
}
I am persisting commentEntity using the code:
entityManagerFactory = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(commentEntity);
entityTransaction.commit();
entityManager.close();
I am not able to understand what can be the cause? And then why PostEntity is getting persisted in the same situation?
I am using EclipseLink
Because you try to persist CommentEntity that have either userEntity or postEntity (or both) referencing to the entity that is not persisted. Call to em.persist(instance of commentEntity) does not cause those entities to be persisted, because you cascaded only refresh. You should persist those entities with separate calls to em.persist.
If this does not answer to your question, please provide the code that creates entities and persists them.