Hibernate Automatically load relationships - java

I have the following Entity classes UserEntity and TicketEntity. A User has many tickets and many tickets can belong to a user. My question is, is there a way to automatically load all the tickets belonging to a pertaining user by using Hibernate or do I have to manually load all the entity relationships from the DB? I think the .load() does this but I'm not quite sure. In my case could I do something like
userEntity.load()
Any help is appreciated, thanks
UserEntity.java
package com.issuetracking.domain;
/**
*/
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.LAZY)
private List<TicketEntity> tickets;
//Getters/Setters
public List<TicketEntity> getTickets() {
return tickets;
}
public void setTickets(List<TicketEntity> tickets) {
this.tickets = tickets;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
TicketEntity.java
package com.issuetracking.domain;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity assigned_to;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
public int getUrgency_id() {
return urgency_id;
}
public void setUrgency_id(int urgency_id) {
this.urgency_id = urgency_id;
}
public UserEntity getBelongs_to() {
return belongs_to;
}
public void setBelongs_to(UserEntity belongs_to) {
this.belongs_to = belongs_to;
}
public UserEntity getAssigned_to() {
return assigned_to;
}
public void setAssigned_to(UserEntity assigned_to) {
this.assigned_to = assigned_to;
}
}

A User has many tickets and many tickets can belong to a user.
In this case relationship should be ManyToMany
My question is, is there a way to automatically load all the tickets belonging to a pertaining user
Use EAGER FetchType instead of LAZY , Like
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;

Related

JPA mapping table could not delete

I have entity Account, Role, AccountRole.
#Entity
public class Account {
#Id
private String loingId;
private String username;
private String password;
private String email;
private boolean enable;
#OneToMany(mappedBy = "account", orphanRemoval = true)
private List<AccountRole> accountRoles = new ArrayList<>();
public String getLoingId() {
return loingId;
}
public void setLoingId(String loingId) {
this.loingId = loingId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
public void addAccountRoles(AccountRole accountRoles) {
if (this.accountRoles == null){
this.accountRoles = new ArrayList<>();
}
this.accountRoles.add(accountRoles);
accountRoles.setAccount(this);
}
public void removeAccountRoles(){
this.accountRoles = null;
}
}
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
private boolean enable;
#OneToMany(mappedBy = "role")
private List<AccountRole> accountRoles = new ArrayList<>();
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
}
#Entity
public class AccountRole implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name = "account_id")
private Account account;
#ManyToOne
#JoinColumn(name = "role_id")
private Role role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
To create account with role is OK.
There is a problem in update.
I want to delete the existing Role and only add the changed Role when the Role of the Account is changed. However, existing data is not deleted from the AccoutRole table.
How can I solve the problem?
springBootVersion = '1.5.3.RELEASE'
java 1.8
gradle dependencies
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime ('org.mariadb.jdbc:mariadb-java-client')
}
A couple of ideas:
Thought 1: Try using cascade
Yes, JPA 2.0 should handle this with orphanRemoval = true, but let's just see if that works. I think that it is not because you aren't creating an orphan here. The mapping is still "valid" from a relational perspective.
#OneToMany(mappedBy = "account", cascade = CascadeType.ALL) // or CascadeType.REMOVE
private List<AccountRole> accountRoles = new ArrayList<>();
Thought 2: Try setting the account roles to an empty hashmap instead first:
account.setAccountRoles(new HashMap<AccountRole>());
account.getAccountRoles().add(accountRole);;

Hibernate OneToOne relationship

I have 3 classes Appointment,Patient and Doctor.Appointment have 1to1 reletionship with both Patient and Doctor.
When i insert a appointment object in database everytime the new patient and doctor object is also inserted in the database.
Patient Class:
#Entity
#Table(name = "Patient")
public class Patient {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int patientId;
private String firstName;
private String lastName;
private int age;
private String cnic;
private String contactNumber;
private String homeNumber;
private String country;
private String city;
private String town;
private String streetNo;
private String houseNo;
private String email;
private String username;
private String password;
public int getPatientId() {
return patientId;
}
public void setPatientId(int patientId) {
this.patientId = patientId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCnic() {
return cnic;
}
public void setCnic(String cnic) {
this.cnic = cnic;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId(){
return patientId;
}
public Patient getPatient(){
return this;
}
}
Doctor Class :
#Entity
#Table(name = "Doctor")
public class Doctor extends Users {
private String specialization;
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
this.specialization = specialization;
}
}
Appointment Class:
#Entity
public class AppointmentClass {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int appointmentId;
private int appointmentDay;
private int appointmentTime;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Patient patient;
#OneToOne (cascade=CascadeType.ALL,fetch = FetchType.EAGER)
private Doctor doctor;
public int getAppointmentId() {
return appointmentId;
}
public void setAppointmentId(int appointmentId) {
this.appointmentId = appointmentId;
}
public int getAppointmentDay() {
return appointmentDay;
}
public void setAppointmentDay(int appointmentDay) {
this.appointmentDay = appointmentDay;
}
public int getAppointmentTime() {
return appointmentTime;
}
public void setAppointmentTime(int appointmentTime) {
this.appointmentTime = appointmentTime;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
}
Service Class:
public class AppointmentPatientService {
private SessionFactory sessionFactory = null;
public AppoinmentPatient createNewAppointment(AppoinmentPatient appointment){
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Patient patient = new Patient();
Doctor doctor = new Doctor();
patient = (Patient)(appointment).getPatient();
AppointmentClass appointment1 = new AppointmentClass();
appointment1 = (AppointmentClass)(appointment).getAppointment();
doctor = (Doctor)appointment.getDoctor();
appointment1.setPatient(patient);
appointment1.setDoctor(doctor);
session.beginTransaction();
session.save(appointment1);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return appointment;
}
}
Is there any way that when i save the appointment object the new objects of patient and doctor not save to the database.
I shall be thankful :)
I think your relationship type should not be OneToOne from neither the doctor or the patient, because one doctor can have many appointments and one patient can have many appointments. So it should be OneToMany from both sides, in which case a new doctor and a new patient won't be created for each new appointment if you supply the appointment with correct existing doctor and patient ID-s.
In the class AppointmentClass, change the cascade settings.
You can use cascade=CascadeType.NONE, This will make sure that the associated Patient and Doctor objects are not saved to database.
You can see all other values of CascadeType to find the right choice for you.

Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)

I have spring application everytime I run and I try to login I got the following excpetion after login
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethod$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj:19)
at com.emc.fleet.domain.User.entityManager(User.java:1)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethodDispatch1$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj)
at com.emc.fleet.domain.User_Roo_Finder.ajc$interMethod$com_emc_fleet_domain_User_Roo_Finder$com_emc_fleet_domain_User$findUsersByUserIdEquals(User_Roo_Finder.aj:47)
at com.emc.fleet.domain.User.findUsersByUserIdEquals(User.java:1)
I have read many STO questions and checked all answers none of them succeded
this is my user class
package com.emc.fleet.domain
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
#RooJavaBean
#RooToString
#RooJpaActiveRecord(finders = { "findUsersByEmailLike", "findUsersByUserIdEquals", "findUsersByCostCenter", "findUsersByDepartmet" })
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#NotNull
private String firstName;
#NotEmpty
#NotNull
private String lastName;
#NotNull
private Long userId;
#Email
#NotNull
private String email;
#NotNull
private String address;
#NotNull
private String district;
private String deskPhone;
#NotEmpty
#NotNull
private String mobile;
#NotEmpty
#NotNull
private String password;
#Transient
private String retypePassword;
#OneToOne
private Department departmet;
#OneToOne
#JoinColumn(name = "cost_center")
private CostCenter costCenter;
private String managerName;
private boolean enabled = true;
#Enumerated(EnumType.STRING)
private Roles role = Roles.ROLE_USER;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getDeskPhone() {
return deskPhone;
}
public void setDeskPhone(String deskPhone) {
this.deskPhone = deskPhone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRetypePassword() {
return retypePassword;
}
public void setRetypePassword(String retypePassword) {
this.retypePassword = retypePassword;
}
public Department getDepartmet() {
return departmet;
}
public void setDepartmet(Department departmet) {
this.departmet = departmet;
}
public CostCenter getCostCenter() {
return costCenter;
}
public void setCostCenter(CostCenter costCenter) {
this.costCenter = costCenter;
}
public String getManagerName() {
return managerName;
}
public void setManagerName(String managerName) {
this.managerName = managerName;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Roles getRole() {
return role;
}
public void setRole(Roles role) {
this.role = role;
}
#Override
public String toString() {
return getEmail() + " - " + getUserId();
}
}
and this the user_Roo_Configurable file
package com.emc.fleet.domain;
import com.emc.fleet.domain.User;
import org.springframework.beans.factory.annotation.Configurable;
privileged aspect User_Roo_Configurable {
declare #type: User: #Configurable;
}
any clue ?

hibernate gives two rows the same instead of two distinct rows

I have a user dao
#Entity
#Table(name="EBIGUSERTIM")
public class EbigUser {
private String id;
private Integer source;
private String entryscheme;
private String fullName;
private String email;
private Long flags;
private String status;
private String createdBy;
private Date createdStamp;
private String modifiedBy;
private Date modifiedStamp;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
public void setSource(Integer source) {
this.source = source;
}
#Column(name="ENTRYSCHEME")
public String getEntryscheme() {
return entryscheme;
}
public void setEntryscheme(String entryscheme) {
this.entryscheme = entryscheme;
}
#Column(name="FULLNAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="FLAGS")
public Long getFlags() {
return flags;
}
public void setFlags(Long flags) {
this.flags = flags;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="CREATEDBY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name="CREATEDSTAMP")
public Date getCreatedStamp() {
return createdStamp;
}
public void setCreatedStamp(Date createdStamp) {
this.createdStamp = createdStamp;
}
#Column(name="MODIFIEDBY")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
#Column(name="MODIFIEDSTAMP")
public Date getModifiedStamp() {
return modifiedStamp;
}
public void setModifiedStamp(Date modifiedStamp) {
this.modifiedStamp = modifiedStamp;
}
i am selecting 2 rows out of the db. The sql works
select * from ebigusertim where id='blah'
It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object.
Criteria userCriteria = session.createCriteria(EbigUser.class);
userCriteria.add(Restrictions.eq("id", id));
userlist = userCriteria.list();
Why are you defining two id columns(both id and source are mapped with annotation #Id)?
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
Please remove one if it is by mistake. If both together make composite key, map them accordingly e.g.
#Embeddable
public class UserPK implements Serializable {
#Column(name = "ID", nullable = false)
private String id;
#Column(name = "SOURCE", nullable = false)
private Integer source;
.....
.....
}
Use this new class in you original class as Id as below:
#EmbeddedId
private UserPK userPK;
Hope this helps.

how to write java hibernate many to many relationship retrieving query

I have two tables as specified below. I want to write a query to get all the contacts of a particular group.(According to group id). Please help me.
Thanks in advance.
1.this contacts table , which has many has many to many relationship with contact groups table.
#Entity
#Table(name="contacts")
public class Contacts implements Serializable {
private Long id;
private String userId;
private String emailId;
private Set<ContactGroups> contactGroups;
private String firstName;
private String lastName;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="user_id")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name="email_id")
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#ManyToMany(targetEntity = ContactGroups.class, cascade = {CascadeType.ALL},fetch=FetchType.EAGER)
#JoinTable(name="contact_group",
joinColumns=#JoinColumn(name="c_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="g_id", referencedColumnName="id")
)
public Set<ContactGroups> getContactGroups() {
return contactGroups;
}
public void setContactGroups(Set<ContactGroups> contactGroups) {
this.contactGroups = contactGroups;
}
#Column(name="first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
#Entity
#Table(name="contact_groups")
public class ContactGroups implements Serializable{
private Long id;
private String groupName;
private String userName;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name="group_name")
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
select c from Contacts c
inner join c.contactGroups group
where group.id = :groupId
But everything would be simpler if
you named your entities ContactGroup and Contact (without the final s)
you mapped the association as a bidirectional one. It would allow getting the ContactGroup by ID, and just call getContacts() to get its contacts.
select c from Contacts c, ContactGroups g
where c.contactGroups.id = g.id
and g.id = 'whatever id you want'

Categories