I have an 5 entities, User, Roles, Permissions , UserRoles, PermisssionRoles, how would I construct a JPA class to fetch data using pivot tablesenter image description here
public class Roles implements Serializable {
// #OneToMany(mappedBy = "role_id")
// private Collection permissionRoleCollection;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "name")
private String name;
#Size(max = 50)
#Column(name = "code")
private String code;
#Size(max = 255)
#Column(name = "brief")
private String brief;
#Size(max = 8)
#Column(name = "status")
private String status;
#Basic(optional = false)
#NotNull
#Column(name = "date_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
#Column(name = "date_updated")
#Temporal(TemporalType.TIMESTAMP)
private Date dateUpdated;
#JoinColumn(name = "created_by", referencedColumnName = "id")
#ManyToOne
private User createdBy;
#JoinColumn(name = "updated_by", referencedColumnName = "id")
#ManyToOne
private User updatedBy;
#ManyToOne
#JoinTable(name = "permission_role",
joinColumns = #JoinColumn(name = "userid",
referencedColumnName = "userid"),
inverseJoinColumns = #JoinColumn(name = "groupid",
referencedColumnName = "groupid")
)
private Collection<PermissionRole> permissionRoles;
public Roles() {
}
public Roles(Integer id) {
this.id = id;
}
public Roles(Integer id, Date dateCreated) {
this.id = id;
this.dateCreated = dateCreated;
}
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public User getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Roles)) {
return false;
}
Roles other = (Roles) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
#Override
public String toString() {
return "myproperty.v1.db._entities.Roles[ id=" + id + " ]";
}
}
I suppose that you would like to have many to many relations between user and role and also between role and privileges. If you will declare a #ManyToMany annotation, hibernate will know to create an intermediary table...
Check this
Also you could create programmatically the "inner" table and annotate #OneToMany from user to inner and #OneToMany from Role to inner and the same with privileges
Related
I have small project with Spring Data, MVC and Web Flow. Also I have 2 entities that I use in Spring Web Flow, so they MUST implement Serializable interface, but I noticed that Hibernate doesn't create tables, that implement it, for proving it I just copied my entity, removed "implements Serializable" created new class and pasted the entity code there, the new table was created. How it works ? How to create table from entity that implement Serializable, is it possible at all ?
The entities code:
#Table(name = "users")
#Entity
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idUsers")
private int id;
#Column(name = "login")
#Size(min = 3, max = 15,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
private String login;
#Size(min = 6, max = 21,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
#Column(name = "password")
private String password;
#NotNull(message = "Не може бути пустим!")
#Column(name = "email")
private String email;
#Column(name = "photo")
private String path;
#Column(name = "about")
private String about;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<CommentsToBook> commentsToBooks;
public Set<CommentsToBook> getCommentsToBooks() {
return commentsToBooks;
}
public void setCommentsToBooks(Set<CommentsToBook> commentsToBooks) {
this.commentsToBooks = commentsToBooks;
}
public Set<BookOrder> getOrders() {
return orders;
}
public void setOrders(Set<BookOrder> orders) {
this.orders = orders;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<BookOrder> orders;
public String getPath() {
return path;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public void setPath(String path) {
this.path = path;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
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;
}
}
And the second one:
#Entity
#Table(name = "booook_order")
public class BookOrder implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "bank_card")
private String bankCardId;
#Column(name = "user_name")
private String custName;
public User getUser() {
return user;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "book", joinColumns = {
#JoinColumn(name = "id")
},inverseJoinColumns = {#JoinColumn(name = "idlibrary")})
private Set<Book> booksList;
#Column(name ="novaposhta-vid")
private String NPVid;
public String getNPVid() {
return NPVid;
}
public void setNPVid(String NPVid) {
this.NPVid = NPVid;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "city")
private String city;
public void setUser(User user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(name = "idUsers")
private User user;
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Book> getBooksList() {
return booksList;
}
public void setBooksList(Set<Book> booksList) {
this.booksList = booksList;
}
public String getBankCardId() {
return bankCardId;
}
public void setBankCardId(String bankCardId) {
this.bankCardId = bankCardId;
}
}
I'm starting from scratch a new project and i got this problem which i cannot solve. I have three entities, and they all have a manytomany relationship with each other. There is the Cluster:
#Entity
#Component
#Table(name = "clusterEntity")
public class Cluster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
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;
}
#ManyToMany
#JoinTable(name="cluster_user",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_cluster;
#ManyToMany
#JoinTable(name="cluster_sito",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"))
private List<Sito> sitos;
#Override
public String toString() {
return "Cluster{" +
"id=" + id +
", name='" + name +
", users='" + users_cluster.toString() +
'}';
}
}
This is the User:
#Entity
#Component
#Table(name = "userEntity")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password_hash", nullable = false)
private String passwordHash;
#Column(name = "role", nullable = false)
#Enumerated(EnumType.STRING)
private Role role;
#Column(name = "G1", nullable = true)
private String G1;
#Column(name = "G2", nullable = true)
private String G2;
#Column(name = "G3", nullable = true)
private String G3;
#Column(name = "G4", nullable = true)
private String G4;
#Column(name = "G5", nullable = true)
private String G5;
#Column(name = "G6", nullable = true)
private String G6;
#Column (name = "access_token", nullable = true)
private String access_token;
#Column (name = "refresh_token", nullable = true)
private String refresh_token;
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getG1() {
return G1;
}
public void setG1(String g1) {
G1 = g1;
}
public String getG2() {
return G2;
}
public void setG2(String g2) {
G2 = g2;
}
public String getG3() {
return G3;
}
public void setG3(String g3) {
G3 = g3;
}
public String getG4() {
return G4;
}
public void setG4(String g4) {
G4 = g4;
}
public String getG5() {
return G5;
}
public void setG5(String g5) {
G5 = g5;
}
public String getG6() {
return G6;
}
public void setG6(String g6) {
G6 = g6;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
#ManyToMany(mappedBy="users_cluster")
private List<User> users_cluster;
#ManyToMany(mappedBy="users_sito")
private List<User> users_sito;
public User(){}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email.replaceFirst("#.*", "#***") +
", passwordHash='" + passwordHash.substring(0, 10) +
", role=" + role +
'}';
}
}
This is the Sito:
#Entity
#Component
#Table(name = "sitoEntity")
public class Sito {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
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;
}
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_sito;
#Override
public String toString() {
return "Sito{" +
"id=" + id +
", name='" + name+
", users='" + users_sito.toString()+
'}';
}
}
When i try compiling with maven i get the following error about mappedBY, as if it was written on both side of the relation, but in fact it is written only on one side:
Caused by: org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: User.users_cluster
Anyone has any ideaof what am i doing wrong?
Clustor
As far as I can see the Cluster entity is annotated correctly except some kine of naming convention. Instead of
private List<User> users_cluster;
I would recommend using
private List<User> users;
The list contains users so it should be named to reflect that; good naming is the best documentation, (imo).
User
This entity seems to be correctly annotated but the references are wrong as they are self referencing. So the entity should be modified as follows if you want to create a many-to-many relationship between the thre entities:
public class User {
// ...
#ManyToMany(mappedBy="users")
private List<Cluster> clusters;
#ManyToMany(mappedBy="users")
private List<Sito> sitos;
// getters + setters
}
Sito
Here too I made a small modification as follows:
public class Sito {
// ...
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users;
#ManyToMany(mappedBy = "sitos")
private List<Cluster> clusters;
// getters + setters
}
Now your three entities should be related to each other as you desired.
I need to save the child table values without retrieve the values.
POJO Class:
public class User {
private String firstName;
#Id
#SequenceGenerator(name = "userID", sequenceName = "userID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
#Column(name = "id")
private Long id;
private String lastName;
private Integer passwordReset;
#Column(name = "useremail", nullable = false, unique = true)
#Email
#NotEmpty
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<WashingOrder> orderList;
#Column(unique = true)
#NotEmpty(message = "{username}")
private String username;
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setId(Long id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPasswordReset() {
return passwordReset;
}
public void setPasswordReset(Integer passwordReset) {
this.passwordReset = passwordReset;
}
public List<WashingOrder> getOrderList() {
return orderList;
}
public void setOrderList(List<WashingOrder> orderList) {
this.orderList = orderList;
}
}
public class WashingOrder {
#Id
#SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
#Column(name = "orderNo")
private Long orderNo;
#Column(name = "totalClothes", nullable = false)
#NotNull
private Integer totalClothes;
#Column(name = "mensCloth", nullable = true)
private Integer mensCloth;
#Column(name = "womensCloth", nullable = true)
private Integer womensCloth;
#Column(name = "otherCloth", nullable = true)
private Integer otherClothes;
#Column(name = "deliveryDate", nullable = true)
/* #DateTimeFormat(pattern = "yyyy-mm-dd") */
private Date deliveryDate;
#Column(name = "status", nullable = true)
private String orderStatus;
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getTotalClothes() {
return totalClothes;
}
public void setTotalClothes(Integer totalClothes) {
this.totalClothes = totalClothes;
}
public Integer getMensCloth() {
return mensCloth;
}
public void setMensCloth(Integer mensCloth) {
this.mensCloth = mensCloth;
}
public Integer getWomensCloth() {
return womensCloth;
}
public void setWomensCloth(Integer womensCloth) {
this.womensCloth = womensCloth;
}
public Integer getOtherClothes() {
return otherClothes;
}
public void setOtherClothes(Integer otherClothes) {
this.otherClothes = otherClothes;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
Implementation:
Session session = sessionFactory.getCurrentSession();
long id = 1;
Query query = session.createQuery("from user where id =" + id);
User emp6 = (User) session.load(User.class, new Long(1));
User user = (User) query.uniqueResult();
List<WashingOrder> washingOrder = user.getOrderList();
washingOrder.add(order);
user.setOrderList(washingOrder);
session.save(user);
Long orderID = (long) 1;
return orderID;
Here if you check I am getting the order list first (user.getOrderList()) and then I am adding the new list and saving the user.
But I want to save the new order list of the user without retrieve the previous order list.
There is any possibility for the adding new order data without retrieve the previous order list of the particular user.
You need to change a mapping
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<WashingOrder> orderList;
}
public class WashingOrder {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, 1L);
WashingOrder order = new WashingOrder();
order.setUser(user);
session.save(order);
You can try to use a fake User instead of loading
WashingOrder order = new WashingOrder();
order.setUser(new User(1L));
session.save(order);
I searched lot. But can't find solution for my case. i want create hibernate criteria for following query.
SELECT * FROM patient as p1 LEFT OUTER JOIN (SELECT * FROM patient_caller_admin_map WHERE caller_admin_id='1') as pca ON p1.patient_id=pca.patient_id;
i went through the DetachedCriteria , Criteria and created the following things. But don't know how to use LEFT_JOIN by joining both.
DetachedCriteria inner=DetachedCriteria.forClass(PatientCallerAdminMap.class, "patientCallerAdmin");
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
PatientCallerAdminMap Entity:
/**
* PatientCallerAdminMap generated by hbm2java
*/
#Entity
#Table(name = "patient_caller_admin_map", catalog = "test")
public class PatientCallerAdminMap implements java.io.Serializable {
private PatientCallerAdminMapId id;
private CallerAdmin callerAdmin;
private Caller caller;
private Patient patient;
private String notes;
private Integer isArchived;
private Integer patientStatus;
private Set<CallLog> callLogs = new HashSet<CallLog>(0);
private Set<CallLog> callLogs_1 = new HashSet<CallLog>(0);
public PatientCallerAdminMap() {
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Patient patient) {
this.id = id;
this.callerAdmin = callerAdmin;
this.patient = patient;
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Caller caller, Patient patient,
String notes, Integer isArchived, Integer patientStatus,
Set<CallLog> callLogs, Set<CallLog> callLogs_1) {
this.id = id;
this.callerAdmin = callerAdmin;
this.caller = caller;
this.patient = patient;
this.notes = notes;
this.isArchived = isArchived;
this.patientStatus = patientStatus;
this.callLogs = callLogs;
this.callLogs_1 = callLogs_1;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "patientId", column = #Column(name = "patient_id", nullable = false)),
#AttributeOverride(name = "callerAdminId", column = #Column(name = "caller_admin_id", nullable = false)) })
public PatientCallerAdminMapId getId() {
return this.id;
}
public void setId(PatientCallerAdminMapId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_admin_id", nullable = false, insertable = false, updatable = false)
public CallerAdmin getCallerAdmin() {
return this.callerAdmin;
}
public void setCallerAdmin(CallerAdmin callerAdmin) {
this.callerAdmin = callerAdmin;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_id")
public Caller getCaller() {
return this.caller;
}
public void setCaller(Caller caller) {
this.caller = caller;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, insertable = false, updatable = false)
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
#Column(name = "notes", length = 600)
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Column(name = "is_archived")
public Integer getIsArchived() {
return this.isArchived;
}
public void setIsArchived(Integer isArchived) {
this.isArchived = isArchived;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs() {
return this.callLogs;
}
public void setCallLogs(Set<CallLog> callLogs) {
this.callLogs = callLogs;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs_1() {
return this.callLogs_1;
}
public void setCallLogs_1(Set<CallLog> callLogs_1) {
this.callLogs_1 = callLogs_1;
}
}
Patient Entity Class:
#Entity
#Table(name = "patient", catalog = "test")
public class Patient implements java.io.Serializable {
private String patientId;
private String addedDate;
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String phoneNumber;
private Integer tier;
private Integer patientStatus;
private Integer status;
private Set<PatientCallerAdminMap> patientCallerAdminMaps = new HashSet<PatientCallerAdminMap>(
0);
public Patient() {
}
public Patient(String patientId) {
this.patientId = patientId;
}
public Patient(String patientId,String addedDate, String timeOfCrash,
String name, String dateOfBirth, String gender,
String address,
String phoneNumber,Integer tier, Integer patientStatus,
Integer status,
Set<PatientCallerAdminMap> patientCallerAdminMaps,
) {
this.patientId = patientId;
this.addedDate = addedDate;
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.phoneNumber = phoneNumber;
this.tier=tier;
this.patientStatus = patientStatus;
this.status = status;
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
#Id
#Column(name = "patient_id", unique = true, nullable = false)
public String getPatientId() {
return this.patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
#Column(name = "added_date", length = 45)
public String getAddedDate() {
return addedDate;
}
public void setAddedDate(String addedDate) {
this.addedDate = addedDate;
}
#Column(name = "name", length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "date_of_birth", length = 45)
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "gender", length = 5)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name = "address", length = 200)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "phone_number", length = 20)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "tier")
public Integer getTier() {
return this.tier;
}
public void setTier(Integer tier) {
this.tier = tier;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
public Set<PatientCallerAdminMap> getPatientCallerAdminMaps() {
return this.patientCallerAdminMaps;
}
public void setPatientCallerAdminMaps(
Set<PatientCallerAdminMap> patientCallerAdminMaps) {
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
}
Please help to solve this.
Maybe you can achieve this without using subquery so the query become simpler :
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
cr2=cr1.createCriteria("patientCallerAdminMaps ",CriteriaSpecification.LEFT_JOIN);
cr3= cr2.createCriteria("callerAdmin",CriteriaSpecification.LEFT_JOIN);
cr3.add(Restrictions.eq("id", "1"));
For the "select *" you can't do it with criteria. This criteria will return a list of Patient entity.
If really want * you will have to add alias on subcriteria and use Projection to select explicitly the fields that you want
How to join newMap detals in custMap.
Map<String, Customer> custMap= new HashMap<String,Customer>();
Map<String, DoCustomer> newMap= new HashMap<String,DoCustomer>();
for (Map.Entry<String, DoCustomer> cust: newMap.entrySet()) {
custMap.put(cust.getKey(),cust.getValue());
}
public class DoCustomer {
private Long id;
private String custName;
private String description;
private String status;
private List<DoCustomerBranch> doCustomerBranch=new ArrayList<DoCustomerBranch>
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
getter/setters of doCustomerBranch
}
#Entity
#Table(name = "CUSTOMER")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String custName;
private String description;
private String createdBy;
private Date createdOn;
private String updatedBy;
private Date updatedOn;
private Set<CustomerBranch> customerBranch=new HashSet<CustomerBranch>
#Id
#GeneratedValue(generator = "CUSTOMER_SEQ")
#SequenceGenerator(name = "CUSTOMER_SEQ", sequenceName = "CUSTOMERN_SEQ", allocationSize = 1)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "CUST_NAME",nullable=false)
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "CREATED_BY", length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name = "UPDATED_BY", length = 50)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON")
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "customer")
public Set<CustomerBranch> getCustomerBranch() {
return customerBranch;
}
public void setCustomerBranch(Set<CustomerBranch> customerBranch) {
this.customerBranch = customerBranch;
}
}
CustomerBranch
#Entity
#Table(name = "CUSTOMER_BRANCH")
public class CustomerBranch implements Serializable{
#Id
#GeneratedValue(generator = "CUSTOMER_BRANCH_SEQ")
#SequenceGenerator(name = "CUSTOMER_BRANCH_SEQ", sequenceName = "CUSTOMER_BRANCH_SEQ", allocationSize = 1)
#Column(name = "ID")
private Long id;
private String branchName;
private String branchAddress;
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "BRANCH_NAME",nullable=false)
public String getBranchName() {
return branchName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBEE_CUSTOMER")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
The problem with your code is that you want to put a DoCustomer in a Customer container. It only works if DoCustomer is a subclass of Customer.
Edit 1: You could use BeanUtils to convert a DoCustomer into a Customer. Here is a good tutorial.
Do you mean:
custMap.putAll(newMap)
As everyone else has pointed out, we need to know what DoCustomer is to be able to help.
But, from what you have given us, I'd suggest casting each DoCustomer to a Customer or, more correctly, making a new Customer from the fields of each DoCustomer.
Something like:
custMap.put(cust.getKey(), new Customer(cust.getValue().getId(), cust.getValue().getCustName(), and so on..));
inside your for loop.
I can see the customer class defined you have provided doesn't have a constructor, so naturally you would have to add one to it