Many To Many Relation JPA - java

I want to create a ManyToMany relation between the entites Movie and Genre. Because a Movie can have lots of genres, and a Genre can have lots of movies. But I don't know how to do the association. I have to create the entity "genre_movie"? If I compile it, generetes to more tables : movie_genre and genre_movie. I only want one.
#Entity
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JsonView(Views.Private.class)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#JsonView(Views.Private.class)
private String name;
#JsonView(Views.Private.class)
private Long year;
#JsonView(Views.Private.class)
private String sinopsis;
#JsonView(Views.Private.class)
private Double puntuation;
#JsonView(Views.Private.class)
private Long duration;
#JsonView(Views.Private.class)
private String idioma;
#JsonView(Views.Private.class)
private String trailer;
//getters seters
#ManyToMany(targetEntity=Genre.class)
private Set teacherSet;
}
Genre Class
import com.fasterxml.jackson.annotation.JsonView;
import javax.persistence.*;
import java.io.Serializable;
import java.util.*;
#Entity
public class Genre implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JsonView(Views.Private.class)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#JsonView(Views.Private.class)
private String genreName;
public Genre(){}
public Genre(String genreName){
this.genreName = genreName;
}
#ManyToMany(targetEntity = Movie.class)
private Set movieSet;
public String getName() {
return genreName;
}
public void setName(String name) {
this.genreName = name;
}
}
And queries:
insert into Movie (name,year,sinopsis,puntuation,duration,idioma,trailer) values ('Titanic',1997,'Is about a movie ....',0,88,'english','https://www.youtube.com/watch?v=zCy5WQ9S4c0&t=112s');
insert into Movie (name,year,sinopsis,puntuation,duration,idioma,trailer) values ('Nightcrawler',2014,'Is about a movie dpsvr....',0,175,'english','https://www.youtube.com/watch?v=u1uP_8VJkDQ');
insert into Movie (name,year,sinopsis,,,idioma,trailer) values ('Iron Man 2',2010,'Is about a movie dpsvr....',0,145,'english','https://www.youtube.com/watch?v=BoohRoVA9WQ');
insert into Genre (genreName) values ('comedy');
insert into Genre (genreName) values ('drama');
insert into Genre (genreName) values ('thriller');
insert into Genre (genreName) values ('terror');

#Entity
public class Movie implements Serializable {
#ManyToMany
private Set<Genre> teacherSet;
}
#Entity
public class Genre implements Serializable {
#ManyToMany(mappedBy="teacherSet")
private Set<Movie> movieSet;
}
In this example, will be generate only one relationship between Movie and Genre where the owner of the relationship will be Movie. In SQL, will be generate a association table Movie_Genre.

Related

When the model in hibernate need Serializable?

I have two model:
#Entity
public class Invoice {
#Id
#Column(name="InvoiceID")
private String InvoiceID;
#Column(name="Date")
private Date Date;
#Column(name="TotalPrice")
private int TotalPrice;
...
}
#Entity
public class Product {
#Id
private String ProductID;
#Column(name="ProductName")
private String ProductName;
#Column(name="Quantity")
private int Quantity;
#Column(name="Price")
private int Price;
...
}
And I have a join model
#Entity
public class InvoiceDetail implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name="InvoiceID")
private Invoice Invoice;
#Id
#ManyToOne
#JoinColumn(name="ProductID")
private Product Product;
...
}
In InvoiceDetail, if i dont implement Serializable, i will get Caused by: org.hibernate.MappingException: Composite-id class must implement Serializable: com.javainsimpleway.model.InvoiceDetail
But in Invoice and Product model, i dont need to do that.
Any one can explain me about that!
The id of an entity must be Serializable. Your String ids in Invoice and Product are both Serializable. Since you are (IMHO mis-)using Invoice as id in InvoiceDetail it also needs to be Serializable

Hibernate: ERROR Unknown column 'foo' in 'field list' - two #ManyToOne relationships from one entity to the same parent entity

I'm persisting a MySQL database with Hibernate 5.2.10
The child table Game has a couple of peculiarities:
First of all it has a composite primary key made of 4 columns, namely leagueId, which is also a foreign key of League, seasonId, which is also a foreign key of Season, roundNo, gameNo
Second, two of the table's foreign keys are pointing to the same table, i.e to Club.id: homeTeamId and awayTeamId.
I'm trying to query against the Club entity, but I keep on getting the same error message.
The query:
List<Game> gameList = session.createQuery("FROM Game g WHERE g.id.leagueId = 1L AND g.id.seasonId = 1L AND g.id.roundNo = 35 AND g.id.gameNo = 7")
.getResultList();
which translates into this:
Hibernate: select game0_.gameNo as gameNo1_1_, game0_.leagueId as leagueId2_1_, game0_.roundNo as roundNo3_1_, game0_.seasonId as seasonId4_1_, game0_.clubAway as clubAway5_1_, game0_.clubHome as clubHome6_1_, game0_.date as date7_1_, game0_.gameDescr as gameDesc8_1_, game0_.league as league9_1_, game0_.played as played10_1_, game0_.postponed as postpon11_1_, game0_.season as season12_1_ from game game0_ where game0_.leagueId=1 and game0_.seasonId=1 and game0_.roundNo=35 and game0_.gameNo=7
The error:
ERROR: Unknown column 'game0_.clubAway' in 'field list'
I think the error might be due to those two foreign keys pointing to the same Club table, but I'm pretty lost and don't know how to solve this problem. I think my entity classes are mapped properly.
The Game class
#Entity
#Table(name = "game")
public class Game implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private GameId id;
#Temporal(TemporalType.DATE)
private Date date;
private Boolean postponed;
private Boolean played;
private String gameDescr;
private League league;
private Season season;
private Club clubHome;
private Club clubAway;
public Game() {
}
//unannotated getters and setters omitted for brevity
#ManyToOne
#JoinColumn(name="leagueId", referencedColumnName="id", table="League")
public League getLeague() {
return league;
}
#ManyToOne
#JoinColumn(name="seasonId", referencedColumnName="id", table="Season")
public Season getSeason() {
return season;
}
#ManyToOne
#JoinColumn(name="homeTeamId", referencedColumnName="id", table="Club")
public Club getClubHome() {
return clubHome;
}
#ManyToOne
#JoinColumn(name="awayTeamId", referencedColumnName="id", table="Club")
public Club getClubAway() {
return clubAway;
}
}
The GameId class:
#Embeddable
public class GameId implements Serializable{
private static final long serialVersionUID = 1L;
private Long leagueId;
private Long seasonId;
private Integer roundNo;
private Integer gameNo;
public GameId() {
}
//getters and setters omitted for brevity
#Override
public int hashCode() {
// code omitted for brevity
}
#Override
public boolean equals(Object obj) {
//code omitted for brevity
}
}
The Club class:
#Entity
#Table(name = "Club")
public class Club implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String clubName;
private League league;
public Club() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
//unannotated getters and setters omitted for brevity
#ManyToOne
#JoinColumn(name = "currentLeagueId")
public League getLeague() {
return league;
}
}
The League class:
#Entity
public class League implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String leagueName;
private String descr;
public League() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
//unannotated getters and setters omitted for brevity
}
The Season class:
#Entity
#Table(name="season")
public class Season implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Integer yearBegin;
private Integer yearEnd;
private String descr;
public Season(){
}
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
//unannotated getters and setters omitted for brevity
}
The tables shown here are a subset of the entire database, which consists of 7 tables, but I've tested queries against all the other 6 entities and they worked smoothly. The problem must be in the Game entity, but I've no idea what's wrong with it. Can anybody shed some light on this issue? Thank you very much in advance to all those who'll help!
I found the solution. It seems crazy but all I needed to do was moving the #EmbeddedId annotation from the field to the getter in the Game class.
Now the Game class is:
#Entity
#Table(name = "game")
public class Game implements Serializable {
private static final long serialVersionUID = 1L;
private GameId id;
#Temporal(TemporalType.DATE)
private Date date;
private Boolean postponed;
private Boolean played;
private String gameDescr;
private League league;
private Season season;
private Club clubHome;
private Club clubAway;
public Game() {
}
#EmbeddedId
public GameId getId() {
return id;
}
//everything else stays the same

Define unique key in hibernate

I have three models in my project.
public class Bank{
private int id;
private String title;
....
}
public class Branch{
private Bank bank;
private int id;
private String title;
....
}
public class Account{
private Branch branch;
private int id;
private String accountNumber;
private String title;
....
}
how to define the accountNumber and id Of bank combined as a unique key?
For composite unique key, you can use uniqueConstraints property of #Table annotation:
#Table(
name = "account",
uniqueConstraints = {#UniqueConstraint(columnNames = {"accountNumber", "bank"})}
)
public class Account{
private Branch branch;
private int id;
private String accountNumber;
private String title;
#ManyToOne
private Bank bank;
}

How to retrieve many columns using jpql?

I have a problem retrieving some info from this class.
#Entity
public class Absence {
#Id #GeneratedValue(strategy= GenerationType.IDENTITY)
private int absenceId;
private int crn;
private int studentId;
#Temporal(TemporalType.DATE)
private Date absenceDate;
}
I want to retrieve the following information : studentId, student name ,number of absences. The problem the query doesn't work.
The query I am using is
public List<StudentAbsenceSummary> getSetionAbsences(int crn) {
Query q=em.createQuery("select b.studentId,count(b.studentId) from Absence b where b.crn =:crn group by (b.studentId)")
.setParameter("crn", crn);
List<StudentAbsenceSummary> students =q.getResultList();
return students;
}
The class of the retrieved list
public class StudentAbsenceSummary {
private int studentId;
private String name;
private int absenceCount;

Object db relational database

Using Objectdb to develop this relational database. Can someone please help fix this code up. I am doing a relational database to display student grade results. New to this so i have gone wrong somewhere..
package Student;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.*;
#Entity
public class students implements Serializable {
private static final long serialVersionUID = 1L;
#studentid #GeneratedValue
private long id;
}
#embeddable
public class Student {
int studentid;
String firstname;
String surname;
char gender;
Date dob;
String address1;
String address2;
String address3;
char postcode;
int phonenumber;
int courseid;
}
#Entity
public class courses implements Serializable {
#EmbeddedId Course id;
:
}
#Embeddable
public class course {
int courseid;
string coursename;
date coursestartdate;
date courseenddate;
}
#entity
public class moduledetails implements Serializable {
private static final long serialVersionUID = 1L;
#moduleId #GeneratedValue
private long id;
}
#Embeddable
public class module {
int moduleid;
String modulename;
int courseid;
int lectureid;
}
#entity
public class lecturedetails implements Serializable {
private static final long serialVersionUID = 1L;
#lectureId #GeneratedValue
private long id;
}
#Embeddable
public class lecture {
int lectureid;
String lecturename;
String lecturedepartment;
}
#entity
public class resultdetails implements Serializable {
private static final long serialVersionUID = 1L;
#studentId #GeneratedValue
private long id;
#Embeddable
public class result<Varchar> {
int studentid;
int courseid;
int moduleid;
Varchar modulename;
char grade;
}
}
Thanks!
The annotations #studentid, #moduleId and #lectureId are invalid. Use #Id.

Resources