jpa mapping two properties - java

I need CompanyUser.companyRolCompanyUsers property with OneToMany relation, completed in each query.
JPA company_usr entity:
#Entity
#Table(name = "company_usr")
public class CompanyUser extends BaseModel implements Serializable {
#Id
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(nullable = false)
private Company company;
#Id
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "usr_id", nullable = false)
private User user;
#Column(nullable = false)
private Boolean external;
#OneToMany(fetch = FetchType.EAGER)
private List<CompanyRolCompanyUser> companyRolCompanyUsers;
....
JPA companyRol_companyUsr entity:
#Entity
#Table(name = "companyRol_companyUsr")
public class CompanyRolCompanyUser extends BaseModel implements Serializable {
#Id
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumns({
#JoinColumn(name="companyuser_company_id", referencedColumnName="company_id"),
#JoinColumn(name="companyuser_usr_id", referencedColumnName="usr_id")
})
private CompanyUser companyUser;
#Id
#ManyToOne(fetch = FetchType.EAGER)
private CompanyRol companyRol;
....
How to set mappedBy in companyRolCompanyUsers property correctly?

If i get what you want to achieve i think you need something like :
#OneToMany(fetch = FetchType.EAGER, mappedBy="companyUser")
private List<CompanyRolCompanyUser> companyRolCompanyUsers;

You can have two properties for the same column like this :
#JoinColumn(name = "CGRADO_CODIGO", referencedColumnName = "CGRADO_CODIGO")
#ManyToOne
#NotFound(action=NotFoundAction.IGNORE)
private SipreGrado sipreGrado;
#Column(name = "CGRADO_CODIGO",insertable=false,updatable=false)
private String sipreGradoCodigo;
Remember if you have sometimes the entity NULL you can skip it with that annotation
#NotFound(action=NotFoundAction.IGNORE)
Also,Remember to set
insertable=false,updatable=false
for the one that you dont want to include in the insert/update queries.

Related

“Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements” SpringBoot

i have three entites named depense ,benifice and categories , when i want to get the benefice_C and the Depenese_C in the category entity .this error displayed to me
“Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements” SpringBoot
Depens Entities
> #Entity
#Getter
#Setter
#Table(name="depense")
public class Depense {
#Id #GeneratedValue
#Column(name = "id_etab")
private Long idEtab;
#ManyToOne
#JoinColumn(name = "personnel_id")
private Personnel personnel;
#ManyToOne
#JoinColumn(name = "CATD")
private Categories categoriesD;
Benfice Entities
> public class Benifice {
#Column(name = "id_etab")
private Long idEtab;
#ManyToOne
#JoinColumn(name = "inscrit_id")
private Inscrit inscrit;
#ManyToOne
#JoinColumn(name = "be_C")
private Categories benificeC;
Categorie entite
> public class Categories implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idCat;
#OneToMany(mappedBy = "categoriesD", fetch = FetchType.LAZY)
private Depense depense;
#OneToMany(mappedBy = "benificeC", fetch = FetchType.LAZY)
private Benifice benifice;
Your #OneToMany mapping is not correct.
You would need a List/Set/Collection of Objects if you map OneToMany.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idCat;
#OneToMany(mappedBy = "categoriesD", fetch = FetchType.LAZY)
private List<Depense> depense;
#OneToMany(mappedBy = "benificeC", fetch = FetchType.LAZY)
private List<Benifice> benifice;

HIbernate ignore fetching data from OnetoMany field

I would like to ignore #OnetoMany field in my entity. fetch data need to get actual fields but don't want to fire query to dependent table. But deleting data from parent table needs deletion from dependent table
I have tried #Transient that ignores but the delete is also being ignored. Is there any other option to tell JPA not to fetch data from childs table when i call the parent entity?
#Entity
Table(name = "User")
public class UserEntity implements Serializable {
#Id
#Column(name = "id")
private int id;
#Column(name = "SERIAL", unique = true, nullable = false)
private String serial;
#OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL)
private Set<UserActionEntity> userActionsById;
}
#Table(name = "user_action")
public class UserActionEntity implements Serializable {
#Id
#Column(name = "id")
private int id;
#Column(name = "action")
private String action;
#ManyToOne
#JoinColumn(name = "USER_ID", referencedColumnName = "ID", nullable = false)
private UserEntity userByUserId;
If you don't want to fire query to dependent table, you can use (fetch = FetchType.LAZY) on UserActionEntity property.
#OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<UserActionEntity> userActionsById;

Hibernate MappedBy for Multiple columns

I am using Postgresql for my database and it contains a table called user and a table called friendship, which has 2 foreign keys userA_id and userB_id. I know how to use mappedBy to check for friendships based on userA_id but I am not sure how to check for userB_id. Is there a way to tell hibernate to check a user ID from user table with both of columns on friendship table?
EDIT: Here is the code I currently have.
#Entity
#Table(name = "users")
public class UserDB implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userid", nullable=false)
public int userID; //not null
#OneToMany (targetEntity = FriendshipDB.class, mappedBy = "userA_ID", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
//#OneToMany (targetEntity = FriendshipDB.class, mappedBy = "userB_ID", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
public List<FriendshipDB> friends = new ArrayList<>();
}
#Entity
#Table(name = "friendships")
public class FriendshipDB implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "friendshipid", nullable = false)
private int friendshipID; //not null
#ManyToOne
#JoinColumn(name="usera_id")
private UserDB userA_ID; //not null
#ManyToOne
#JoinColumn(name = "userB_id")
private UserDB userB_ID;
}
I think this is very specific mapping but the only solution I know is to go with 2 association like this:
#OneToMany(mappedBy = "user1")
private Collection<User> usersByFirst;
#OneToMany(mappedBy = "user2")
private Collection<User> usersBySecond;

Spring Data Rest Projection to get value from different entity

I have two entities. One is the parent (for which I have a projection) and the other entity has FK relation with the parent. My parent entity does "not" have bidirectional relationship (mappedBy).
How do I expose/get the child entity in the projection I have for the parent.
Here is how I want.
Parent:
public class EntityA implements java.io.Serializable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ENTITYAID", unique = true, nullable = false)
private Integer entityAID;
......
}
Child:
public class EntityB {
#EmbeddedId
private EntityBPk entityBPk;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ENTITYAID", referencedColumnName = "ENTITYAID",insertable=false,updatable=false)
private EntityA entityA;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ENTITYCID", referencedColumnName = "ENTITYCID",insertable=false,updatable=false)
private EntityC entityC;
#Column(name = "DUMMY")
private String dummy;
}
I want to access EntityB from EntityA's projection. Something like below.
Projection for EntityA:
#Projection(name = "projEntityA", types = { EntityA.class })
public interface EntityAProjection {
.....
Set<EntityB> getEntityBs();
}
Note:
But I don't have any reference of EntityB inside EntityA (since I don't want bidirectional relationship)
This may not be needed. But just FYI.
public class EntityBPk implements Serializable {
#Column(name = "ENTITYAID", nullable = false)
private Integer entityAID;
#Column(name = "ENTITYCID", nullable = false)
private Integer entityCId;
}
Thanks
Bharath

Inheritance in JPA not working

I have a parent class:
#MappedSuperclass
public class BaseText implements Serializable {
#Column(name = "LOCALE_CODE", nullable = false)
private String localeCode;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#Index
#Column(name = "LOCALIZED_TEXT_ID", nullable = false)
#ForeignKey
private LocalizedText localizedText;
//getters and setters
}
And one of the sub classes:
#Entity
#Table(name = "ASSESSMENT_TEXT")
#AttributeOverride(name = "localeCode", column = #Column(name = "LOCALE_CODE"))
#AssociationOverride(name = "localizedText", joinColumns = #JoinColumn(name = "LOCALIZED_TEXT_ID"))
public class AssessmentText extends BaseText {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#Index
#Column(name = "ASSESSMENT_ID", nullable = false)
#ForeignKey
private Assessment assessment;
//Getters and setters.
}
When I am trying to persist an object I get the following error:
org.apache.openjpa.persistence.ArgumentException: Superclass field "java.lang.Object.localizedText" is mapped in the metadata for subclass "com.my.com.AssessmentText", but is not a persistent field.
What is causing this and how to solve it?
I am using embedded derby database in JUnit and the JPA implementation is OpenJPA.
I am not sure that it is the solution, but I miss an #Inheritance annotation from AssessmentText:
#Entity
#Table(name = "ASSESSMENT_TEXT")
#Inheritance(strategy=InheritanceType.JOINED)
#AttributeOverride(name = "localeCode", column = #Column(name = "LOCALE_CODE"))
#AssociationOverride(name = "localizedText",
joinColumns = #JoinColumn(name = "LOCALIZED_TEXT_ID"))
public class AssessmentText extends BaseText {
I had the same issue, and solved it by adding the MappedSuperClass to the persistence.xml.
I know this is also in the comments somewhere, but the useful one was hidden and I think this should be an answer, not a comment to the question.

Categories