Invoking method in setter of #Entity class - java

I only need to get first name and last name into attribute ownerName and for me the best solution would be if I just call the setter for ownerName in setter of conversationOwner but with this I am getting error:
Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Exception occurred inside setter of medictonproject.model.ConversationEntity.conversationOwner
Here is the Entity class:
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.*;
import org.hibernate.annotations.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "conversation", schema = "swprojekt")
public class ConversationEntity {
private int conversationId;
private String title;
private Timestamp beginningDate;
#JsonIgnore
private UserEntity conversationOwner;
private String ownerName;
#JsonIgnore
private List<MessageEntity> messages = new ArrayList<>();
private MessageEntity firstMessage;
private boolean seen;
#Transient
public MessageEntity getFirstMessage() {
return firstMessage;
}
public void setFirstMessage(MessageEntity firstMessage) {
this.firstMessage = firstMessage;
}
#Transient
public boolean isSeen() {
return seen;
}
public void setSeen( boolean seen ) {
this.seen = seen;
}
#OneToMany(mappedBy="conversation", cascade = javax.persistence.CascadeType.ALL)
public List<MessageEntity> getMessages() {
return messages;
}
public void setMessages(List<MessageEntity> messages) {
this.messages = messages;
}
#ManyToOne(fetch=FetchType.LAZY, cascade = javax.persistence.CascadeType.ALL)
#JoinColumn(name="user_id")
public UserEntity getConversationOwner() {
return conversationOwner;
}
public void setConversationOwner(UserEntity conversationOwner) {
this.conversationOwner = conversationOwner;
setOwnerName();
}
#Transient
public String getOwnerName() {
return ownerName;
}
public void setOwnerName() {
this.ownerName = conversationOwner.getFirstName() + " " + conversationOwner.getLastName();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "conversation_id", nullable = false)
public int getConversationId() {
return conversationId;
}
public void setConversationId(int conversationId) {
this.conversationId = conversationId;
}
#Basic
#Column(name = "title", nullable = false, length = 200)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Basic
#Column(name = "beginning_date", nullable = false)
public Timestamp getBeginningDate() {
return beginningDate;
}
public void setBeginningDate(Timestamp beginningDate) {
this.beginningDate = beginningDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConversationEntity that = (ConversationEntity) o;
if (conversationId != that.conversationId) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
if (beginningDate != null ? !beginningDate.equals(that.beginningDate) : that.beginningDate != null)
return false;
return true;
}
#Override
public int hashCode() {
int result = conversationId;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (beginningDate != null ? beginningDate.hashCode() : 0);
return result;
}
}

Related

Unable to add value to entity

I can’t set the discipline values ​​​​for my semester, when I work out the controller, I get all the data I need, but I can’t connect them, can anyone tell me with an experienced eye what is the reason? I am getting this kind of error:
Request processing failed; nested exception is
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.kushnirmark.spring.project.entity.Discipline.id] by reflection for persistent property [com.kushnirmark.spring.project.entity.Discipline#id] : Higher mathematics
Here is my entity Semestr:
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "semestr")
public class Semestr {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
#Column(name = "duration")
private String duration;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_semestr"),
inverseJoinColumns = #JoinColumn(name = "id_discipline")
)
private List<Discipline> disciplineList;
public void addDisciplineToSemester(Discipline discipline) {
if (disciplineList == null) {
disciplineList = new ArrayList<>();
}
disciplineList.add(discipline);
}
public Semestr() {
}
public Semestr(int id, String name, String duration, boolean status) {
this.id = id;
this.name = name;
this.duration = duration;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Discipline> getDisciplineList() {
return disciplineList;
}
public void setDisciplineList(List<Discipline> disciplineList) {
this.disciplineList = disciplineList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Semestr semestr = (Semestr) o;
if (id != semestr.id) return false;
if (status != semestr.status) return false;
if (name != null ? !name.equals(semestr.name) : semestr.name != null) return false;
return duration != null ? duration.equals(semestr.duration) : semestr.duration == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (duration != null ? duration.hashCode() : 0);
result = 31 * result + (status ? 1 : 0);
return result;
}
#Override
public String toString() {
return "Semestr{" +
"id=" + id +
", name='" + name + '\'' +
", duration='" + duration + '\'' +
", status=" + status +
'}';
}
}
Controller :
#RequestMapping("/saveNewSemester")
public String saveNewSemester(#ModelAttribute("semestr") Semestr semestr,
#RequestParam(name = "AllDiscipline") String[] AllDiscipline,
Model model) {
List<Integer> list = Arrays.stream(AllDiscipline).map(Integer::parseInt).collect(Collectors.toList());
List<Discipline> disciplineSemestrList = service.getDisciplineList(list);
semestr.setDisciplineList(disciplineSemestrList);
service.saveNewSemester(semestr);
return "redirect:/semestr";
}
Here is my entity Discipline :
package com.kushnirmark.spring.project.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "discipline")
public class Discipline {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "discipline")
private String discipline;
#Column(name = "status")
private boolean status = true;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "semestr_discipline",
joinColumns = #JoinColumn(name = "id_discipline"),
inverseJoinColumns = #JoinColumn(name = "id_semestr")
)
private List<Semestr> semestrList;
public void addSemesterToDiscipline(Semestr semestr) {
if (semestrList == null) {
semestrList = new ArrayList<>();
}
semestrList.add(semestr);
}
public Discipline() {
}
public Discipline(int id, String discipline, boolean status) {
this.id = id;
this.discipline = discipline;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiscipline() {
return discipline;
}
public void setDiscipline(String discipline) {
this.discipline = discipline;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Semestr> getSemestrList() {
return semestrList;
}
public void setSemestrList(List<Semestr> semestrList) {
this.semestrList = semestrList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Discipline that = (Discipline) o;
return id == that.id &&
status == that.status &&
Objects.equals(discipline, that.discipline);
}
#Override
public int hashCode() {
return Objects.hash(id, discipline, status);
}
#Override
public String toString() {
return "Discipline{" +
"id=" + id +
", discipline='" + discipline + '\'' +
", status=" + status +
'}';
}
}

Request hibernate with #EmbeddedId not working (Spring boot - 2.3.1.RELEASE)

I'm blocked in my project. I can't get sql queries to work with the class that's "#Embeddable."
I have a class "User" which have multiple "Preference"
package com.donation.rest.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import com.donation.rest.converter.RightConverter;
import com.donation.rest.dto.UserDTO;
import com.donation.rest.enums.RightsEnum;
#Entity
#Table(name = "users")
public class User extends DateModel implements IModel {
private static final long serialVersionUID = 6678092850253642056L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", unique = true, updatable = false, nullable = false)
private Long id;
#Column(name = "USER_NAME", unique = true, nullable = false)
#Pattern(regexp = "^[a-zA-Z0-9]*$")
private String name;
#Column(name = "USER_PASSWORD", nullable = false)
private String password;
#ElementCollection(targetClass = RightsEnum.class, fetch = FetchType.EAGER)
#CollectionTable(name = "users_rights", joinColumns = #JoinColumn(name = "USER_ID"))
#Column(name = "RIGHTS", nullable = false)
#Convert(converter = RightConverter.class)
private Set<RightsEnum> rights = new HashSet<RightsEnum>();
#OneToMany(mappedBy = "preferenceId.user", cascade = CascadeType.REMOVE)
private Set<Preference> preferences = new HashSet<Preference>();
public User() {
super();
}
public User(Long id, String name, String password, Set<RightsEnum> rights, Set<Preference> preferences) {
super();
this.id = id;
this.name = name;
this.password = password;
this.rights = rights;
this.preferences = preferences;
}
public User(UserDTO userDTO) {
this.setName(userDTO.getName());
this.setPassword(userDTO.getPassword());
this.setRights(userDTO.getRights());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<RightsEnum> getRights() {
return rights;
}
public void setRights(Set<RightsEnum> rights) {
this.rights = rights;
}
public Set<Preference> getPreferences() {
return preferences;
}
public void setPreferences(Set<Preference> preferences) {
this.preferences = preferences;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", rights=" + rights + ", preferences="
+ preferences + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof User))
return false;
User other = (User) obj;
if (id == null) {
if (other.getId() != null)
return false;
} else if (!id.equals(other.getId()))
return false;
return true;
}
}
I have the class "Preference" which use two primary key : an user and a key (enum). So I use the annotation #EmbeddedId and declare PreferenceId.
package com.donation.rest.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
#Entity
#Table(name = "preferences")
public class Preference implements Serializable {
private static final long serialVersionUID = 6320680839053872351L;
#EmbeddedId
private PreferenceId preferenceId;
#Column(name = "PREFERENCE_VALUE", nullable = false)
#Type(type = "text")
private String value;
public Preference() {
super();
}
public Preference(PreferenceId preferenceId, String value) {
super();
this.preferenceId = preferenceId;
this.value = value;
}
public PreferenceId getPreferenceId() {
return preferenceId;
}
public void setPreferenceId(PreferenceId preferenceId) {
this.preferenceId = preferenceId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "Preference [preferenceId=" + preferenceId + ", value=" + value + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((preferenceId == null) ? 0 : preferenceId.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Preference other = (Preference) obj;
if (preferenceId == null) {
if (other.preferenceId != null)
return false;
} else if (!preferenceId.equals(other.preferenceId))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
Then, the class "PreferenceId" which is "#Embeddable".
package com.donation.rest.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.donation.rest.enums.PreferencesEnum;
#Embeddable
public class PreferenceId implements Serializable {
private static final long serialVersionUID = 5641070814677067804L;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
#JoinColumn(name = "USER_ID", nullable = false)
private User user;
#Enumerated(EnumType.STRING)
#Column(name = "PREFERENCE_KEY", updatable = false, nullable = false)
private PreferencesEnum key;
public PreferenceId() {
super();
}
public PreferenceId(User user, PreferencesEnum key) {
super();
this.user = user;
this.key = key;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public PreferencesEnum getKey() {
return key;
}
public void setKey(PreferencesEnum key) {
this.key = key;
}
#Override
public String toString() {
return "PreferenceId [user=" + user + ", key=" + key + "]";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PreferenceId other = (PreferenceId) obj;
if (key != other.key)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
}
I have a controller which return a value of preference with user id and key parameter.
Controller
Next is the service. This is where my problems begin. I've tested a lot of calls from the jpa repository that I've commented on.
Service
Here the repository :
Repository
The preference I want to retrieve from the database is:
Preference key: LANGUAGE
Preference user id: 1
Preference value : fr
Now the request I used in postman :
Request
And here's the mistake with the request Hibernate made.
I don't get it. It duplicates the fields and also it doesn't use the embedded id field (it doesn't do "preference.preferenceId.user.userId" and "preference.preferenceId.key").
Error
What'd I miss? What did I do wrong? I've looked it all up on the internet, I've tested everything, I just can't do it...
Otherwise, I used "Embeddedid" instead of "IdClass" to avoid duplicating the getters and setters.
Thanks to you guys.

hibernate onetomany annotation fetch = FetchType.LAZY didn't work

I have three tables A,B and C. Table B has a foreign key a_id reference to table A, Table B has a foreign key a_id reference to table A. And my hibernate entity files are as following:
A.java
#Entity
#Table(name = "A")
public class A {
private long id;
private String contentA;
private List<B> bList;
private List<C> cList;
#OneToMany(fetch = FetchType.EAGER , mappedBy = "b")
public List<B> getbList() {
return bList;
}
public void setbList(List<B> bList) {
this.bList = bList;
}
#OneToMany(fetch = FetchType.EAGER , mappedBy = "b")
public List<C> getcList() {
return cList;
}
public void setcList(List<C> cList) {
this.cList = cList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_a", nullable = false, length = 1000)
public String getContentA() {
return contentA;
}
public void setContentA(String contentA) {
this.contentA = contentA;
}
}
B.java
#Entity
#Table(name = "B")
public class B {
private long id;
private String contentB;
private A a;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "a_id", nullable = false)
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_b", nullable = false, length = 1000)
public String getContentB() {
return contentB;
}
public void setContentB(String contentB) {
this.contentB = contentB;
}
}
C.java
#Entity
#Table(name = "C")
public class C {
private long id;
private String contentC;
private A a;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "a_id", nullable = false)
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_c", nullable = false, length = 1000)
public String getContentC() {
return contentC;
}
public void setContentC(String contentC) {
this.contentC = contentC;
}
}
the problem is sometimes I just want to get A with List<B>, in another time I want to get A with List<C>. Is there any way I can do this by hibernate?
------------------------divide line----------------------
In my real project, I have three entity class: ChapterEntity ChapterTitle1Entity ChapterTitle2Entity ChapterTitle3Entity. There is a private List<ChapterTitle1Entity> chapterTitle1EntityList; in ChapterEntity, also private List<ChapterTitle2Entity> chapterTitle2EntityList; in ChapterTitle2Entity, private List<ChapterTitle3Entity> chapterTitle3EntityList; in ChapterTitle2Entity.
I just want to get a list of ChapterEntity with sublist List<ChapterTitle1Entity> chapterTitle1EntityList, the lazy load annotation didn't work. the following are my class files
ChapterEntity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter")
public class ChapterEntity {
private List<ChapterTitle1Entity> chapterTitle1EntityList;
private long id;
private int sequence;
private String content;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "chapterEntity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle1Entity> getChapterTitle1EntityList() {
return chapterTitle1EntityList;
}
public void setChapterTitle1EntityList(List<ChapterTitle1Entity> chapterTitle1EntityList) {
this.chapterTitle1EntityList = chapterTitle1EntityList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterEntity that = (ChapterEntity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
return result;
}
}
ChapterTitle1Entity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-11
* Time 6:09 PM
*/
#Entity
#Table(name = "chapter_title_1", schema = "tutorial2")
public class ChapterTitle1Entity {
private long id;
private int sequence;
private String content;
// private long chapterId;
/**
* 1:章前测试,2:实际的测试
*/
private int type;
private ChapterEntity chapterEntity;
private List<ChapterTitle2Entity> chapterTitle2EntityList;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chapterTitle1Entity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle2Entity> getChapterTitle2EntityList() {
return chapterTitle2EntityList;
}
public void setChapterTitle2EntityList(List<ChapterTitle2Entity> chapterTitle2EntityList) {
this.chapterTitle2EntityList = chapterTitle2EntityList;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "chapter_id", nullable = false)
public ChapterEntity getChapterEntity() {
return chapterEntity;
}
public void setChapterEntity(ChapterEntity chapterEntity) {
this.chapterEntity = chapterEntity;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "chapter_id", nullable = false)
public long getChapterId() {
return chapterId;
}
public void setChapterId(long chapterId) {
this.chapterId = chapterId;
}
*/
#Basic
#Column(name = "type", nullable = false)
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle1Entity that = (ChapterTitle1Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
// if (chapterId != that.chapterId) return false;
if (type != that.type) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + (int) (chapterId ^ (chapterId >>> 32));
result = 31 * result + type;
return result;
}
}
ChapterTitle2Entity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter_title_2")
public class ChapterTitle2Entity {
private long id;
private int sequence;
private String content;
// private long title1Id;
private List<ChapterTitle3Entity> chapterTitle3EntityList;
private ChapterTitle1Entity chapterTitle1Entity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "title_1_id", nullable = false)
public ChapterTitle1Entity getChapterTitle1Entity() {
return chapterTitle1Entity;
}
public void setChapterTitle1Entity(ChapterTitle1Entity chapterTitle1Entity) {
this.chapterTitle1Entity = chapterTitle1Entity;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chapterTitle2Entity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle3Entity> getChapterTitle3EntityList() {
return chapterTitle3EntityList;
}
public void setChapterTitle3EntityList(List<ChapterTitle3Entity> chapterTitle3EntityList) {
this.chapterTitle3EntityList = chapterTitle3EntityList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "title_1_id", nullable = false)
public long getTitle1Id() {
return title1Id;
}
public void setTitle1Id(long title1Id) {
this.title1Id = title1Id;
}
*/
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle2Entity that = (ChapterTitle2Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
// if (title1Id != that.title1Id) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + (int) (title1Id ^ (title1Id >>> 32));
return result;
}
}
ChapterTitle3Entity.java
package com.hnu.tutorial.model.entity;
import javax.persistence.*;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter_title_3")
public class ChapterTitle3Entity {
private long id;
private int sequence;
private String content;
// private long title2Id;
private ChapterTitle2Entity chapterTitle2Entity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "title_2_id", nullable = false)
public ChapterTitle2Entity getChapterTitle2Entity() {
return chapterTitle2Entity;
}
public void setChapterTitle2Entity(ChapterTitle2Entity chapterTitle2Entity) {
this.chapterTitle2Entity = chapterTitle2Entity;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "title_2_id", nullable = false)
public long getTitle2Id() {
return title2Id;
}
public void setTitle2Id(long title2Id) {
this.title2Id = title2Id;
}
*/
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle3Entity that = (ChapterTitle3Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
return result;
}
}
my DAO layer ChapterDAO.java
package com.hnu.tutorial.model.dao;
import com.hnu.tutorial.model.entity.ChapterEntity;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9
* Time 11:13 PM
*/
#Repository
public class ChapterDAO extends BaseDAO<ChapterEntity> {
public List<ChapterEntity> chapterEntityList(){
Criteria criteria = session().createCriteria(ChapterEntity.class, "chapter");
criteria.createAlias("chapter.chapterTitle1EntityList", "title1List");
criteria.addOrder(Order.desc("title1List.sequence"));
List<ChapterEntity> chapterEntityList = criteria.list();
return chapterEntityList;
/*String hql = "from ChapterEntity";
List<ChapterEntity> chapterEntityList = session().createQuery(hql).list();
return chapterEntityList;*/
}
}
my service layer ChapterSvc
package com.hnu.tutorial.service.impl;
import com.hnu.tutorial.model.dao.ChapterDAO;
import com.hnu.tutorial.model.entity.ChapterEntity;
import com.hnu.tutorial.model.entity.ChapterTitle1Entity;
import com.hnu.tutorial.service.dto.ChapterDTO;
import com.hnu.tutorial.service.dto.ChapterTitle1DTO;
import com.hnu.tutorial.service.interfaces.IChapterSvc;
import com.hnu.tutorial.utils.BeanMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-10
* Time 10:59 AM
*/
#Service
#Transactional
public class ChapterSvc implements IChapterSvc {
#Autowired
private ChapterDAO chapterDAO;
#Override
public List<ChapterDTO> chapterDTOList() {
List<ChapterEntity> chapterEntityList = chapterDAO.chapterEntityList();
List<ChapterDTO> chapterDTOList = BeanMap.mapList(chapterEntityList, ChapterDTO.class);
for(ChapterDTO chapterDTO:chapterDTOList){
List<ChapterTitle1Entity> chapterTitle1EntityList = chapterDTO.getChapterTitle1EntityList();
for (ChapterTitle1Entity chapterTitle1Entity:chapterTitle1EntityList){
chapterTitle1Entity.setChapterEntity(null);
}
}
return chapterDTOList;
}
}
Each time when I query the chapter list, I get all the sub list. Even when I set a breakpoint in the end of method chapterEntityList() of my service layer, I also get all the sub list. I also tried query a list use hql, but it still didn't work.
Change FetchType.EAGER to FetchType.LAZY in your #OneToMany annotations. This will casue Hibernate to load a collection only when you directly refer to it.

failed to lazily initialize a collection of role ManyToMany relation

I have an entity question and an entity test with ManyToMany relationship between the two entitie.
when I want to view the questions of a test this error is occurred.
failed to lazily initialize a collection of role:
tn.esen.entities.Test.questions, could not initialize proxy - no Session
this is the JPA implementation of the two entities.
Question:
package tn.esen.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
#Entity
public class Question implements Serializable {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contenu == null) ? 0 :
contenu.hashCode());
result = prime * result + ((dateCreation == null) ? 0 :
dateCreation.hashCode());
result = prime * result + ((niveauDeDifficulte == null) ? 0 :
niveauDeDifficulte.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Question other = (Question) obj;
if (contenu == null) {
if (other.contenu != null)
return false;
} else if (!contenu.equals(other.contenu))
return false;
if (dateCreation == null) {
if (other.dateCreation != null)
return false;
} else if (!dateCreation.equals(other.dateCreation))
return false;
if (niveauDeDifficulte == null) {
if (other.niveauDeDifficulte != null)
return false;
} else if (!niveauDeDifficulte.equals(other.niveauDeDifficulte))
return false;
return true;
}
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_question")
private int id;
private String contenu;
private String niveauDeDifficulte;
private Date dateCreation;
#OneToMany(mappedBy="question",fetch = FetchType.EAGER)
private Collection <Reponse> reponses;
#ManyToOne
private Categorie categorie;
#ManyToOne
private Administrateur administrateur;
#ManyToMany(mappedBy = "questions",fetch = FetchType.EAGER)
private Collection<Test> tests;
public Question(){
super();
}
#Override
public String toString() {
return "Question [id=" + id + ", contenu=" + contenu + ",
niveauDeDifficulte=" + niveauDeDifficulte + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
public String getNiveauDeDifficulte() {
return niveauDeDifficulte;
}
public void setNiveauDeDifficulte(String niveauDeDifficulte) {
this.niveauDeDifficulte = niveauDeDifficulte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Collection<Reponse> getReponses() {
return reponses;
}
public void setReponses(Collection<Reponse> reponses) {
this.reponses = reponses;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Administrateur getAdministrateur() {
return administrateur;
}
public void setAdministrateur(Administrateur administrateur) {
this.administrateur = administrateur;
}
public Collection<Test> getTest() {
return tests;
}
public void setTest(Collection<Test> tests) {
this.tests = tests;
}
public Question(String contenu, String niveauDeDifficulte, Date
dateCreation) {
super();
this.contenu = contenu;
this.niveauDeDifficulte = niveauDeDifficulte;
this.dateCreation = dateCreation;
}
Test:
package tn.esen.entities;
#Entity
public class Test implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String duree;
private String typeDePreparation;
private String lieu;
private int nbrQuestionFacile;
private int nbrQuestionMoyen;
private int nbrQuestionDifficle;
#OneToMany(mappedBy = "test")
private Collection<Resultat> resultats;
#ManyToMany
private Collection<Question> questions;
#ManyToOne
private ResponsableTechnique responsableTechnique;
public Test() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDuree() {
return duree;
}
public void setDuree(String duree) {
this.duree = duree;
}
public Collection<Question> getQuestions() {
return questions;
}
public void setQuestions(Collection<Question> questions) {
this.questions = questions;
}
public Test(String duree, String typeDePreparation, String lieu, int
nbrQuestionFacile, int nbrQuestionMoyen,
int nbrQuestionDifficle) {
super();
this.duree = duree;
this.typeDePreparation = typeDePreparation;
this.lieu = lieu;
this.nbrQuestionFacile = nbrQuestionFacile;
this.nbrQuestionMoyen = nbrQuestionMoyen;
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public ResponsableTechnique getRésponsableTechnique() {
return responsableTechnique;
}
public void setRésponsableTechnique(ResponsableTechnique
résponsableTechnique) {
this.responsableTechnique = résponsableTechnique;
}
public String getTypeDePreparation() {
return typeDePreparation;
}
public void setTypeDePreparation(String typeDePreparation) {
this.typeDePreparation = typeDePreparation;
}
public String getLieu() {
return lieu;
}
public void setLieu(String lieu) {
this.lieu = lieu;
}
public int getNbrQuestionFacile() {
return nbrQuestionFacile;
}
public void setNbrQuestionFacile(int nbrQuestionFacile) {
this.nbrQuestionFacile = nbrQuestionFacile;
}
public int getNbrQuestionMoyen() {
return nbrQuestionMoyen;
}
public void setNbrQuestionMoyen(int nbrQuestionMoyen) {
this.nbrQuestionMoyen = nbrQuestionMoyen;
}
public int getNbrQuestionDifficle() {
return nbrQuestionDifficle;
}
public void setNbrQuestionDifficle(int nbrQuestionDifficle) {
this.nbrQuestionDifficle = nbrQuestionDifficle;
}
public Collection<Resultat> getResultats() {
return resultats;
}
public void setRésultats(Collection<Resultat> resultats) {
this.resultats = resultats;
}
}
}
When you get Test and access Test.questions later, after leaving the transaction, you will get a lazy initialization exception when the Test entity is detached and questions has not been initialized/fetched yet. You can either do a specific fetch, or depending on your configuration, you can call Test.getQuestions().size() before you exit the transaction.
References: How to solve lazy initialization exception using JPA and Hibernate as provider
LazyInitializationException in JPA and Hibernate
Hibernate LazyInitializationException using Spring CrudRepository

SPRING JPA - org.hibernate.PersistentObjectException: detached entity passed to persist:

I've been stuck here for almost a week trying find the answer on the internet but sadly nothing worked. :( Everytime I try to update using this method:
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
Im always getting this error:
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.infor.ecom.tenant.manager.model.entity.ApplicationProperty
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:876)
But when Im using this method it works fine:
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
So here is my complete codes:
Tenant.java
package com.infor.ecom.tenant.manager.model.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.infor.ecom.tenant.manager.constant.TenantManagerConstants;
import com.infor.ecom.tenant.manager.constant.TenantStatusEnum;
#Entity
#Table(name="tenant")
#XmlRootElement(name = "Tenant",namespace = "http://com.infor.ecom.tenant.manager/Tenant")
public class Tenant extends BaseModel {
private static final long serialVersionUID = -6687293822212120396L;
#Id
private String id;
private String displayName;
private String description;
private String url;
private String apiKey;
private String status;
#OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Database> databases;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Activity> activites;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Administrator> administrators;
private String message;
#OneToMany(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<TenantApplicationProperty> tenantApplicationProperties;
#OneToOne(mappedBy = "tenant", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private Product product;
public Database findEcomDatabase() {
Database database = null;
if(databases != null) {
for(Database db : databases) {
if(db.getDatasource() != null) {
if(TenantManagerConstants.ECOM_DATASOURCE.equals(db.getDatasource().getName())) {
database = db;
break;
}
}
}
}
return database;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getStatus() {
return status;
}
public void setStatus(TenantStatusEnum statusEnum) {
this.status = statusEnum.name();
}
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
public void addDatabase(Database database) {
if (this.databases == null) {
this.databases = new ArrayList<Database>();
}
database.setTenant(this);
this.databases.add(database);
}
public List<Activity> getActivites() {
return activites;
}
public void setActivites(List<Activity> activities) {
this.activites = activities;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setStatus(String status) {
this.status = status;
}
public List<Administrator> getAdministrators() {
return this.administrators;
}
public void setAdministrators(List<Administrator> administrators) {
for (Administrator admin:administrators) {
admin.setTenant(this);
}
this.administrators = administrators;
}
public void addAdministrator(Administrator administrator) {
if (this.administrators == null) {
this.administrators = new ArrayList<Administrator>();
}
administrator.setTenant(this);
this.administrators.add(administrator);
}
public List<TenantApplicationProperty> getTenantApplicationProperties() {
return tenantApplicationProperties;
}
public void setTenantApplicationProperties(
List<TenantApplicationProperty> tenantApplicationProperties) {
this.tenantApplicationProperties = tenantApplicationProperties;
}
public void addTenantApplicationProperty(TenantApplicationProperty tenantApplicationProperty) {
if (this.tenantApplicationProperties == null) {
this.tenantApplicationProperties = new ArrayList<TenantApplicationProperty>();
}
tenantApplicationProperty.setTenant(this);
this.tenantApplicationProperties.add(tenantApplicationProperty);
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
product.setTenant(this);
this.product = product;
}
}
TenantApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.infor.ecom.tenant.manager.model.entity.pk.TenantApplicationPropertyPK;
#Entity
#Table(name = "tenant_application_property")
#IdClass(TenantApplicationPropertyPK.class)
public class TenantApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
#Id
#OneToOne
#JoinColumn(name = "application_property_id")
private ApplicationProperty applicationProperty;
private String value;
public TenantApplicationProperty() {
super();
}
/**
* Added constructor to handle custom query for
* findByTenantIdApplicationPropertyName. No need to retrieve Tenant and
* ApplicationProperty
*
* #param value
*/
public TenantApplicationProperty(String value) {
setTenant(null);
setApplicationProperty(null);
setValue(value);
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public ApplicationProperty getApplicationProperty() {
return applicationProperty;
}
public void setApplicationProperty(ApplicationProperty applicationProperty) {
this.applicationProperty = applicationProperty;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
return result;
}
#Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
TenantApplicationProperty tenantAppProp = (TenantApplicationProperty) object;
if (applicationProperty == null) {
if (tenantAppProp.applicationProperty != null) {
return false;
}
} else if (!applicationProperty.getApplicationPropertyGroup().getName().equals(tenantAppProp.applicationProperty.getApplicationPropertyGroup().getName())
|| !applicationProperty.getName().equals(tenantAppProp.applicationProperty.getName())) {
return false;
}
return true;
}
}
TenanatApplicationPropertyPK.java
package com.infor.ecom.tenant.manager.model.entity.pk;
public class TenantApplicationPropertyPK implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String tenant;
private Integer applicationProperty;
public String getTenantId() {
return tenant;
}
public void setTenantId(String tenant) {
this.tenant = tenant;
}
public Integer getApplicationPropertyId() {
return applicationProperty;
}
public void setApplicationPropertyId(Integer applicationProperty) {
this.applicationProperty = applicationProperty;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((applicationProperty == null) ? 0 : applicationProperty
.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TenantApplicationPropertyPK tenantAppPropPK = (TenantApplicationPropertyPK) obj;
if (applicationProperty == null) {
if (tenantAppPropPK.applicationProperty != null) {
return false;
}
} else if (!applicationProperty
.equals(tenantAppPropPK.applicationProperty)) {
return false;
}
if (tenant == null) {
if (tenantAppPropPK.tenant != null) {
return false;
}
} else if (!tenant.equals(tenantAppPropPK.tenant)) {
return false;
}
return true;
}
}
ApplicationProperty.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "application_property")
public class ApplicationProperty extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String defaultValue;
private boolean isVisible;
private boolean clientVisible;
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public boolean getIsVisible() {
return isVisible;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public boolean getClientVisible() {
return clientVisible;
}
public void setClientVisible(boolean clientVisible) {
this.clientVisible = clientVisible;
}
public ApplicationPropertyGroup getApplicationPropertyGroup() {
return applicationPropertyGroup;
}
public void setApplicationPropertyGroup(ApplicationPropertyGroup applicationPropertyGroup) {
this.applicationPropertyGroup = applicationPropertyGroup;
}
public ApplicationPropertyType getApplicationPropertyType() {
return applicationPropertyType;
}
public void setApplicationPropertyType(ApplicationPropertyType applicationPropertyType) {
this.applicationPropertyType = applicationPropertyType;
}
}
ApplicationPropertyGroup.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_group")
public class ApplicationPropertyGroup extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ApplicationPropertyType.java
package com.infor.ecom.tenant.manager.model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "application_property_type")
public class ApplicationPropertyType extends BaseModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TenantServiceImpl.java
private Tenant updateTenantWithApplicationProperties(List<TenantApplicationProperty> newTenantApplicationProperties, String tenantId) {
String reason = "Update application properties.";
Tenant existingTenant = tenantRepository.findById(tenantId);
List<TenantApplicationProperty> temp = existingTenant.getTenantApplicationProperties();
existingTenant.setTenantApplicationProperties(newTenantApplicationProperties);
setApplicationPropertiesUpdateValues(temp, existingTenant);
if(newTenantApplicationProperties != null && newTenantApplicationProperties.size() != 0) {
Tenant savedTenantWithAppProps = saveTenantWithLog(existingTenant, reason);
return savedTenantWithAppProps;
}
return existingTenant;
}
private Tenant saveTenantWithLog(Tenant tenant, String reason) {
Tenant updatedTenant = tenantRepository.save(tenant);
TenantLog tenantLog = new TenantLog();
tenantLog.setTenantId(updatedTenant.getId());
tenantLog.setDisplayName(updatedTenant.getDisplayName());
tenantLog.setDescription(updatedTenant.getDescription());
tenantLog.setUrl(updatedTenant.getUrl());
tenantLog.setApiKey(updatedTenant.getApiKey());
tenantLog.setStatus(TenantStatusEnum.valueOf(updatedTenant.getStatus()));
tenantLog.setReason(reason);
tenantLog.setMessage(updatedTenant.getMessage());
tenantLogRepository.save(tenantLog);
return updatedTenant;
}
private void setApplicationPropertiesUpdateValues(List<TenantApplicationProperty> existingTenantAppProps, Tenant tenant) {
List<TenantApplicationProperty> newTenantApplicationProperties = (tenant.getTenantApplicationProperties() != null) ? tenant.getTenantApplicationProperties() : new ArrayList<TenantApplicationProperty>();
if(newTenantApplicationProperties.size() != 0) {
for(TenantApplicationProperty tenantAppProp : newTenantApplicationProperties) {
int index = existingTenantAppProps.indexOf(tenantAppProp);
if (index < 0) {
// throw an error -- tenantAppProp should always exist, right?
} else {
existingTenantAppProps.get(index).setValue(tenantAppProp.getValue());
}
}
tenant.setTenantApplicationProperties(existingTenantAppProps);
}
}
public Tenant updateTenant(Tenant tenant) {
List<Database> databases = tenant.getDatabases();
List<Administrator> administrators = tenant.getAdministrators();
validateUpdateTenant(tenant);
validateDatabases(databases);
validateAdministrators(administrators);
Tenant existingTenant = findByIdWithAllDetails(tenant.getId());
List<Database> listExistingDatabases = existingTenant.getDatabases();
Database existingEcomDb = getDatabaseByType(listExistingDatabases,
TenantManagerConstants.ECOM_DATASOURCE);
setDatabaseUpdateValues(listExistingDatabases, tenant);
setAdministratorsUpdateValues(existingTenant.getAdministrators(),
tenant);
setProductUpdateValue(existingTenant.getProduct(), tenant);
setApplicationPropertiesUpdateValues(existingTenant.getTenantApplicationProperties(), tenant);
setEcomDBParamsDefaultValues(tenant);
setAdministratorDefaultValues(tenant);
Database updateEcomDb = getDatabaseByType(tenant.getDatabases(),
TenantManagerConstants.ECOM_DATASOURCE);
Boolean shouldInstallNewDB = true;
if (existingEcomDb.getName().equalsIgnoreCase(updateEcomDb.getName())
&& existingEcomDb.getHost().equalsIgnoreCase(
updateEcomDb.getHost())
&& existingEcomDb.getPort().equals(updateEcomDb.getPort())) {
shouldInstallNewDB = false;
} else {
testEcomDBConnection(updateEcomDb);
}
int ecomDbTableCount = getEcomDBTableCount(updateEcomDb);
String[][] languages = formatAndValidateLanguages(updateEcomDb
.getEcomDatabaseParameters().getLanguages());
Tenant updatedTenant = saveExistingTenant(tenant);
if (updatedTenant != null) {
if (shouldInstallNewDB || ecomDbTableCount == 0) {
installDatabase(updateEcomDb, languages, updatedTenant);
} else {
updateDatabase(updateEcomDb, languages, updatedTenant);
}
storageService.updateTenantFolderStructure(updatedTenant);
} else {
throw new TenantManagerException(
ApiMessageConstants.M_TENANT_PROVISION_ERROR,
ApiMessageConstants.C_TENANT_PROVISION_ERROR);
}
return updatedTenant;
}
private Tenant saveExistingTenant(Tenant tenant) {
tenant.setStatus(TenantStatusEnum.INPROGRESS);
tenant.setMessage(ApiMessageConstants.M_DATABASE_UPDATE_INPROGRESS);
String reason = ApiMessageConstants.R_UPDATE_TENANT;
return saveTenantWithLog(tenant, reason);
}
In application property, you defined 1-1 relation like:
#OneToOne
#JoinColumn(name = "property_group_id")
private ApplicationPropertyGroup applicationPropertyGroup;
#OneToOne
#JoinColumn(name = "property_type_id")
private ApplicationPropertyType applicationPropertyType;
While you have not defined the same relation (note it should work bidirectionally i.e. say for e.g. if you as a person related to an employee id, then employee id is related to you as a person well) in individual property ApplicationPropertyGroup and ApplicationPropertyType.
You should add the same 1-1 relation in ApplicationPropertyGroup and ApplicationPropertyType with ApplicationProperty.

Categories

Resources