Using a Spring Entity inside another Spring Entity - java

Getting the following error when I try to add a "Game" object to my ArrayList specified in my User class. This action was done in my controller class:
"org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.billsheng.huddlespringmvc.models.Game; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.billsheng.huddlespringmvc.models.Game"
User Entity
#Data
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String email;
private String firstName;
private String lastName;
private String password;
private String chosenTeam;
private int gamesPlayed;
private int gamesWon;
#ElementCollection
private List<Game> games = new ArrayList<>();
public User(String firstName, String lastName, String email, String password, String chosenTeam, int gamesPlayed, int gamesWon, ArrayList<Game> games) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.chosenTeam = chosenTeam;
this.gamesPlayed = gamesPlayed;
this.gamesWon = gamesWon;
this.games = games;
}
public User(String firstName, String lastName, String email, String password, String chosenTeam) {
this(firstName, lastName, email, password, chosenTeam, 0, 0, null);
}
public User(int gamesPlayed, int gamesWon, ArrayList<Game> games) {
this.gamesPlayed = gamesPlayed;
this.gamesWon = gamesWon;
this.games = games;
}
public User() {
}
//getters and setters
}
Game Entity
#Data
#Entity
public class Game {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String homeTeam;
private String awayTeam;
private Date date;
private String location;
private String bettingOdds;
private boolean inProgress;
private boolean isReviewed;
//getters and setters
}
I did some research and I believe this issue stems from me using my Game object inside my User object but I'm not sure what the problem is specifically.
All help is appreciated.

#ElementCollection is not supposed to be used with collections of entities; it's used with collections of #Embeddable. If Thing is an entity, you don't use #ElementCollection, you use #OneToMany.
#ElementCollection:
Defines a collection of instances of a basic type or embeddable class
You can use #OneToMany mapping for establishing the relationship between User and Game entity.
User.java
#OneToMany(cascade=CascadeType.ALL,fetch= FetchType.LAZY,mappedBy = "user")
private List<Game> games = new ArrayList<>();
//getters and setters
Game.java
#ManyToOne
private User user;
//getters and setters

Related

How can i establish a one to one relationship between this two classes using spring boot jpa?, also, how do i save the entities?

This is my Alias record class, it has a one to one relationship to the personal details class:
#Entity
public class AliasRecord
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String policeId;
private String enrollmentId;
#NotNull
private boolean isVerified;
#NotEmpty(message = "status not set")
private String status;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "personalDetails", referencedColumnName = "id")
private PersonalDetails personalDetails;
public AliasRecord(String policeId, String enrollmentId, #NotNull boolean isVerified, #NotEmpty(message = "status not set") String status) {
this.policeId = policeId;
this.enrollmentId = enrollmentId;
this.isVerified = isVerified;
this.status = status;
}
public AliasRecord(String policeId, String enrollmentId, #NotNull boolean isVerified,
#NotEmpty(message = "status not set") String status, PersonalDetails personalDetails) {
this.policeId = policeId;
this.enrollmentId = enrollmentId;
this.isVerified = isVerified;
this.status = status;
this.personalDetails = personalDetails;
}
public AliasRecord() {
}
}
Here is my personal details class:
#Entity
public class PersonalDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
private String title;
private String firstName;
private String middleName;
private String previousMiddleName;
private String otherNames;
private String surName;
private String previousSurName;
private String maidenName;
private String email;
private String phone;
private String gender;
private String dob;
private String stateOfBirth;
private String countryOfBirth;
private String dobVerification;
private String enrolmentType;
private String photo;
#OneToOne(mappedBy = "personalDetails")
private AliasRecord record;
public PersonalDetails() {
}
public PersonalDetails(String title, String firstName, String middleName, String previousMiddleName, String otherNames, String surName, String previousSurName, String maidenName, String email, String phone, String gender, String dob, String stateOfBirth, String countryOfBirth, String dobVerification, String enrolmentType, String nin, String photo, AliasRecord record) {
this.title = title;
this.firstName = firstName;
this.middleName = middleName;
this.previousMiddleName = previousMiddleName;
this.otherNames = otherNames;
this.surName = surName;
this.previousSurName = previousSurName;
this.maidenName = maidenName;
this.email = email;
this.phone = phone;
this.gender = gender;
this.dob = dob;
this.stateOfBirth = stateOfBirth;
this.countryOfBirth = countryOfBirth;
this.dobVerification = dobVerification;
this.enrolmentType = enrolmentType;
this.nin = nin;
this.photo = photo;
this.record = record;
}
}
This is how I save the entities using Crud Repository:
AliasRecord record = new AliasRecord("12","1222",true,"status");
AliasRecord aliasRecord = aliasRepository.save(record);
PersonalDetails details = new PersonalDetails("d","","","","","",
"","","","","","","",
"","34","4444","","cccc",
aliasRecord);
personalDetailsRepository.save(details);
I just put random values in the constructor just to see that the code works, anyway, when I try to save the entities, the column "personalDetails" appears in the AliasRecord table as a column for the foreign key, but its always null.How do I go about creating a one to one relationship between this two entities and how do I go about saving the entities to a MySQL db?.
Dont use bidirectional mapping in OneToOne relationship. If "PersonalDetails" depends on "AliasRecord" add OneToOne mapping in to "PersonalDetails" entity. Identify the most significant entity and add OneToOne mapping into that entity. If you add OneToOne mapping in both sides then you cant save because both expect FK values

Using CrudRepository interface to auto-implement methods that return different type of objects

I am trying to convert a Spring MVC application into a combo of Spring REST + Angular2 app.This is my 'Ticket.java' entity class (skipped getters and setters)
#Entity
#Table(name="ticket")
public class Ticket {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#ManyToOne
#JoinColumn(name="bookings_id")
private Booking booking;
#ManyToOne
#JoinColumn(name="customer_id")
private Customer customer;
#Column(name="seat_no")
private int seatNumber;
public Ticket(){
}
How do I write a method in TicketDAO that returns all the customers given the booking.id? Here is the TicketDAO.java interface
public interface TicketDAO extends CrudRepository<Ticket, Integer>{
// I want to auto-implement such type of method using CrudRepository
// public List<Customer> getCustomersBooking(int bId); }
I have previously implemented such method as :
#Override
public List<Customer> getCustomersBooking(int bId) {
Session currentSession = sessionFactory.getCurrentSession();
logger.info("DAOgetCustomersBooking: D1");
List<Customer> customer = new ArrayList<Customer>();
Query<Ticket> theQuery =
currentSession.createQuery("from Ticket where bookings_id = "+bId, Ticket.class);
List<Ticket> tickets = theQuery.getResultList();
for (Ticket temp: tickets){
customer.add(temp.getCustomer());
}
return customer;
}
But now I want to auto-implement such type of method using CrudRepository in the TicketDAO interface. How will I write a method declaration that will enable me to do so?
For Reference, Booking.java
#Entity
#Table(name="bookings")
public class Booking {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#ManyToOne
#JoinColumn(name="van_id")
private Van van;
#ManyToOne
#JoinColumn(name="driver_id")
private Driver driver;
#ManyToOne
#JoinColumn(name="route_id")
private Route route;
#Column(name="registered_seats")
private int registeredSeats;
#Column(name="departure_time")
private String departureTime;
#Column(name="arival_time")
private String arrivalTime;
#Column(name="departure_date")
private String departureDate;
#Column(name="expected_price")
private int expectedPrice;
//Ticket.java reference
#OneToMany(mappedBy="booking",fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private Set<Ticket> tickets;
//Webdata.java reference
#OneToOne(mappedBy="bookingWebdata",fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private Webdata webdata;
Customers.java
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="regnumber")
private int regNumber;
#Column(name="phonenumber")
private int phoneNumber;
#Column(name="flagged")
private int flagged;
//Ticket.java reference
#OneToMany(mappedBy="customer",cascade=CascadeType.ALL)
private Set<Ticket> tickets;
for a project I used JpaRepository but I think that's the same kind of request.
You have to use #Query() with HQL based on your java entities.
I gave object directly in the request and not the id so I don't know if you can do with id as I do with object.
Like this :
public interface TicketDAO extends CrudRepository<Ticket, Integer>{
#Query("SELECT t.customer FROM Ticket t WHERE t.booking = ?1")
public List<Customer> getCustomersBooking(Booking booking);
}
If you want to try with id, it would be around that :
public interface TicketDAO extends CrudRepository<Ticket, Integer>{
#Query("SELECT t.customer FROM Ticket t WHERE t.booking.id = ?1")
public List<Customer> getCustomersBooking(int bId);
}

How to achieve Hibernate composite key relation?

I have clases which look something like this. I want to associate user with locality. Where there is a OneToMany relation between City-Locality. How to achieve this
public class User {
private Long userId;
private String email;
private String password;
private String firstName;
private String lastName;
private String phone;
}
#Entity
public class City {
#Id
private Long id;
private String cityName;
private String pinCode;
}
#Entity
public class Locality {
private Long Id;
private String localityName;
}
Your model lacks clarity a bit - there is no information about either city or locality in User entity. However, if you would add locality id field to user entity, solution will look like below:
#Entity
public class User {
#Id
private Long userId;
private String email;
private String password;
private String firstName;
private String lastName;
private String phone;
#OneToOne
#JoinColumn(name="LOCALITY_ID")
private Locality locality;
//setters/getters omitted
}
#Entity
public class City {
#Id
private Long id;
private String cityName;
private String pinCode;
#OneToMany
#JoinColumn(name="LOCALITY_ID") // join column is in table for LOCALITY
private Set<Locality> localities;
//setters/getters omitted
}

How to retrieve a list of objects from a different table in same model?

I have two models, both of them are using hibernate and uses mySQL, they have a ManyToOne relationship, I am using AngularJS to display the view. I was wondering if there is a way to retrieve a list of objects from TraineeStatus model and store it in Trainee model?
TraineeStatus.java
#Entity
public class Trainees {
#Id
#GeneratedValue
private int traineesID;
#ManyToOne
private Technologies technologies;
#ManyToOne
private TraineeStatus traineestatus;
private int customersID;
private String name;
private String surname;
private String phoneDetails;
private String email;
public Trainees(){
}
public Trainees(String name, String surname, String phoneDetails, String email, int id, Technologies technologies, TraineeStatus traineestatus, int customersID) {
super();
this.name = name;
this.surname = surname;
this.email = email;
this.phoneDetails = phoneDetails;
this.technologies = technologies;
this.traineestatus = traineestatus;
this.customersID = customersID;
}
//getters and setters
TraineeStatus.java
#Entity
#Table(name="traineeStatus")
public class TraineeStatus {
#Id
#GeneratedValue
private int traineeStatusId;
private String value;
public TraineeStatus(){
}
My goal is to retrieve an array of objects from TraineeStatus with id and value inside the object and the use it in my Trainees model. Is it possible to do it? Thanks in regards.
Try it
#Entity
#Table(name="traineeStatus")
public class TraineeStatus {
#OneToMany(mappedBy = "traineestatus")
private List<Trainees> orderItems;
...
// GETTERS and SETTERS
}

Hibernate composite keys with abstract class

Is it possible to have a Employee table with composit primary key (personID,departmentName) keeping
the Person's class #id annotation , also keeping as it is a abstract class.
public abstract class Person {
#Id
#GeneratedValue
#Column(name = "PERSON_ID")
private Long personId;
#Column(name = "FIRSTNAME")
private String firstname;
// Getter and Setter methods,
}
#Entity
#Table(name="EMPLOYEE")
#PrimaryKeyJoinColumn(name="PERSON_ID")
public class Employee extends Person {
#Column(name="joining_date")
private Date joiningDate;
#Column(name="department_name")
private String departmentName;
public Employee() {
}
public Employee(String firstname, String lastname, String departmentName, Date joiningDate) {
super(firstname, lastname);
this.departmentName = departmentName;
this.joiningDate = joiningDate;
}
// Getter and Setter methods,
}

Categories

Resources