Hibernate OneToOne relationship - java

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.

Related

org.springframework.orm.jpa.JpaSystemException: Error accessing field by reflection for persistent property

I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I canĀ“t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter

Foreign key not saving in child table in a One-to-many relationship

I am developing an REST API application using spring boot and is struck up with the One to Many mapping while using mappedBy property.
I have User class and Usermeata class, a user can have more than one usermeta.
While the program successfully save the foreign while using JoinColumn, I want to know what mistake I am committing while using mappedby.
Here is my code:
User Entity class:
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userId;
#Column(unique=true)
private String username;
#Column(unique=true)
private String emailId;
private String password;
private String firstName;
private String lastName;
private String phoneNo;
#OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="user")
// #JoinColumn(name="user_id")
private List<UserMeta> userMetaList=new ArrayList();
public List<UserMeta> getUserMetaList() {
return userMetaList;
}
public void setUserMetaList(List<UserMeta> userMetaList) {
this.userMetaList = userMetaList;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
UserMeta class:
#Entity
public class UserMeta {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userMetaId;
#ManyToOne
#JoinColumn(name="user_id")
private User user;
private String _key;
private String _value;
public Long getUserMetaId() {
return userMetaId;
}
public void setUserMetaId(Long userMetaId) {
this.userMetaId = userMetaId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String get_key() {
return _key;
}
public void set_key(String _key) {
this._key = _key;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
}
UserService.class
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User getUser(Long userId) {
return userRepository.getOne(userId);
}
public List<User> getAllUser() {
return userRepository.findAll();
}
public User addUser(User user) {
return userRepository.save(user);
}
public void removeUser(User user) {
userRepository.delete(user);
}
public void updateUser(User user) {
userRepository.save(user);
}
}
POST request:
{
"username":"myusername",
"emailId":"myemailid#gmail.com1",
"password":"2323#123",
"firstName":"myfname",
"lastName":"mlname",
"phoneNo":"000000",
"userMetaList":[
{
"_key":"api_key",
"_value":"api_key_value"
},
{
"_key":"prop1",
"_value":"val1"
}
]
}
Now the tables are created and updated with the values, however the column user_id in the table usermeta is always null..

get data in json format between two mapping classes

I have mapping with class admin and class role I want to show the data od admin class in Json format but I have error Http 500 because this is a mapping between class admin and role how can I do this?
this is my class Admin
#Entity
public class Admin implements Serializable {
#Id
#GeneratedValue
private int idAdmin;
private String email;
private String cin;
private String nom;
private String prenom;
private String loginAdmin;
private String adresse;
private Long tele;
private String motPasse;
private boolean actived;
#ManyToOne
#JoinColumn(name = "idRole")
private Role role;
public Admin() {
super();
}
public int getIdAdmin() {
return idAdmin;
}
public void setIdAdmin(int idAdmin) {
this.idAdmin = idAdmin;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMotPasse() {
return motPasse;
}
public void setMotPasse(String motPasse) {
this.motPasse = motPasse;
}
public boolean isActived() {
return actived;
}
public void setActived(boolean actived) {
this.actived = actived;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getLoginAdmin() {
return loginAdmin;
}
public void setLoginAdmin(String loginAdmin) {
this.loginAdmin = loginAdmin;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Long getTele() {
return tele;
}
public void setTele(Long tele) {
this.tele = tele;
}
}
And this is my role class
#Entity
public class Role implements Serializable {
#Id
#GeneratedValue
private Long idRole;
private String roleName;
#OneToMany(mappedBy = "role")
private List<Admin> admin;
public Role() {
super();
}
public Long getIdRole() {
return idRole;
}
public void setIdRole(Long idRole) {
this.idRole = idRole;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setAdmin(List<Admin> admin) {
this.admin = admin;
}
public List<Admin> getAdmin() {
return admin;
}
}
And this is my function in controller to show the data in json format
#RequestMapping(value =" /jsonPosts", method = RequestMethod.GET,produces =
"application/json")
#ResponseBody
public List<Admin> generateJSONPosts() {
return adminService.selectAll();
}
The problem is the mapping between role and admin

Hibernate Automatically load relationships

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;

Strange mysql retrieve with hibernate criteria

In a web-service i have the following function which retreives some infos of a doctor and his patient based on patient's phone:
public String findDoctorOfPatient(String phone) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Criteria query = session.createCriteria(doctor.class);
query.createCriteria("patients", "p");
query.add(Restrictions.eq("p.phone", phone));
List<doctor> doctorList = (ArrayList<doctor>) query.list();
session.getTransaction().commit();
String answear = "";
for (doctor d : doctorList) {
answear = answear.concat("docPhone" + d.getPhone() + "docEmail"
+ d.getEmail() + "patDia"
+ d.getPatients().iterator().next().getDiastolic()
+ "patSys"
+ d.getPatients().iterator().next().getSystolic());
}
if (doctorList.isEmpty()) {
session.close();
factory.close();
return "No Doctor!";
} else {
session.close();
factory.close();
return answear;
}
}
The problem is when i have one patient is ok , but when i add second patient it gives me the details of last patient despite i have set to criteria tha firt's patient phone!
I have 2 tables:
1.doctor(id,username,password,phone,email)
2.patient(id,name,surname,phone,systolic,diastolic,doctorid(FK refers to doctor.id))
I have configured properly the hibernate.cfg.xml.
And i have set the class for doctor and patient:
#Entity
public class doctor {
#Id
private int id;
private String username;
private String password;
private String phone;
private String email;
#OneToMany(targetEntity = patient.class, cascade = CascadeType.ALL, mappedBy = "doctor")
#Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Collection<patient> patients = new ArrayList<patient>();
public Collection<patient> getPatients() {
return patients;
}
public void setPatients(Collection<patient> patients) {
this.patients = patients;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
#Entity
public class patient {
#Id
private int id;
private String name;
private String surname;
private String phone;
private int systolic;
private int diastolic;
#ManyToOne
private doctor doctor;
public doctor getDoctor() {
return doctor;
}
public void setDoctor(doctor doctor) {
this.doctor = doctor;
}
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 getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getSystolic() {
return systolic;
}
public void setSystolic(int systolic) {
this.systolic = systolic;
}
public int getDiastolic() {
return diastolic;
}
public void setDiastolic(int diastolic) {
this.diastolic = diastolic;
}
}
In this web-service the response is always the same (given the mobile number) .
It gives me always the patSys=130 and patDia=80 which are the second's patient info!.Something must be wrong in the webservice but to me all seems ok!
You need to create Criteria object on Patient and no need to obtain transaction here.
Criteria query = session.createCriteria(Patient.class)
.add(Restrictions.eq("phone", phone));
List<Patient> patList = (ArrayList<Patient>) query.list();
String result="";
if(!patList.isEmpty()) {
Patient patient=patList.get(0);
result="Doc Phone : " + patient.getDoctor().getPhone();
}
return result;

Categories