I am inserting a User object with roles(existing) roles .
It is giving me unable insert null in user_role.id
Schema:
#Entity
#Table(name = "user_data")
public class User extends Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* user can have set of roles profiles
*/
#ManyToMany(cascade = {CascadeType.ALL} ,fetch=FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns = { #JoinColumn(name = "user_id", referencedColumnName = "id") }, inverseJoinColumns = { #JoinColumn(name = "role_id", referencedColumnName = "id") })
private Set<Role> roles;
}
#Entity #Table(name = "role")
public class Role extends Serializable {
private static final long serialVersionUID = -5954247513572163065L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name")
private String name;
#ManyToMany
#JoinTable(name = "role_permission", joinColumns = { #JoinColumn(name = "role_id",
referencedColumnName = "id") },
inverseJoinColumns = { #JoinColumn(name = "permission_id",
referencedColumnName = "id") })
private Set<Permission> permissions;
[...]
}
Now when i am trying to create user it is giving me the exception
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("USER_ROLE"."ID")
For creating a user I am using spring repository code as below:
#Override
#Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public User createUser(User user) throws BusinessException {
List<Error> errors = new ArrayList<Error>();
validateUserRoles(user ,errors);
if ( errors.size() > 0 )
{
throw new BusinessException(errors);
}
user.setUserIdentifier(user.getUserIdentifier().trim());
logger.info("Creating User with username: " + user.getUserIdentifier());
return this.userRepositotry.save(user);
}
private void validateUserRoles(User user ,List<Error> errors) {
Set<Role> roles = new HashSet<Role>();
if (user.getRoles() != null)
{
for(Role role : user.getRoles())
{
Role r = null;
if(role.getId() != null)
{
r = this.roleRepository.findOne(role.getId());
} else if( role.getName() != null )
{
r = this.roleRepository.findByName(role.getName());
}
if(r == null)
{
errors.add(new Error(ErrorCode.INVALID_ARGUMENTS,"Invalid user Role.",r));
} else
{
roles.add(r);
}
}
}
user.setRoles(roles);
}
Your user_role join table has an id column, that Hibernate doesn't know about. All hibernate knows about is the role_id and user_id columns. The id column isn't useful, and you should remove it from the user_role table. If you leave it there, you need to make it nullable, or to make it have a default value.
Related
Good morning everyone. Im trying to build an spring application that has two ManyToMany relations between the same entities: A team has several members and leaders.
First entity:
#Entity
#Table(name = "team")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Team implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "team2member", joinColumns = #JoinColumn(name = "team_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"))
private Set<User> members = new HashSet<User>();
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "team2leader", joinColumns = #JoinColumn(name = "team_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"))
private Set<User> leaders = new HashSet<User>();
// Members (ManyToMany)
public Set<User> getMembers() {
return members;
}
public void setMembers(Set<User> members) {
this.members = members;
}
public void addMember(User member) {
this.members.add(member);
}
public void removeMember(User member) {
this.members.remove(member);
}
// Leaders (ManyToMany)
public Set<User> getLeaders() {
return leaders;
}
public void setLeaders(Set<User> leaders) {
this.leaders = leaders;
}
public void addLeader(User leader) {
this.leaders.add(leader);
}
public void removeLeader(User leader) {
this.members.remove(leader);
}
}
Second entity:
#Entity
#Table(name = "user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "team2member", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "team_id", referencedColumnName = "id"))
private Set<Team> teams = new HashSet<Team>();
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "team2leader", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "team_id", referencedColumnName = "id"))
private Set<Team> leadedTeams = new HashSet<Team>();
// Teams (ManyToMany)
public Set<Team> getTeams() {
return teams;
}
public void setTeams(Set<Team> teams) {
this.teams = teams;
}
public void addTeam(Team team) {
this.teams.add(team);
}
public void removeTeam(Team team) {
this.teams.remove(team);
}
// LeadedTeams (ManyToMany)
public Set<Team> getLeadedTeams() {
return leadedTeams;
}
public void setLeadedTeams(Set<Team> leadedTeams) {
this.leadedTeams = leadedTeams;
}
public void addLeadedTeam(Team leadedTeam) {
this.leadedTeams.add(leadedTeam);
}
public void removeLeadedTeam(Team leadedTeam) {
this.leadedTeams.remove(leadedTeam);
}
}
My question: Cause im facing a stackoverflow issue im wondering if it is possible this way. Or maybe there is a better solution for this problem?
StackTrace (shorted):
2018-03-27 01:19:08.635 DEBUG 12656 --- [ XNIO-2 task-12] n.s.aop.logging.LoggingAspect : Exit: net.schwungkraft.service.DocumentService.findAllForOrderHeader() with result = Page 1 of 0 containing UNKNOWN instances
2018-03-27 01:19:08.636 DEBUG 12656 --- [ XNIO-2 task-12] n.s.aop.logging.LoggingAspect : Exit: net.schwungkraft.web.rest.OrderHeaderResource.getDocumentsForOrderHeader() with result = <200 OK,[],{X-Total-Count=[0], Link=[</api/order-headers/%7Bid%7D/documents?page=0&size=20>; rel="last",</api/order-headers/%7Bid%7D/documents?page=0&size=20>; rel="first"]}>
2018-03-27 01:19:08.645 DEBUG 12656 --- [ XNIO-2 task-13] n.s.aop.logging.LoggingAspect : Exit: net.schwungkraft.service.OrderHeaderService.findOneForCurrentUser() with result = OrderHeader{id=3102, orderScopeType='BEWERBUNG', dateStart='null', dateEnd='null', duration=null, classType='null', estimatedNoOfApplicants=null, isTaxLiable='false', amountWithoutTaxes=null, taxesPercent=null, taxesAmount=null, amountWithTaxes=null, extraGrantApplicants=null, extraGrantOthers=null, reminderDate='null', rating='null', ratingText='null', category='null', freeText='null', histComissionRateTitle=null, histPaymentTermDescription='3D', histPaymentTimeLimit=null, histPaymentTermTimeLimitForDiscount=null, histPaymentTermDiscount=null, histContactName='test', histContactStreet='null', histContactPostCode=null, histContactCity='null', histContactCountry='null', histContactContactPerson='null', histContactEmail='null', histContactPhoneNumber='null'}
2018-03-27 01:19:08.645 DEBUG 12656 --- [ XNIO-2 task-13] n.s.aop.logging.LoggingAspect : Exit: net.schwungkraft.web.rest.OrderHeaderResource.getOrderHeader() with result = <200 OK,OrderHeader{id=3102, orderScopeType='BEWERBUNG', dateStart='null', dateEnd='null', duration=null, classType='null', estimatedNoOfApplicants=null, isTaxLiable='false', amountWithoutTaxes=null, taxesPercent=null, taxesAmount=null, amountWithTaxes=null, extraGrantApplicants=null, extraGrantOthers=null, reminderDate='null', rating='null', ratingText='null', category='null', freeText='null', histComissionRateTitle=null, histPaymentTermDescription='3D', histPaymentTimeLimit=null, histPaymentTermTimeLimitForDiscount=null, histPaymentTermDiscount=null, histContactName='test', histContactStreet='null', histContactPostCode=null, histContactCity='null', histContactCountry='null', histContactContactPerson='null', histContactEmail='null', histContactPhoneNumber='null'},{}>
2018-03-27 01:19:09.162 ERROR 12656 --- [raft-Executor-2] n.s.c.audit.AsyncEntityAuditEventWriter : Exception while getting entity ID and content {}
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.collection.internal.PersistentSet[1]->net.schwungkraft.domain.User["leadedTeams"]->org.hibernate.collection.internal.PersistentSet[0]->net.schwungkraft.domain.Team["members"]->org.hibernate.collection.internal.PersistentSet[1]->net.schwungkraft.domain.User["leadedTeams"]->org.hibernate.collection.internal.PersistentSet[0]->net.schwungkraft.domain.Team["members"]->org.hibernate.collection.internal.PersistentSet[1]->net.schwungkraft.domain.User["leadedTeams"]->org.hibernate.collection.internal.PersistentSet[0]->net.schwungkraft.domain.Team["members"]->org.hibernate.collection.internal.PersistentSet[1]->net.schwungkraft.domain.User["leadedTeams"]->org.hibernate.collection.internal.PersistentSet[0]->net.schwungkraft.domain.Team["members"])
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:705)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149)
I used this wizard to create entity classes from my database. Some tables have not been transformed into classes, but there are attributes that identify the relationships.
this is my db ERD (mysql)
and this is the user entity class (attributes)
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findByOid", query = "SELECT u FROM User u WHERE u.oid = :oid"),
#NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"),
#NamedQuery(name = "User.findByAddress", query = "SELECT u FROM User u WHERE u.address = :address"),
#NamedQuery(name = "User.findBySince", query = "SELECT u FROM User u WHERE u.since = :since")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "oid")
private Integer oid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 15)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 15)
#Column(name = "password")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "email")
private String email;
#Size(max = 50)
#Column(name = "address")
private String address;
#Basic(optional = false)
#NotNull
#Column(name = "since")
#Temporal(TemporalType.DATE)
private Date since;
#JoinTable(name = "favorite", joinColumns = {
#JoinColumn(name = "user_oid", referencedColumnName = "oid")}, inverseJoinColumns = {
#JoinColumn(name = "wheelchair_oid", referencedColumnName = "oid")})
#ManyToMany
private List<Wheelchair> wheelchairList;
#ManyToMany(mappedBy = "userList1")
private List<Wheelchair> wheelchairList1;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOid")
private List<Comment> commentList;
#JoinColumn(name = "role_oid", referencedColumnName = "oid")
#ManyToOne(optional = false)
private Role roleOid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userOid")
private List<Orthopedy> orthopedyList;
public User() {
}
...
i can't understand something:
where is the OWN join table?
why i have userList1 and wheelchairList1? should it identifies OWN table? in this case i can rename it here or i have to rename it in some xml file?
why of
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userOid")
private List<Orthopedy> orthopedyList;
?
it should be OneToOne...
moreover the "JSF from entities class" wizard creates CRUD operation to manage Users, how can i manage join tables? I need to write something in the controller like what?
can you please link me some resource where i can learn this?
thank you so much
While Creating Entities It Creates Classes For All Tables With Primary Key
But not for tables that have many to many relations . its managed by their parent classes it is maintained as a list.
This is my code for managing my many to many table of SubjectFaculty which has details of Faculty and Subjects
Assigning A Subject To Faculty
public void assignFacultyToSubject(String facultyUname, Integer subjectId) {
try {
Subject oSubject = em.find(Subject.class, subjectId);
Faculty oFaculty = em.find(Faculty.class, facultyUname);
College oCollege = em.find(College.class, oFaculty.getCollegeUname().getCollegeUname());
List<Faculty> lstFaculty = oSubject.getFacultyList();
List<Subject> lstSubject = oFaculty.getSubjectList();
if (!lstSubject.contains(oSubject)) {
lstFaculty.add(oFaculty);
lstSubject.add(oSubject);
oSubject.setFacultyList(lstFaculty);
oFaculty.setSubjectList(lstSubject);
em.merge(oSubject);
em.getEntityManagerFactory().getCache().evictAll();
} else {
System.out.println("Entry Already Found");
}
} catch (Exception e) {
System.out.println("Error :- " + e.getMessage());
}
}
Removing Subject And Faculty Details Form Many to Many Table
#Override
public void removeFacultySubject(String facultyUname, Integer subjectId) {
try {
Subject oSubject = em.find(Subject.class, subjectId);
Faculty oFaculty = em.find(Faculty.class, facultyUname);
List<Subject> lstSubject = oFaculty.getSubjectList();
List<Faculty> lsFaculty = oSubject.getFacultyList();
lstSubject.remove(oSubject);
lsFaculty.remove(oFaculty);
em.merge(oSubject);
} catch (Exception e) {
System.out.println("Error :- " + e.getMessage());
}
}
I am asking about WHERE clause. I have searched internet but I didn`t find answer for my question.
I have a few entity classes, which i represent below:
#NamedQuery(name = "selectTrasy",
query = "SELECT t FROM Trasa t WHERE t.raport = :raport ORDER BY t.id")
#Entity
public class Trasa implements Serializable {
#Id
#Column(name = "id", unique = true )
#GeneratedValue
private Long id;
#Column(name = "data_z")
private Date dataz;
#Column(name = "data_do")
private Date datado;
#Column(name = "czas_z")
private String czasZ;
#Column(name = "czas_do")
private String czasDo;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "miejscowosc_z")
private MiejscowoscDB miejscowoscZ;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "miejscowosc_do")
private MiejscowoscDB miejscowoscDo;
#OneToOne(fetch = FetchType.LAZY)
private Uzytkownik user;
#OneToOne(fetch = FetchType.LAZY)
private Raport raport;
#Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((Trasa) other).id)
: (other == this);
}
#Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
//next I have getters and setters
}
#Entity
public class Raport implements Serializable {
#Id
#Column(name = "id", unique = true )
#GeneratedValue
private Long id;
#Column(name = "data")
private Date data;
#Column(name = "nazwa")
private String nazwa;
#Enumerated(EnumType.STRING)
private Powod powod;
#OneToOne(fetch = FetchType.LAZY)
private Uzytkownik uzytkownik;
#Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((Raport) other).id)
: (other == this);
}
#Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
//getters and setters
}
My question is why this query doesn`t work properly. Returned list is empty, but recordes exists in database, when I want return all Trasa records there is everything ok, only not works when I add WHERE clause with raport property.
trasy = (List<Trasa>)(manager.createNamedQuery("selectTrasy")
.setParameter("raport", propertyWydatek.getRaport())
.getResultList());
Change your query to:
#NamedQuery(name = "selectTrasy",
query = "SELECT t FROM Trasa t WHERE t.raport.id = :raportId ORDER BY t.id")
and run it like this:
trasy = (List<Trasa>)(manager.createNamedQuery("selectTrasy")
.setParameter("raportId", propertyWydatek.getRaport().getId())
.getResultList());
Other version of the query:
#NamedQuery(name = "selectTrasy",
query = "SELECT t FROM Trasa t join t.raport r WHERE r.id = :raportId ORDER BY t.id")
I have a large DB on MySql Workbench and I'm trying to map the relationship between the entities on Eclipse Mars thanks to Hibernate and the JPA module. The fact is that I receive the error:
"In attribute 'personAddresses', the "mapped by" attribute 'peopleAdd' has an invalid mapping type for this relationship."
This are the entities involved.
1
I've to say that making a forward engineering, Hibernate creating for me an AddressId class, where the composite primary key of Address is mapped. I suspect that the problem could be this, but I'm not certain, can you help me please?
Under I post the code so that it's more clear to understand how the classes are implemented.
#Entity
#IdClass(AddressId.class)
#Table(schema = "YouDroop", name = "Address")
public class Address implements Serializable
{
...
private Collection<Person> peopleAdd = new HashSet<Person>();
#Id
#Column(name = "Address", length = 45, unique = true, nullable = false)
private String address;
#Id
#Column(name = "Number", unique = true, nullable = false)
private int number;
...
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "PersonHasAddress",
joinColumns = {
#JoinColumn(name = "Address_Address", referencedColumnName = "Address", nullable = false),
#JoinColumn(name = "Address_Number", referencedColumnName = "Number", nullable = false)
},
inverseJoinColumns = {#JoinColumn(name = "Person_Email", referencedColumnName = "Email", nullable = false)}
)
public Collection<Person> getPeopleAddressed(){
return this.peopleAdd;
}
public void setPeopleAddressed(Collection<Person> people){
this.peopleAdd = people;
}
}
public class AddressId implements Serializable
{
private String address;
private int number;
public AddressId(){}
public AddressId(String address, int number) {
super();
this.address = address;
this.number = number;
}
...
}
#Entity
#Table(name = "Person", schema = "YouDroop", uniqueConstraints =
{ #UniqueConstraint(columnNames = "NickName"),
#UniqueConstraint(columnNames = "Password") })
public class Person implements Serializable
{
...
private Collection<Address> addresses = new HashSet<Address>();
...
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "peopleAdd")
public Collection<Address> getPersonAddresses(){
return this.addresses;
}
public void setPersonAddresses(Collection<Address> addresses){
this.addresses = addresses;
}
}
Since you placed you #ManyToMany annotation on your getter method (or property) and not on the field. The mappedBy attribute should reference the property instead and not the field.
#ManyToMany
public Collection<Person> getPeopleAddressed() {
...
}
So your mappedBy attribute should have been
#ManyToMany(mappedBy="peopleAddressed")
public Collection<Address> getPersonAddresses() {
...
}
I got a problem with JPA and ManyToMany association.
I got two class FOA_PARAM_EMPLOYE and FOA_PARAM_POSITION, and an association table FOA_PARAM_EMPLOYE_POSITION.
Class FoaParamEmploye :
#Entity
#Table(name = "FOA_PARAM_EMPLOYE")
#NamedQuery(name = "FoaParamEmploye.findAll", query = "SELECT f FROM FoaParamEmploye f")
public class FoaParamEmploye implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private FoaParamEmployePK id;
#Column(name = "ACTEUR_MAJ_OCCUR")
private String acteurMajOccur;
#Column(name = "ADRESSE_EMAIL")
private String adresseEmail;
// bi-directional many-to-many association to FoaParamPosition
#ManyToMany
#JoinTable(
name = "FOA_PARAM_EMPLOYE_POSITION",
joinColumns = { #JoinColumn(name = "ID_EMPLOYE"),
#JoinColumn(name = "COD_ENTREP") },
inverseJoinColumns = { #JoinColumn(name = "ID_POSITION")
})
private List<FoaParamPosition> foaParamPositions;
public FoaParamEmployePK getId() {
return this.id;
}
public void setId(FoaParamEmployePK id) {
this.id = id;
}
public String getActeurMajOccur() {
return this.acteurMajOccur;
}
public void setActeurMajOccur(String acteurMajOccur) {
this.acteurMajOccur = acteurMajOccur;
}
public String getAdresseEmail() {
return this.adresseEmail;
}
public void setAdresseEmail(String adresseEmail) {
this.adresseEmail = adresseEmail;
}
public List<FoaParamPosition> getFoaParamPositions() {
return foaParamPositions;
}
public void setFoaParamPositions(List<FoaParamPosition> pFoaParamPositions) {
this.foaParamPositions = pFoaParamPositions;
}
}
Class FoaParamPosition :
#Entity
#Table(name="FOA_PARAM_POSITION")
#NamedQuery(name="FoaParamPosition.findAll", query="SELECT f FROM FoaParamPosition f")
public class FoaParamPosition implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private FoaParamPositionPK id;
#Column(name="ACTEUR_MAJ_OCCUR")
private String acteurMajOccur;
#Column(name="CD_PROFIL_AFFECTATION")
private String cdProfilAffectation;
// bi-directional many-to-many association to FoaParamEmploye
#ManyToMany
private List<FoaParamEmploye> foaParamEmployes;
public FoaParamPositionPK getId() {
return this.id;
}
public void setId(FoaParamPositionPK id) {
this.id = id;
}
public String getActeurMajOccur() {
return this.acteurMajOccur;
}
public void setActeurMajOccur(String acteurMajOccur) {
this.acteurMajOccur = acteurMajOccur;
}
public String getCdProfilAffectation() {
return this.cdProfilAffectation;
}
public void setCdProfilAffectation(String cdProfilAffectation) {
this.cdProfilAffectation = cdProfilAffectation;
}
public List<FoaParamEmploye> getFoaParamEmployes() {
return foaParamEmployes;
}
public void setFoaParamEmployes(List<FoaParamEmploye> pFoaParamEmployes) {
this.foaParamEmployes = pFoaParamEmployes;
}
}
Table FOA_PARAM_EMPLOYE_POSITION has this columns :
COD_ENTREP
ID_EMPLOYE
ID_POSITION
XQCIF
ACTEUR_MAJ_OCCUR
DATE_HEURE_MAJ_OCCUR
I got this exception :
A Foreign key refering com.groupama.middlgan.entities.FoaParamPosition from
com.groupama.middlgan.entities.FoaParamEmploye has the wrong number of column.
should be 2
If I add COD_ENTREP on inverseJoinColumns in my FoaParamEmploye entity, I got this exception :
Repeated column in mapping for collection:
com.groupama.middlgan.entities.FoaParamEmploye.foaParamPositions column: COD_ENTREP
Any idee ?
[I am assuming you are listing the columns for the association table FOA_PARAM_EMPLOYE_POSITION, not FOA_PARAM_EMPLOYE, as you state in your question.]
Your mappings imply FOA_PARAM_EMPLOYE_POSITION.COD_ENTREP is part of two foreign keys, one referencing FOA_PARAM_EMPLOYE and one referencing FOA_PARAM_POSITION. In practice these two foreign keys might contain the same value for COD_ENTREP, but this cannot be enforced by the database or JPA.
You should probably model the relationship differently, possibly add another, container-like, object that has bi-directional one-to-many relationships with both FoaParamEmploye and FoaParamPosition and shares parts of its primary key with the other two primary keys.
If you want to keep your inverseJoinColumn mapping you can do as follows,
#ManyToMany
#JoinTable(
name = "FOA_PARAM_EMPLOYE_POSITION",
joinColumns = { #JoinColumn(name = "ID_EMPLOYE"),
#JoinColumn(name = "COD_ENTREP") }
,
inverseJoinColumns = {#JoinColumn(name = "FOAPARAMPOSITION_COD_ENTREP"), #JoinColumn(name = "FOAPARAMPOSITION_ID_POSITION")}
)
private List<FoaParamPosition> foaParamPosition;
and
#ManyToMany
#JoinTable(
name = "FOA_PARAM_EMPLOYE_POSITION",
joinColumns = { #JoinColumn(name = "ID_POSITION"),
#JoinColumn(name = "COD_ENTREP") }
,
inverseJoinColumns = {#JoinColumn(name = "FOAPARAMEMPLOYE_COD_ENTREP"), #JoinColumn(name = "FOAPARAMEMPLOYE_ID_EMPLOYE")}
)
private List<FoaParamEmploye> foaParamEmploye;
the mappings are aligned with the code you've posted in your other question JPA Many To Many Select