#ManyToMany association isn't inserted in the second table - java

I want to insert data into a table that is associated with another table in a relationship ManyToMany. When I insert the data, it is inserted into the table but the association with the other data that is in the second table is not. This is a Java EE application using JSF2+Spring+Hibernate.
Here is the entity:
#Entity
#Table(name="USER")
public class User {
private int id;
private String nom;
private Set<Formation> mesformations;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "USER_ID")
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the nom
*/
#Column(name="NOM",length=50)
public String getNOM() {
return nom;
}
/**
* #param nom the nom to set
*/
public void setNom(String nom) {
this.nom = nom;
}
/**
* #return the mesFormations
*/
#ManyToMany
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
#JoinTable(name = "USER_FORM",
joinColumns = #JoinColumn(name = "user_id",
referencedColumnName = "USER_ID"),
inverseJoinColumns = #JoinColumn(name = "form_id", referencedColumnName = "ID"))
public Set<Formation> getMesFormations() {
return mesFormations;
}
/**
* #param mesFormations the mesFormations to set
*/
public void setMesFormations(Set<Formation> mesFormations) {
this.mesFormations = mesFormations;
}
public void addToFormation(Formation formation) {
if(mesFormation==null)
{
mesFormations=new HashSet<Formation>();
}
mesFormations.add(formation);
}
.....
}
Formation.java
#Entity
#Table(name="Foramtion")
public class Formation {
private int id;
private String nomFormation;
private int nombreMatiere;
private Set<User> mesUsers;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the mesUsers
*/
#ManyToMany(mappedBy = "mesFormations",fetch=FetchType.LAZY)
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
public Set<User> getMesUsers() {
return mesUsers;
}
/**
* #param mesUsers the mesUsers to set
*/
public void setMesUsers(Set<User> mesUsers) {
this. mesUsers = mesUsers;
}
/**
* #return the nomFormation
*/
#Column(name="NOM_FORMATION",length=50,unique=true)
public String getNomFormation() {
return nomForamtion;
}
/**
* #param nomFormation the nomForamtion to set
*/
public void setNomForamtion(String nomForamtion) {
this.nomForamtion = nomForamtion;
}
/**
* #return the nombreMatiere
*/
public int getNombreMatiere() {
return nombreMatiere;
}
/**
* #param nombreMatiere the nombreMatiere to set
*/
public void setNombreMatiere(int nombreMatiere) {
this.nombreMatiere = nombreMatiere;
}
public void addToUser(User user) {
if(mesUser==null)
{
mesUsers=new HashSet<User>();
}
mesUsers.add(user);
user.addToFormation(this);
}
public void removeFromUser(User user) {
this.getMesUsers().remove(user);
user.getMesUsers().remove(this);
}
}
the method of the DAO layer which allows for the persistence of a user
public User enregistrer(User user) {
// TODO Auto-generated method stub
this.getSession().beginTransaction();
this.getSession().persist(user);
this.getSession().beginTransaction().commit();
return Entity ;
}
the method of the service layer that allows to call the save method of the dao layer
public User persistUser(User user, List<Integer> idList){
for(Integer id : idList){
Formation form = iformationDao.findById(id);
form.addToUser(user);
}
return iuserDao.enregistrer(user);
thank for answering

It looks to me like you have your CascadeTypes set to:
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
yet you are calling:
this.getSession().persist(user);
I think you will need to add CascadeType.PERSIST to your #Cascade annotation to get the behavior you desire.

change from
public User enregistrer(User user) {
// TODO Auto-generated method stub
this.getSession().beginTransaction();
this.getSession().persist(user);
this.getSession().beginTransaction().commit();
return Entity ;
}
to
public User enregistrer(User user) {
// TODO Auto-generated method stub
Transaction tx = this.getSession().beginTransaction();//change
this.getSession().persist(user);
tx.commit();//change
return Entity ;
}

Related

Olingo 2.0.6 JPA Extension: EdmComplexTypeImplProv cannot be cast to EdmSimpleType

When using the JPA Extension to scan an entity that includes #Embedded objects the $metadata is created correctly with ComplexTypes. However, when retrieving the entity I receive a ClassCastException:
org.apache.olingo.odata2.core.edm.provider.EdmComplexTypeImplProv
cannot be cast to org.apache.olingo.odata2.api.edm.EdmSimpleType
Class:
org.apache.olingo.odata2.jpa.processor.core.access.data.JPAEntityParse
Here is the entity code I'm using:
#Entity
public class BORROWER {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Embedded
protected BORROWER_DETAIL borrower_DETAIL;
#Embedded
protected NAME name;
#ManyToOne
protected DEAL deal;
//Mark transient to force orika to skip
#Transient
public DEAL getDeal() {
return deal;
}
public void setDeal(DEAL deal) {
this.deal = deal;
}
/**
* Gets the value of the borrower_DETAIL property.
*
* #return
* possible object is
*
*
*/
public BORROWER_DETAIL getBORROWER_DETAIL() {
return borrower_DETAIL;
}
/**
* Sets the value of the borrower_DETAIL property.
*
* #param value
* allowed object is
*
*
*/
public void setBORROWER_DETAIL(BORROWER_DETAIL value) {
this.borrower_DETAIL = value;
}
public NAME getName() {
return name;
}
public void setName(NAME name) {
this.name = name;
}
public long getId() {
return id;
}
}
Seeing the comment regarding getter/setters being the source of the issue on this bug ticket (also I borrowed parts of the write up for the question):
https://issues.apache.org/jira/browse/OLINGO-948
I updated the getter and setter method signatures for borrower_DETAIL, and I'm no longer getting the error. Here is the updated entity code that is working for me:
#Entity
public class BORROWER {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Embedded
protected BORROWER_DETAIL borrower_DETAIL;
#Embedded
protected NAME name;
#ManyToOne
protected DEAL deal;
//Mark transient to force orika to skip
#Transient
public DEAL getDeal() {
return deal;
}
public void setDeal(DEAL deal) {
this.deal = deal;
}
public BORROWER_DETAIL getBorrower_DETAIL() {
return borrower_DETAIL;
}
public void setBorrower_DETAIL(BORROWER_DETAIL borrower_DETAIL) {
this.borrower_DETAIL = borrower_DETAIL;
}
public NAME getName() {
return name;
}
public void setName(NAME name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

JPA Hibernate Saving ManyToOne field is null

I have a servlet method that creates a JPA entity and assigns an existing JPA entity to a #ManyToOne field
When I persist it, it saves the entity but the foreign key is NULL. Why?
Here are my entities:
#Entity
public class SimpleEntity implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -5930519292861829894L;
#Id #GeneratedValue
Long id;
String name;
#ManyToOne()
#JoinColumn(name="simple_entity_group_id", insertable=false, updatable=false, nullable=true)
SimpleEntityGroup group;
/**
*
*/
public SimpleEntity() {
}
/**
* #return the id
*/
public Long getId() {
return this.id;
}
/**
* #param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return this.name;
}
/**
* #param name the name to set
*/
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "SimpleEntity [id=" + this.id + ", name=" + this.name + ", group=" + this.getGroup() + "]";
}
/**
* #return the group
*/
public SimpleEntityGroup getGroup() {
return this.group;
}
/**
* #param group the group to set
*/
public void setGroup(SimpleEntityGroup group) {
this.group = group;
}
}
#Entity
public class SimpleEntityGroup implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1680386377742600266L;
#Id #GeneratedValue
Long id;
String name;
#OneToMany(mappedBy="group")
java.util.List<SimpleEntity> simpleEntities;
/**
*
*/
public SimpleEntityGroup() {
simpleEntities = new ArrayList<SimpleEntity>();
}
/**
* #return the id
*/
public Long getId() {
return this.id;
}
/**
* #param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return this.name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the simpleEntities
*/
public java.util.List<SimpleEntity> getSimpleEntities() {
return this.simpleEntities;
}
/**
* #param simpleEntities the simpleEntities to set
*/
public void setSimpleEntities(java.util.List<SimpleEntity> simpleEntities) {
this.simpleEntities = simpleEntities;
}
public void addSimpleEntity(SimpleEntity e) {
if(this.getSimpleEntities() != null) {
this.getSimpleEntities().add(e);
return;
}
throw new RuntimeException("Entity list is null!!!");
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "SimpleEntityGroup [id=" + this.id + ", name=" + this.name + "]";
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SimpleEntityGroup other = (SimpleEntityGroup) obj;
if (this.id == null) {
if (other.id != null) {
return false;
}
} else if (!this.id.equals(other.id)) {
return false;
}
return true;
}
}
Here is how I persist it:
SimpleEntity e = new SimpleEntity();
e.setName("Mike");
SimpleEntityGroup g = dao.getGroupById(1l);
e.setGroup(g);
dao.persist(e);
System.out.println(e);
System.out.println(dao.findAll());
Here is the output from the Java code, the group is set on the entry but it is not saved. Why?!?!
SimpleEntity [id=4, name=Mike, group=SimpleEntityGroup [id=1,
name=Group 1]]
[SimpleEntity [id=4, name=Mike, group=null]]
Of course I just figured it out, needed to do:
#ManyToOne()
#JoinColumn(name="simple_entity_group_id")
SimpleEntityGroup group;
-- Got rid of the insert=false, update=false
You only posted your child class but I think will be better if you also include the parent class code. I had the same problem when I tried make saves in cascade using only auto generated ids. I could solve it using the next annotations.
In my parent class I have
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="IDCOBPRES", unique=true, nullable=false)
public Long getIdcobpres() {
return this.idcobpres;
}
//....
#OneToMany(fetch=FetchType.LAZY, mappedBy="cobpresGestion")
#Cascade({CascadeType.ALL})
public Set<CobpresOptionDet> getCobpresOptionDets() {
return this.cobpresOptionDets;
}
In my child class I have
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="IDOPTIONDET", unique=true, nullable=false)
public Long getIdoptiondet() {
return this.idoptiondet;
}
//...
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="IDCOBPRES", nullable=false, insertable=true, updatable=true)
public CobpresGestion getCobpresGestion() {
return this.cobpresGestion;
}

Spring Data JPA user posts

I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction?
I have a user entity:
#Entity
#Table(name = "usr", indexes = { #Index(columnList = "email", unique = true) })
// using usr because in may conflict with the name of the class
public class User {
public static final int EMAIL_MAX = 250;
public static final int NAME_MAX = 50;
/*
* public static enum Role {
*
* UNVERIFIED, BLOCKED, ADMINISTRATOR
*
* }
*/
// primary key long, needs to be annotated with #Id
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
// add columns
#Column(nullable = false, length = EMAIL_MAX)
private String email;
#Column(nullable = false, length = NAME_MAX)
private String name;
// no length, the password will be encrypted to some longer value than the
// user enters
#Column(nullable = false)
private String password;
/*
* //email verification code
*
* #Column(length = 16) private String verificationCode;
*
* public String getVerificationCode() { return verificationCode; }
*
* public void setVerificationCode(String verificationCode) {
* this.verificationCode = verificationCode; }
*
*
* #ElementCollection(fetch = FetchType.EAGER) private Set<Role> roles = new
* HashSet<Role>();
*
*
*
* public Set<Role> getRoles() { return roles; }
*
* public void setRoles(Set<Role> roles) { this.roles = roles; }
*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEditable() {
User loggedIn = MyTools.getSessionUser();
if (loggedIn == null) {
return false;
}
return loggedIn.getId() == id;
}
}
and repo:
public interface UserRepository extends JpaRepository<User, Long> {
// #Query("select u from User u where u.email = ?1")
User findByEmail(String email);
}
now, in order to have posts by that user, do I create a posts entity and repository with #manytoone in post pojo?
I'm trying to make a twitter eventually but first I gotta get users to post. If you know of a good tutorial explaining this then that'd be great.
Create a second entity (java class) e.g. UserPost:
#Entity
#Table(...)
public class UserPost {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long userId;
...
}
Then add #OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User:
#OneToMany(cascade={...})
#JoinColumn(name="userId")
private Set<UserPost> posts;

How does hibernate decide update/save associated objects

Anyone could help me explain about hibernate. How do it save/update child objects when we save/update parent object. Especially, Child Object with #EmbeddedId look like my mapping
#Embeddable
public class BomLevelKey implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
Item item;
long organizationId;
Item componentItem;
#Column(name = "organization_id")
public long getOrganizationId() {
return organizationId;
}
public void setOrganizationId(long organizationId) {
this.organizationId = organizationId;
}
#ManyToOne
#JoinColumn(name = "inventory_item_id")
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
#ManyToOne
#JoinColumn(name = "component_item_id")
public Item getComponentItem() {
return componentItem;
}
public void setComponentItem(Item componentItem) {
this.componentItem = componentItem;
}
#Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof BomLevelKey)) {
return false;
}
BomLevelKey key = (BomLevelKey) obj;
if (key.getItem().getInventoryItemID() == this.getItem()
.getInventoryItemID()
&& key.getComponentItem().getInventoryItemID() == this
.getComponentItem().getInventoryItemID()
&& key.getOrganizationId() == this.getOrganizationId()) {
return true;
}
return false;
}
}
#Entity
#Table(name = "es_bom_levels", schema = "xx_vms")
public class ItemConversionAttributes implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Double componentRoutingYield;
private Double forwardRoutingYield;
private Double conversionFactor;
private Double cumulativeLeadTime;
private Integer organizationID;
private Item componentItem;
private BomLevelKey id;
#EmbeddedId
public BomLevelKey getId() {
return id;
}
public void setId(BomLevelKey id) {
this.id = id;
}
/**
* #hibernate.property
* column="component_routing_yield"
*
**/
#Column(name="component_routing_yield")
public Double getComponentRoutingYield(){ return componentRoutingYield; }
public void setComponentRoutingYield(Double componentRoutingYield){ this.componentRoutingYield= componentRoutingYield; }
/**
* #hibernate.property
* column="forward_routing_yield"
*
**/
#Column(name="forward_routing_yield")
public Double getForwardRoutingYield(){ return forwardRoutingYield; }
public void setForwardRoutingYield(Double forwardRoutingYield){ this.forwardRoutingYield = forwardRoutingYield; }
/**
* #hibernate.property
* column="conversion_factor"
*
**/
#Column(name="conversion_factor")
public Double getConversionFactor(){ return conversionFactor; }
public void setConversionFactor(Double conversionFactor){ this.conversionFactor = conversionFactor; }
/**
* #hibernate.property
* column="cumulative_lead_time"
*
**/
#Column(name="cumulative_lead_time")
public Double getCumulativeLeadTime(){ return cumulativeLeadTime; }
public void setCumulativeLeadTime(Double cumulativeLeadTime){ this.cumulativeLeadTime = cumulativeLeadTime; }
/**
* #hibernate.property
* column="organization_id"
*
**/
#Column(name="organization_id", insertable = false, updatable = false)
public Integer getOrganizationID(){ return organizationID; }
public void setOrganizationID(Integer organizationID){ this.organizationID = organizationID; }
/**
* #hibernate.many-to-one
* column="component_item_id"
* insert="false"
* update="false"
*
**/
#ManyToOne(targetEntity=Item.class)
#JoinColumn(name="component_item_id", insertable=false, updatable=false)
#NotFound(action=NotFoundAction.IGNORE)
public Item getComponentItem(){ return componentItem; }
public void setComponentItem(Item componentItem){ this.componentItem = componentItem; }
}
In class Item, I've this mapping:
#OneToMany(mappedBy = "id.item")
#MapKey(name = "id.componentItem")
public Map<Item, ItemConversionAttributes> getConversionAttributes(){ return conversionAttributes; }
public void setConversionAttributes(Map<Item, ItemConversionAttributes> conversionAttributes) {
this.conversionAttributes = conversionAttributes;
}
save/update do nothing.
Its based on DAO Objects primary key's value.
If its set default value , hibernate will add otherwise update

Composite Foreign Key Issue while using Inheritance in JPA

I have a JPA Entity StatsEntity which has a composite primary key that is also as foreign key to another Entity Roster. This is setup as a #OneToOne relationship using #JoinColumns({#JoinColumn...}) annotations.
StatsEntity extends another entity CoreStatsEntity which is setup as #MappedSuperClass where as RosterEntity extends another entity CoreRoster using SINGLE_TABLE inheritance strategy.
#Entity
#Table(name = "Stats")
#IdClass(value = StatsEntity.Key.class)
public class StatsEntity extends CoreStatsEntity implements
Stats {
#Id
private Integer competitionId;
#Id
private Integer playerId;
#Id
private Integer teamId;
#OneToOne
#JoinColumns({
#JoinColumn(name = "competitionId", referencedColumnName = "competitionId", insertable = false, updatable=false),
#JoinColumn(name = "playerId", referencedColumnName = "personId", insertable = false, updatable=false),
#JoinColumn(name = "teamId", referencedColumnName = "teamId", insertable = false, updatable=false) })
private RosterEntity roster;
....
}
StatsEntity.Key
#Embeddable
public static class Key implements Serializable {
private static final long serialVersionUID = -7349082038890396790L;
#Column(name = "competitionId", insertable = false, updatable = false)
private Integer competitionId;
#Column(name = "playerId", insertable = false, updatable = false)
private Integer playerId;
#Column(name = "teamId", insertable = false, updatable = false)
private Integer teamId;
public Key() {
super();
}
public Key(int competitionId, int playerId, int teamId) {
this.competitionId = Integer.valueOf(competitionId);
this.playerId = Integer.valueOf(playerId);
this.teamId = Integer.valueOf(teamId);
}
public int getTeamId() {
return teamId.intValue();
}
public void setTeamId(int teamId) {
this.teamId = Integer.valueOf(teamId);
}
public int getPlayerId() {
return playerId.intValue();
}
public void setPlayerId(int playerId) {
this.playerId = Integer.valueOf(playerId);
}
public int getCompetitionId() {
return competitionId.intValue();
}
public void setCompetitionId(int CompetitionId) {
this.competitionId = Integer.valueOf(CompetitionId);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Key)) {
return false;
}
Key other = (Key) object;
return Utils.equals(other.getTeamId(), this.getTeamId())
&& Utils.equals(other.getPlayerId(), this.getPlayerId())
&& Utils.equals(other.getCompetitionId(),
this.getCompetitionId());
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
return Utils.hashCode(this.teamId, this.playerId,
this.competitionId);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return Utils.toString("CompetitionPlayerStatsEntity.Key",
this.teamId, this.playerId, this.competitionId);
}
}
CoreStatsEntity.java
#MappedSuperclass
public abstract class CoreStatsEntity
{}
RosterEntity
#Entity
#DiscriminatorValue("20")
public class RosterEntity extends
CoreRosterEntity {
//.... attributes, getters, setters
}
CoreRosterEntity.java
#Entity
#DiscriminatorValue("0")
#Table(name="Roster")
#IdClass(CoreRoster.Key.class)
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="discriminator", discriminatorType=DiscriminatorType.INTEGER)
public class CoreRosterEntity {
private static final long serialVersionUID = 1521639115446682871L;
#Id
private Integer competitionId;
#Id
private Integer teamId;
#Id
private Integer playerId;
//.. getters, setters and other attributes
}
CoreRoster.Key.class inside CoreRoster.java
#Embeddable
public static class Key implements Serializable {
private static final long serialVersionUID = 2L;
#Column(name="competitionId", nullable=false)
private Integer competitionId;
#Column(name="teamId", nullable=false)
private Integer teamId;
#Column(name="personId", nullable=false)
private Integer playerId;
public Key() {
super();
}
public Key(int competitionId, int teamId, int playerId) {
this.competitionId = Integer.valueOf(competitionId);
this.teamId = Integer.valueOf(teamId);
this.playerId = Integer.valueOf(playerId);
}
public int getPlayerId() {
return playerId.intValue();
}
public void setPlayerId(int playerId) {
this.playerId = Integer.valueOf(playerId);
}
public int getTeamId() {
return teamId.intValue();
}
public void setTeamId(int teamId) {
this.teamId = Integer.valueOf(teamId);
}
public int getCompetitionId() {
return this.competitionId.intValue();
}
public void setCompetitionId(int competitionId) {
this.competitionId = Integer.valueOf(competitionId);
}
/*
* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object object) {
if (object == this) { return true; }
if (!(object instanceof Key)) { return false; }
Key other = (Key) object;
return Utils.equals(other.getCompetitionId(), this.getCompetitionId()) &&
Utils.equals(other.getTeamId(), this.getTeamId()) &&
Utils.equals(other.getPlayerId(), this.getPlayerId());
}
/*
* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
return Utils.hashCode(this.competitionId, this.teamId,
this.playerId);
}
/*
* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return Utils.toString("CoreRoster.Key",
this.competitionId, this.teamId,
this.playerId);
}
}
When I persist StatsEntity, it gets persisted. But when I try to find it using the primary key it gives me an error:
StatsEntity playerStats = new StatsEntity();
//set all values
this.persist(playerStats);
entityManager.find(StatsEntity.class, playerStats.getId()); //getId returns the composite primary key
java.lang.IllegalArgumentException: Provided id of the wrong type for class com.sports.RosterEntity. Expected: class com.sports.CoreRoster$Key, got class com.espn.sports.StatsEntity$Key
My first question here is, is the #OneToOne mapping I have given correct or not?
If it is correct then why this error appears when I try to find the entity using primarykey.
You haven't posted full source code, especially of your primary key class, but you've mapped foreign key as read-only, which is required when single column is mapped more than once.
I see however that you id columns are exactly the same 3 columns that are foreign key to RosterEntity, rights? In that case this RosterEntity should be your ID, which would simplify your design.
What is the return type of your getId() method? The problem is propably with definition or usage of IdClass.

Categories

Resources