getting error during the creation of relationship between JPA entities - java

I'm trying to create entities but I got the following error.
Internal Exception: Exception [EclipseLink-7157] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class application.Team] must use a #JoinColumn instead of #Column to map its relationship attribute [mPlayers].
These are my entities, I need to store data into the database using the Java Persistence API (JPA). To do so I create entities as following. Maybe I have created the relationships between entities in the wrong way.
Person
#MappedSuperclass
public class Person {
#Id
#GeneratedValue( strategy= GenerationType.AUTO )
protected int p_id;
protected String firstName;
protected String middleName;
protected String lastName;
protected String phone;
protected String email;
public Person() {
}
}
Player
#Entity
#Table( name = "tbl_players")
#AttributeOverride(name="id", column=#Column(name="player_id"))
public class Player extends Person implements Serializable{
private int player_id;
#Column(name = "goals_in_year")
private int numberOfGoalsInCurrentYear;
private boolean goalie;
#Column(name = "defended_goals")
private int defendedGoals;
public Player(){
}
}
Manager
#Entity
#Table( name = "tbl_manager")
#AttributeOverride(name="id", column=#Column(name="manager_id"))
public class Manager extends Person implements Serializable{
private String dob;
private int starRating;
#OneToOne
private Team teamToManage;
public Manager(){
}
}
Team
#Entity
#Table( name = "tbl_team")
public class Team implements Serializable {
#Column(name = "team_name")
#Id
String teamName;
#OneToOne
Manager manager;
#Column(name = "team_players")
#OneToMany
private List<Player> mPlayers = new ArrayList<>();
#Column(name = "jersey_color")
String jerseyColor;
public Team(){
}
}
League
#Entity
public class League {
#Id
private int league_id;
#OneToMany
#Column(name = "League Teams")
private List<Team> mTeam = new ArrayList<>();
public void addTeam(Team team) {
mTeam.add(team);
}
public void removeTeam(Team team) {
mTeam.remove(team);
}
}

Use #JoinColumn for Mapping (#OneToMany, #ManyToMany, #ManyToOne) instead of #Column. #Column is used to specify the mapped column for a persistent property or field.

Player
#Entity
#Table( name = "tbl_players")
#AttributeOverride(name="id", column=#Column(name="player_id"))
public class Player extends Person implements Serializable{
private int player_id;
#Column(name = "goals_in_year")
private int numberOfGoalsInCurrentYear;
private boolean goalie;
#Column(name = "defended_goals")
private int defendedGoals;
#OneToOne // or #OneToMany as you desire
#JoinColumn(name="team_name") // here the name you have given to the column in tbl_players
private Team team;
public Player(){
}
}
Manager
#Entity
#Table( name = "tbl_manager")
#AttributeOverride(name="id", column=#Column(name="manager_id"))
public class Manager extends Person implements Serializable{
private String dob;
private int starRating;
#OneToOne(mappedBy="manager")
private Team teamToManage;
public Manager(){
}
}
Team
#Entity
#Table( name = "tbl_team")
public class Team implements Serializable {
#Id
#Column(name = "team_id")
private int id;
#Column(name = "team_name")
String teamName;
#OneToOne
#JoinColumn(name="manager_id")
Manager manager;
#Column(name = "team_players")
#OneToMany(mappedBy="team")
private List<Player> mPlayers = new ArrayList<>();
#Column(name = "jersey_color")
String jerseyColor;
#ManyToOne(mappedBy="")
private League league;
public Team(){
}
}
League
#Entity
#Table( name = "tbl_league")
public class League {
#Id
#Column(name="league_id")
private int league_id;
#OneToMany
#JoinTable(name="tbl_league_teams",joinColumns=#JoinColumn(name = "league_id"), inverseJoinColumns=#JoinColumn(name = "team_id"))
private List<Team> mTeam = new ArrayList<>();
public void addTeam(Team team) {
mTeam.add(team);
}
public void removeTeam(Team team) {
mTeam.remove(team);
}
}
Create new intermiditate mapping table named tbl_league_teams with columns league_id and team_id to facilitate the #JoinTable in League entity to map between teams in a league.

It seems to be due to #Column(name = "team_players") and #OneToManyPlease
Please read the link
https://stackoverflow.com/a/24206471/11207493

Why dont u treat each model class as an entity then u join the model using either ManyToOne or OneToMany

Related

I used crudrepository findAll() method on MAGICNOTIFY_CARD_INFO table but it shows other columns from another table MAGICNOTIFY_PRICE

I tried to select all columns from the table MAGICNOTIFY_CARD_INFO, so i wrote a code;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MagicnotifyApplication.class, args);
MagicnotifyCardInfoRepository magicnotifyCardInfoRepository =
context.getBean(MagicnotifyCardInfoRepository.class);
magicnotifyCardInfoRepository.findAll();
//SpringApplication.run(MagicnotifyApplication.class, args);
}
and this is the entity i wanted to select;
public class MagicnotifyCardInfoID implements Serializable {
#Column(name = "koname")
private String koname;
#Column(name = "name")
private String name;
#Column(name = "cardkingdom")
private String cardkingdom;
#Column(name = "cardkingdomfoil")
private String cardkingdomfoil;
#Column(name = "set")
private String set;
#Column(name = "setName")
private String setName;
#Column(name = "reldate")
private Date reldate;
#Column(name = "rarity")
private String rarity;
#Column(name = "uuid")
private String uuid;
#ManyToOne
private MagicnotifyUuidName magicnotifyUuidName;
#ManyToOne
private MagicnotifySetInfo magicnotifySetInfo;
}
public class MagicnotifyCardInfo implements Serializable {
#EmbeddedId
private MagicnotifyPriceID id;
}
public interface MagicnotifyCardInfoRepository extends JpaRepository<MagicnotifyCardInfo, Long> {
#Query(value = "SELECT * FROM MAGICNOTIFY_CARD_INFO", nativeQuery = true)
List<MagicnotifyCardInfo> findByAll();
List<MagicnotifyCardInfo> findAll();
}
but after querying, it tries to select other column item from table
MAGICNOTIFY_PRICE;
public class MagicnotifyPriceID implements Serializable {
#Column(name = "foil")
private BigDecimal foil;
#Column(name = "normal")
private BigDecimal normal;
#Column(name = "date")
private Date date;
#Column(name = "key")
private String key;
#ManyToOne
private MagicnotifyUuidName id;
}
public class MagicnotifyPrice implements Serializable {
#EmbeddedId
private MagicnotifyPriceID id;
}
I'm not sure why it happens from differently mapped two tables; how can i select from initial table MAGICNOTIFY_CARD_INFO and select from its columns?
First of all, you have not mentioned any primary key using #Id annotation inside either of your MagicnotifyCardInfoID class or MagicnotifyPriceID class
Secondly, you have given same #EmbeddedId fields "MagicnotifyPriceID id" in both the below classes
public class MagicnotifyCardInfo implements Serializable {
#EmbeddedId
private MagicnotifyPriceID id;
}
public class MagicnotifyPrice implements Serializable {
#EmbeddedId
private MagicnotifyPriceID id;
}
I don't see #Embeddable used anywhere in your program
Please refer https://www.baeldung.com/jpa-embedded-embeddable
public interface MagicnotifyCardInfoRepository extends JpaRepository<MagicnotifyCardInfo, Long> {
#Query(value = "SELECT * FROM MAGICNOTIFY_CARD_INFO", nativeQuery = true)
List<MagicnotifyCardInfo> findByAll();
List<MagicnotifyCardInfo> findAll();
}
In the above class you are passing "JpaRepository<MagicnotifyCardInfo, Long>"
Long as the data type of a primary key in your entity "MagicnotifyCardInfo"
which does not even exist.
Please fix these and try again.

JPA mapping sports game with two #OneToOne relations

I have the following hierarchy for a football match.
#Entity
public class Match {
#Id
#GeneratedValue
protected Integer id;
#Column(name = "home_team_id")
private int homeTeamId;
#Column(name = "away_team_id")
private int awayTeamId;
private TeamScore homeScore;
private TeamScore awayScore;
}
#Entity(name = "team_score")
public class TeamScore {
#EmbeddedId
protected TeamScoreId id;
private List<Goal> goals;
}
#Embeddable
public class TeamScoreId {
#Column(name = "match_id")
private Integer matchId;
#Column(name = "team_id")
private int teamId;
}
And I have a problem with mapping homeScore and awayScore in Match with TeamScore entity.
The first concern is whether two #OneToOne relations should be here. And how should they be configured?
The second one relates to matchId in TeamScoreId. How this mapping can be performed?

Remove redundant column for composite key in Hibernate

Hibernate creates empty "ID" column in case of code like in this post.
How tune it to not create "ID" column ("ID" is exact name of created column) or this can not be changed?
#Entity
#Table(name = "CATEGORY_RELATIONS")
public class CategoryRelations implements Serializable {
private CategoryRelationsPrimaryKey id;
#Id
#Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
private String categoryId;
#Id
#Column(name = "CATEGORY_RELATIONS_PARENT_ID")
private String parentId;
//getters and setters
#Entity
#IdClass(CategoryRelationsPrimaryKey.class)
public class CategoryRelationsPrimaryKey implements Serializable {
protected long categoryId;
protected long parentId;
//euqals, hashCode
}
}
1) #IdClass should stand at entity, not at composite id class;
2) If you already marked id properties by #Id, no separate id property is required:
#Entity
#Table(name = "CATEGORY_RELATIONS")
#IdClass(CategoryRelationsPrimaryKey.class)
public class CategoryRelations implements Serializable {
#Id
#Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
private String categoryId;
#Id
#Column(name = "CATEGORY_RELATIONS_PARENT_ID")
private String parentId;
//...
}
public class CategoryRelationsPrimaryKey implements Serializable {
protected String categoryId;
protected String parentId;
// ...
}
If you need some property named id, make it transient to avoid mapping to a DB table column.

HIbernate #OneToOne mapping

I have a PatientVisit.java that has a one to one mapping with the PatientVisitObject.java:
#Entity
#Table(name = "P_Visit")
public class PatientVisit extends Bean {
#Id
#Column(name = "PATIENT_VISIT_SEQ")
private Long patientVisitSeq;
#Column(name = "PATIENT_FIRST_NM")
private String firstName;
#Column(name = "PATIENT_LAST_NM")
private String lastName;
#Column(name = "PATIENT_MIDDLE_NM")
private String middleName;
#OneToOne
private PatientVisitObject pvo;
}
The PatientVisitObject.java has a composite key. I need to map key.patientVisitSeq to my patientVisitSeq in the PatientVisit.java.
#Entity
#Table(name = "Patient_V_O")
public class PatientVisitObject extends Bean {
#Id
private PatientVisitObjectKey key;
#Column(name = "FIELD")
private String field;
}
Here is the key:
#Embeddable
public class PatientVisitObjectKey implements Serializable {
#Column(name = "PATIENT_VISIT_SEQ")
private Long patientVisitSeq;
#Column(name = "PATIENT_VISIT_OBJECT_SEQ")
private Long patientVisitObjectSeq;
}
I have tried using the #JoinTable annotation and cannot get it right. Could someone please give me some direction. Thanks.
You need to use bidirectional mapping with PatientVisit being the inverse side of relationship:
public class PatientVisit extends Bean {
...
#OneToOne(mappedBy = "pv")
private PatientVisitObject pvo;
...
}
public class PatientVisitObject extends Bean {
#EmbeddedId
private PatientVisitObjectKey key;
#OneToOne
#MapsId("patientVisitSeq")
private PatientVisit pv;
...
}
See also:
#MapsId

Hibernate 1:n relation bringing null values

I have two classes
Alocacao and Responsavel
I have a 1:n
Responsavel.class
#Entity
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
#Table(name="Responsavel")
public class Responsavel {
#Id
#Column(name="idResp")
private int idResp;
#Column(name="nomeResp")
private String nomeResp;
#Column(name="emailResp")
private String email;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="idGrupResp")
private GrupoResponsavel grupo;
#Column(name="idPovUser")
private int povUser;
#ManyToMany(mappedBy="responsavel", fetch=FetchType.EAGER)
private List<TarefaBackLog> tarefa;
public Responsavel() {
super();
}
//getters and setters
Alocacao.class
#Entity
#Table(name = "responsavel_alocacao")
public class Alocacao {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "idRespAloc")
private int idAlocacao;
#ManyToOne
#JoinColumn(name="idResponsavel", referencedColumnName="idResp")
private Responsavel idResponsavel;
#JoinColumn(name="idPeriodo")
private PeriodoPov idPeriodo;
#Column(name="Alocacao")
private double alocacao;
//getters and setters
But when I try to get all the Alocacao objects with "findAll()", it brings me null values to idPeriodo and idResponsavel.. any ideas?
Thanks

Categories

Resources