How to achieve Hibernate composite key relation? - java

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
}

Related

Using a Spring Entity inside another Spring Entity

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

How to return only specific field in spring

In the following code when I used projection it returns me the whole object of Group , But I want to get only roleName of class Group
how can I do this?
Projection: UserWithProfile
#Projection(name="UserWithProfile",types=User.class)
public interface UserWithProfile extends UserGetters {
UserPhoto getProfilePhoto();
}
UserGetters
public interface UserGetters{
Long getId();
String getName();
String getLogonEmail();
boolean isEmailVerified();
Group getGroup();
}
User.class
#Entity
public class User implements Serializable, UserGetters {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, targetEntity = Property.class)
private Set<Property> favouriteProperty;
#OneToOne
private AcceptanceLetter acceptanceLetter;
#Column(unique=true)
private String logonEmail;
private String name;
#JsonProperty(access = Access.WRITE_ONLY)
#Column(updatable=false)
private String password;
private boolean emailVerified;
#ManyToOne
private Group group;
#OneToOne
private Business business;
private String address;
private String postcode;
private String phoneNo;
private String passportNo;
#Column(length=1000)
private String description;
#JsonIgnore
private float meanRating;
#OneToOne(mappedBy="user",targetEntity=UserPhoto.class)
private UserPhoto profilePhoto;
#ManyToOne
private Country country;
Getter and setters... }
First I tried #RestResource(exported = false) its not worked but then I tried
#JsonIgnore it finally works :'D

JPA, put complex data type inside an entity in the same table

I have a class Customer which is an entity:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="customerId_Sequence")
#SequenceGenerator(name="customerId_Sequence",sequenceName="CUSTOMER_SEQ",allocationSize=1)
private long customerId;
private String firstName;
private String lastName;
private BillingDetails billingDetails
I have a class BillingDetails that looks like this:
public class BillingDetails {
private String type;
private long ccNumber;
I use hibernate as my persistence provider. I want it to create just one table in sql, which have columns customerId, firstName, lastName, type, ccNumber. I want it all in one table, I don't want billing details to be an entity. Is this possible?
When I try like this I get an error: Could not determine type for: ****.BillingDetails
Model BillingDetails as #Embeddable.
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="customerId_Sequence")
#SequenceGenerator(name="customerId_Sequence",sequenceName="CUSTOMER_SEQ",allocationSize=1)
private long customerId;
private String firstName;
private String lastName;
#Embedded
private BillingDetails billingDetails;
...
}
#Embeddable
public class BillingDetails {
private String type;
private long ccNumber;
...
}

How make a composite primary key using auto generated value and one foreign key using hibernate and spring MVC

I am developing a web application that customer call to a employee and he put a customer's order to the system.
From my ER diagram, the OrderDetail class contain a composite primary key that orderId and productId. Also it contain orderedQuentity column.
What I want is when customer place a order it has to have what products he/she ordered and the quantity of each product he/she order and who place the order(the employee).....
But I feel that in my way of doing that, the orderDetail class can only contain list of product , not the quantity of each product.
How do I do what I want ??
Here is my entity classes that I try to implement.
Customer Class :
#Entity
public class Customer {
#Id
#GeneratedValue
private Integer id;
private String firstName;
private String lastName;
private String companyName;
private Integer teleponeNumber;
#OneToMany(mappedBy="customer")
private List<OrderDetail> orders;
}
Product Class :
#Entity
public class Product {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer availableQuantity;
private String unitType;
private Integer unitPrice;
private String description;
#ManyToMany(mappedBy="products")
private List<OrderDetail> details;
}
Order Class :
#Entity
public class OrderDetail {
#Id
#GeneratedValue
private Integer orderId;
private Integer orderedQuentity;
private String customerAddress;
private String shipingAddress;
private String orderStatus;
#ManyToOne
#JoinColumn(name="Employee_Id")
private Employee employee;
#ManyToOne
#JoinColumn(name="customer_id")
private Customer customer;
#ManyToMany
#JoinTable
private List<Product> products;
}
Employee Class :
#Entity
public class Employee {
#Id
#GeneratedValue
private Integer id;
private String firstName;
private String lastName;
private String designation;
private String email;
private String password;
#OneToMany(mappedBy="employee")
private List<OrderDetail> orders;
}
From Customer to OrderDetail you have a OneToMany relation, I would suggest you to create a JoinTable
So the customer entity will look like:
#Entity
public class Customer {
#Id
#GeneratedValue
private Integer id;
private String firstName;
private String lastName;
private String companyName;
private Integer teleponeNumber;
#OneToMany(mappedBy="customer")
#JoinTable(name = “customer_order_details”, joinColumns= { #JoinColumn(name = “customer_id”, referencedColumnName=”id”) }, inverseJoinColumns = { #JoinColumn(name = “order_id”, referencedColumnName = “id”) })
private List<OrderDetail> orders;
}
The same situation in Employee entity:
#Entity
public class Employee {
#Id
#GeneratedValue
private Integer id;
private String firstName;
private String lastName;
private String designation;
private String email;
private String password;
#OneToMany(mappedBy="employee")
#JoinTable(name = “employee_order_details”, joinColumns= { #JoinColumn(name = “employee_id”, referencedColumnName=”id”) }, inverseJoinColumns = { #JoinColumn(name = “order_id”, referencedColumnName = “id”) })
private List<OrderDetail> orders;
}
And Product entity:
#Entity
public class Product {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer availableQuantity;
private String unitType;
private Integer unitPrice;
private String description;
#ManyToMany(mappedBy="products")
#JoinTable(name = “product_order_details”, joinColumns= { #JoinColumn(name = “product_id”, referencedColumnName=”id”) }, inverseJoinColumns = { #JoinColumn(name = “order_id”, referencedColumnName = “id") })
private List<OrderDetail> details;

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
}

Categories

Resources