I have three Entities in my Spring-Boot Application:
Recipe N->1 RecipeIngredient 1->N Ingredient
It corresponds to a many to many relationship. However, the RecipeIngredient has an extra field "quantity".
I am trying to link together my table so that I can get a Recipe with its ingredients and their quantities.
So far I have this code:
Recipe
#Data
#Entity
#Table(name="recipe")
public class Recipe implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="name")
private String name;
#Column(name="duration")
private int duration;
#Column(name="created_on")
private LocalDate created_on = LocalDate.now();
#Column(name = "preparation")
private String preparation;
#Column(name = "difficulty")
private int difficulty;
#Column(name = "serving")
private int serving;
#Column(name = "pricing")
private int pricing;
#JsonManagedReference("recipe")
#OneToMany(mappedBy = "recipe",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<RecipeIngredient> ingredients = new ArrayList<>();
public Recipe() {
}
public Recipe(String name, int duration, LocalDate created_on, String preparation, int difficulty, int serving, int pricing) {
this.name = name;
this.duration = duration;
this.created_on = created_on;
this.preparation = preparation;
this.difficulty = difficulty;
this.serving = serving;
this.pricing = pricing;
}
}
Ingredient
#Data
#Entity
#Table(name = "ingredient")
public class Ingredient implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#JsonManagedReference("ingredient")
#OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL)
private List<RecipeIngredient> recipeIngredients = new ArrayList<>();
public Ingredient() {
}
public Ingredient(int id, String name, List<RecipeIngredient> recipeIngredients) {
this.id = id;
this.name = name;
this.recipeIngredients = recipeIngredients;
}
}
RecipeIngredient
#Entity
#Table(name = "recipe_ingredient")
#Data
public class RecipeIngredient implements Serializable {
#EmbeddedId
public RecipeIngredientId recipeIngredientId = new RecipeIngredientId();
#JsonBackReference("recipe")
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#MapsId("recipe_id")
private Recipe recipe;
#JsonBackReference("ingredient")
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#MapsId("ingredient_id")
private Ingredient ingredient;
#Column(name="quantity")
private String quantity;
public RecipeIngredient() {
System.out.println("[RecipeIngredient] no args constructor called");
}
public RecipeIngredient(Recipe recipe, Ingredient ingredient, String quantity) {
this.recipe = recipe;
this.ingredient = ingredient;
this.quantity = quantity;
}
}
And finally RecipeIngredientId
#Embeddable
public class RecipeIngredientId implements Serializable {
private static final long serialVersionUID = 1L;
private int recipe_id;
private int ingredient_id;
public RecipeIngredientId() {
}
public RecipeIngredientId(int recipe_id, int ingredient_id) {
this.recipe_id = recipe_id;
this.ingredient_id = ingredient_id;
}
public int getRecipe_id() {
return recipe_id;
}
public void setRecipe_id(int recipe_id) {
this.recipe_id = recipe_id;
}
public int getIngredient_id() {
return ingredient_id;
}
public void setIngredient_id(int ingredient_id) {
this.ingredient_id = ingredient_id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RecipeIngredientId that = (RecipeIngredientId) o;
return recipe_id == that.recipe_id &&
ingredient_id == that.ingredient_id;
}
#Override
public int hashCode() {
return Objects.hash(recipe_id, ingredient_id);
}
}
In my browser, can request all recipe and I obtain the following:
Ideally, I would like to obtain ingredients like:
...
"ingredients": [
{
"name": "salad",
"quantity: 2
}
]
Finally, is it possible with Spring / Hibernate to create a new Recipe, and add it new ingredients in a single request ? Or should I create the ingredients first and then pass them to the recipe ?
Related
I have 3 tables. Hospitals and doctors. The 3rd table is a junction table of both that contains id,ids of 2 other tables as foreign keys and few other columns. When trying to put record to a junction table I got an error that one of foreign keys have to be set with insertable=false. However when I set it like this then I get that the value can't be null (since my database requires that field).I'm stuck and can't go any further with those 2 errors.
If I manage to avoid those 2 errors then I get an erorr that there is an unknown column in the field list.
Doctors entity:
#Entity
#Table(name = "doctors")
public class Doctors implements Serializable {
private Integer id;
private String name;
private String surname;
private String title;
private String licenseNumber;
private String phone;
private String email;
private String nationality;
private String speciality;
private LocalDate dateOfBirth;
private Boolean isATeacher;
private List<HospitalDoctors> hospitalDoctors = new LinkedList<>();
//consturctors
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "Idd", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//setters and getters for rest of the fields with #column annotations on getters
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.doctor", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
public List<HospitalDoctors> getHospitalDoctors() {
return hospitalDoctors;
}
public void setHospitalDoctors(List<HospitalDoctors> hospitalDoctors) {
this.hospitalDoctors = hospitalDoctors;
}
Hospitals entity:
#Entity
#Table(name = "hospitals")
public class Hospitals implements Serializable {
private Integer id;
private String name;
private String country;
private String town;
private String street;
private String postalCode;
private String phoneNumber;
private String faxNumber;
private Integer numberOfAmbulances;
private Boolean helicopterAccess;
private Boolean teachingHospital;
private List<HospitalDoctors> hospitalDoctors = new LinkedList<>();
//constructors
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "Idh", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//getters setters with #column annotations over getters
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.hospital", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
public List<HospitalDoctors> getHospitalDoctors() {
return this.hospitalDoctors;
}
public void setHospitalDoctors(List<HospitalDoctors> hospitalDoctors) {
this.hospitalDoctors = hospitalDoctors;
}
Junction table entity:
#Entity
#Table(name = "hospitaldoctors")
#AssociationOverrides({
#AssociationOverride(name = "pk.hospital",
joinColumns = #JoinColumn(name = "Idh")),
#AssociationOverride(name = "pk.doctor",
joinColumns = #JoinColumn(name = "Idd"))
})
public class HospitalDoctors implements Serializable {
private Integer id;
private Integer idH;
private Integer idD;
private HospitalDoctorsId pk = new HospitalDoctorsId();
private LocalDate contractStartDate;
private LocalDate contractEndDate;
private String position;
private Boolean supervisor;
private Boolean partTime;
//constructors
#Column(name ="Idhos")
public Integer getIdH() {
return this.idH;
}
public void setIdH(Integer idH) {
this.idH = idH;
}
#Column(name ="Iddoc")
public Integer getIdD() {
return this.idD;
}
public void setIdD(Integer idD) {
this.idD = idD;
}
#EmbeddedId
public HospitalDoctorsId getPk() {
return pk;
}
public void setPk(HospitalDoctorsId pk) {
this.pk = pk;
}
#Transient
public Hospitals getHospital(){
return getPk().getHospital();
}
public void setHospital(Hospitals hospital){
getPk().setHospital(hospital);
}
#Transient
public Doctors getDoctor(){
return getPk().getDoctor();
}
public void setDoctor(Doctors doctor){
getPk().setDoctor(doctor);
}
//rest of the setters getters with #Column
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HospitalDoctors that = (HospitalDoctors) o;
if(getPk() != null?!getPk().equals(that.getPk()) : that.getPk() != null) return false;
return true;
}
#Override
public int hashCode() {
return (getPk() != null? getPk().hashCode() : 0);
}
Junction table Id:
#Embeddable
public class HospitalDoctorsId implements Serializable {
private Hospitals hospital;
private Doctors doctor;
#ManyToOne
public Hospitals getHospital() {
return hospital;
}
public void setHospital(Hospitals hospital) {
this.hospital = hospital;
}
#ManyToOne
public Doctors getDoctor() {
return doctor;
}
public void setDoctor(Doctors doctor) {
this.doctor = doctor;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HospitalDoctorsId that = (HospitalDoctorsId) o;
if(hospital != null?!hospital.equals(that.hospital) : that.hospital != null) return false;
if(doctor != null?!doctor.equals(that.doctor) : that.doctor != null) return false;
return true;
}
#Override
public int hashCode() {
int result;
result = (hospital != null? hospital.hashCode() : 0);
result = 31* result + (doctor != null? doctor.hashCode() : 0);
return result;
}
}
I expected to be able to add records to junction table in data base in form fields I have foreign keys for hospital and doctors id to put in as well as other fields. Unfortunately I get either error that say to put foreign keys columns idD and idH as insertable, updatable false which leads to null value being passed which gives another error. When I solve those errors I get the error:
java.sql.SQLSyntaxErrorException: Unknown column 'hospitaldo0_.Idd' in 'field list'when trying to display records nad unknown column Idd when trying to add record (displaying works when Im getting insertable error or null value error. adding never works)
If I remember correctly, you need to have a single #ManyToMany relation rather than two #OneToMany relations.
I'm trying to implement a unidirectional many to many relationship between entities with spring+JPA.
After a few tries changing hibernate versions I don't know whats the cause
Caused by: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Integer com.uca.refactor2.model.Achievement.id] by reflection for persistent property [com.uca.refactor2.model.Achievement#id] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer com.uca.refactor2.model.Achievement.id] by reflection for persistent property [com.uca.refactor2.model.Achievement#id] : 1
User.java
#Entity
#Table(name="USER")
public class User implements Serializable {
private static final long serialVersionUID = 4402583037980335445L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
#Column(unique = true)
private String username;
private String password;
#Enumerated(EnumType.STRING)
private UserType userType;
#OneToMany(cascade=CascadeType.ALL, mappedBy="joinedUserAchievementId.user")
private List<JoinedUserAchievement> joinedUserAchievementList = new ArrayList<JoinedUserAchievement>();
public User() {}
public User(Integer id) {
this.id = id;
}
public User(String username, String firstName, String lastName,
String password, UserType userType) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.userType = userType;
}
public List<JoinedUserAchievement> getAllAchievement() {
return joinedUserAchievementList;
}
public void addAchievement(Achievement achievement) {
// Notice a JoinedUserAchievement object
Date dateOfAcquisition = new Date();
JoinedUserAchievement joinedUserAchievement = new JoinedUserAchievement(new JoinedUserAchievement.JoinedUserAchievementId(this, achievement),dateOfAcquisition );
joinedUserAchievement.setAchievementId(achievement.getId());
joinedUserAchievementList.add(joinedUserAchievement);
}
//set and gets
JoinedUserAchievement.java
#Entity
#Table(name="USER_ACHIEVEMENT")
public class JoinedUserAchievement {
public JoinedUserAchievement() {}
public JoinedUserAchievement(JoinedUserAchievementId joinedUserAchievementId, Date dateOfAcquisition) {
this.joinedUserAchievementId = joinedUserAchievementId;
this.dateOfAcquisition = dateOfAcquisition;
}
#ManyToOne(targetEntity = Achievement.class)
#JoinColumn(name="id", insertable=false, updatable=false)
private Integer achievementId;
private Date dateOfAcquisition;
public String getDate() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = dateOfAcquisition;
return dateFormat.format(date);
}
public Integer getAchievementId() {
return achievementId;
}
public void setAchievementId(Integer achievementId) {
this.achievementId = achievementId;
}
#EmbeddedId
private JoinedUserAchievementId joinedUserAchievementId;
// required because JoinedUserAchievments contains composite id
#Embeddable
public static class JoinedUserAchievementId implements Serializable {
/**
*
*/
private static final long serialVersionUID = -9180674903145773104L;
#ManyToOne
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne
#JoinColumn(name="ACHIEVEMENT_ID")
private Achievement achievement;
// required no arg constructor
public JoinedUserAchievementId() {}
public JoinedUserAchievementId(User user, Achievement achievement) {
this.user = user;
this.achievement = achievement;
}
public JoinedUserAchievementId(Integer userId, Integer achievementId) {
this(new User(userId), new Achievement(achievementId));
}
public User getUser() {
return user;
}
public Achievement getAchievement() {
return achievement;
}
public void setUser(User user) {
this.user = user;
}
public void setAchievement(Achievement achievement) {
this.achievement = achievement;
}
#Override
public boolean equals(Object instance) {
if (instance == null)
return false;
if (!(instance instanceof JoinedUserAchievementId))
return false;
final JoinedUserAchievementId other = (JoinedUserAchievementId) instance;
if (!(user.getId().equals(other.getUser().getId())))
return false;
if (!(achievement.getId().equals(other.getAchievement().getId())))
return false;
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (this.user != null ? this.user.hashCode() : 0);
hash = 47 * hash + (this.achievement != null ? this.achievement.hashCode() : 0);
return hash;
}
}
}
Achievement.java
#Entity
#Table(name="ACHIEVEMENT")
public class Achievement implements Serializable{
private static final long serialVersionUID = 7747630789725422177L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer points;
public Achievement() {
}
public Achievement(String name, Integer points) {
this.name = name;
this.points = points;
}
public Achievement(Integer id) {
this.id = id;
}
//set and gets
I've also tried to make this relationship bidirectional and it didn't work, so I may be missing something
Also before this I had achievement objects instead of achievementId on joinedUserAchievement, it worked but I think its not what I need, I don't need to get every achievement object always, with only the id is fine.
From the docs:
Relationship mappings defined within an embedded id class are not supported
You should put the ids only in JoinedUserAchievementId, and put User and Achievement associations in JoinedUserAchievement directly like so:
public class JoinedUserAchievementId {
private Long userId;
private Long achievementId;
...
}
public class JoinedUserAchievement {
#EmbeddedId
private JoinedUserAchievementId joinedUserAchievementId;
#ManyToOne
#MapsId("userId")
#JoinColumn(name = "USER_ID")
private User user;
#ManyToOne(optional = false, fetch = LAZY)
#MapsId("achievementId")
#JoinColumn(name = "ACHIEVEMENT_ID")
private Achievement achievement;
//if you absolutely need to map the achievement_id column here as well
//note that it will already be mapped to joinedUserAchievementId.achievementId
#Column(name = "ACHIEVEMENT_ID", insertable=false, updatable=false)
private Long achievementId;
...
}
Remember to update the User.joinedUserAchievementList mapping to mappedBy="user".
I have 2 classes, TransportOrder and LardiSendedOrder. It's bounded by field innerId, and I just want list all records from LardiSendedOrder table, but got this error.
Error accessing field [private java.lang.Integer com.example.model.LardiSendedOrder.innerId] by reflection for persistent property [com.example.model.LardiSendedOrder#innerId] : 1;
class Transport Order
#Entity
class TransportOrder {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String url;
private String source;
private String transport;
private Date start_date;
private Date end_date;
private String start_address;
private String end_address;
private ArrayList<String> phones =new ArrayList<>()
private Integer distance;
private String content;
private String weight;
private String size;
private Boolean fromVendor;
private ArrayList<PaymentType> payment_type = new ArrayList<PaymentType>();
private Double payment;
private String payment_by;
private ArrayList<PaymentEvent> payment_event = new ArrayList<PaymentEvent>();
private Date add_date;
#NotNull
#Column(unique=true)
private Integer hashCode;
LardiSendedOrder getLardiSendedOrder() {
return lardiSendedOrder
}
void setLardiSendedOrder(LardiSendedOrder lardiSendedOrder) {
this.lardiSendedOrder = lardiSendedOrder
}
#OneToOne
#JoinColumn(
/* referencedColumnName = "innerId"*/
referencedColumnName = "innerId"
)
private LardiSendedOrder lardiSendedOrder;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
//another getters and setters omitted
}
class LardiSendedOrder
#Entity
class LardiSendedOrder {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private Integer innerId;
private Integer outerId;
private Date publish_date;
Integer getUserId() {
return userId
}
void setUserId(Integer userId) {
this.userId = userId
}
private Integer userId;
TransportOrder getTransportOrder() {
return transportOrder
}
void setTransportOrder(TransportOrder transportOrder) {
this.transportOrder = transportOrder
}
#OneToOne(
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "lardiSendedOrder")
private TransportOrder transportOrder;
Integer getInnerId() {
return innerId
}
void setInnerId(Integer innerId) {
this.innerId = innerId
}
Integer getOuterId() {
return outerId
}
void setOuterId(Integer outerId) {
this.outerId = outerId
}
String getPublish_date() {
return publish_date.format("dd.MM.yyyy HH:mm:ss");;
}
void setPublish_date(Date publish_date) {
this.publish_date = publish_date
}
}
And i just call
ArrayList<LardiSendedOrder> orders = (ArrayList<LardiSendedOrder>) lardiSendedOrderRepository.findAll();
I am trying to return json from these two entity classes.
Questions.java
#Entity
public class Questions {
#Id
#Column(name = "id")
private int id;
#Column(name = "question")
private String question;
#Column(name = "type")
private String type;
#Column(name = "description")
private String description;
#Column(name = "param")
private String param;
#Column(name = "maxlength")
private int maxlength;
#Column(name = "dependency")
private String dependency;
#OneToMany(mappedBy = "questions",targetEntity = Answers.class, cascade = CascadeType.ALL)
private Set<Answers> answers = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public String getDependency() {
return dependency;
}
public Set<Answers> getAnswers() {
return answers;
}
public void setAnswers(Set<Answers> answers) {
this.answers = new HashSet<>(answers);
for(Answers answers1:answers){
answers1.setQuestions(this);
}
}
public void setDependency(String dependency) {
this.dependency = dependency;
}
}
Answers.java
#Entity
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "ans_label")
private String ans_label;
#Column(name = "ans_value")
private int ans_value;
#Column(name = "ans_weightage")
private int ans_weightage;
#Column(name = "is_default")
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ques_id", nullable = false)
private Questions questions;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Questions getQuestions() {
return questions;
}
public void setQuestions(Questions questions) {
this.questions = questions;
}
}
my controller looks like this.
SaveApiController
#RequestMapping("/getData")
public #ResponseBody List<Questions> getData(){
List<Questions> questionss=saveApiServices.getQuestions();
return questionss;
}
The json result i am currently getting has bunch of repeated values.
[{"id":1,"question":"१. व्यक्तिको पुरा नाम थर?", "type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
"answers":
[{"id":0,"ans_label":"मुली","ans_value":1,"ans_weightage":0,"is_default":0,
"questions":{"id":1,"question":"१. व्यक्तिको पुरा नाम थर?",
"type":"input_edittext","description":"","param":"smalltext","maxlength":20
,"dependency":"","answers":[{"id":0,"ans_label":"मुली","ans_value":1,
"ans_weightage":0,"is_default":0,"questions":{"id":1,
"question":"१. व्यक्तिको पुरा नाम थर ?","type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
"answers":[{"id":0,"ans_label":"मुली",
"ans_value":1,"ans_weightage":0,"is_default":0,"questions":{"id":1,
"question":"१. व्यक्तिको पुरा नाम थर ?","type":"input_edittext",
"description":"","param":"smalltext","maxlength":20,"dependency":"",
my database has only one row inserted. and on my controller there is only one list of questions found. but whenever json output is thrown it repeats a lot of same rows like in the above json sample.
what might be the problems? if you can't find the complete solution can you please suggest me the reason behind the duplication of the same values in json format?
Jackson is getting in a loop here. Your Questions class has a link to Answers and that class refers back to Questions.
Solution
Mark the questions field or the getter in the Answers class as #JsonIgnored.
You can try #JsonManagedReference and #JsonBackReference annotations
For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.
#OneToMany(mappedBy = "questions",targetEntity = Answers.class, cascade = CascadeType.ALL)
#JsonManagedReference
private Set<Answers> answers = new HashSet<>();
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ques_id", nullable = false)
#JsonBackReference
private Questions questions;
Or
If not interested in getting some entity data just use #JsonIgnore in any one of the class
I'm creating a simple REST server using Spring framework.
One of the class needs to have a self join one to many relationship to retrieve the data about it's parents object. The class looks like this;
#Entity
#Table(name = "item", schema = "tmp", uniqueConstraints = {
#UniqueConstraint(columnNames = "item_id"), #UniqueConstraint(columnNames = "item_name")})
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private Integer itemId;
private String itemName;
private String itemDescription;
private Item itemParent;
private boolean isEndItem;
private List<Item> childrenItems;
public Item() {}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "item_id", unique = true, nullable = false)
public Integer getItemId() {
return itemId;
}
public void setItemId(final Integer itemId) {
this.itemId = itemId;
}
#Column(name = "item_name", unique = true, nullable = false)
public String getItemName() {
return itemName;
}
public void setItemName(final String itemName) {
this.itemName = itemName;
}
#Column(name = "item_description", unique = false, nullable = false)
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(final String itemDescription) {
this.itemDescription = itemDescription;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JsonManagedReference(value = "item-item")
#JoinColumn(name="item_parentid")
public Item getParentItem() {
return this.itemParent;
}
public void setParentItem(final Item itemParent){
this.itemParent = itemParent;
}
#OneToMany(mappedBy="childrenItems", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JsonBackReference(value = "item-item")
public List<Item> getChildrenItems(){
return this.childrenItems;
}
public void setChildrenItems(final List<Item> childrenItems){
this.childrenItems = childrenItems;
}
#Column(name = "item_isendproduct", unique = false, nullable = false)
public boolean isEndItem() {
return isEndItem;
}
public void setEndItem(final boolean isEndItem) {
this.isEndItem = isEndItem;
}
}
In my database, testing data is saved in this hierarchy:
Entry > Salad > House Salad
[
{
"itemId":1,
"itemName":"Entry",
"itemDescription":"Entry Menu",
"endItem":false,
"parentItem":null
},
{
"itemId":2,
"itemName":"Salad",
"itemDescription":"Salad Menu",
"endItem":false,
"parentItem":{
"itemId":1,
"itemName":"Entry",
"itemDescription":"Entry Menu",
"endItem":false,
"parentItem":null
}
},
{
"itemId":3,
"itemName":"House Salad",
"itemDescription":"House Salad",
"endItem":true,
"parentItem":{
"itemId":2,
"itemName":"Salad",
"itemDescription":"Salad Menu",
"endItem":false,
"parentItem":{
"itemId":1,
"itemName":"Entry",
"itemDescription":"Entry Menu",
"endItem":false,
"parentItem":null
}
}
}
]
But I don't want to know the information about the parent's parent object.
Is there any annotations that I can use to achieve this?
Thank in advance