OneToMany relationship doesn't save foreign key - java

I am doing a OneToMany relationship in a hibernate query. It's working fine but the donorId is not going to the blood table.
Donor Class:
#Entity
#Table(name = "DONOR")
public class Donor {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int donorId;
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;
#OneToMany(mappedBy="donor")
private Set<Blood> blood;
public int getDonorId() {
return donorId;
}
public void setDonorId(int donorId) {
this.donorId = donorId;
}
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 Set<Blood> getBlood() {
return blood;
}
public void setCity(Set<Blood> blood) {
this.blood = blood;
}
}
Blood Class:
#Entity
#Table(name = "BLOOD")
public class Blood {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int bloodId;
private String bloodType;
private int price;
#ManyToOne
#JoinColumn(name="donor_id")
private Donor donor;
public int getBloodId() {
return bloodId;
}
public void setBloodId(int bloodId) {
this.bloodId = bloodId;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Donor getDepartment() {
return donor;
}
public void setDonor(Donor donor) {
this.donor = donor;
}
}
Blood And Donor Object class:
public class BloodDonor {
private Donor donor;
private Blood blood;
public Donor getDonor() {
return donor;
}
public void setDonor(Donor donor) {
this.donor = donor;
}
public Blood getBlood() {
return blood;
}
public void setBlood(Blood blood) {
this.blood = blood;
}
}
BloodService Class:
public class BloodService {
SessionFactory sessionFactory = null;
public BloodDonor addNewBlood(BloodDonor bloodDonor){
try{
Blood blood = new Blood();
Donor donor = new Donor();
blood = (Blood)bloodDonor.getBlood();
donor = (Donor)bloodDonor.getDonor();
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(donor);
session.save(blood);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return bloodDonor;
}
}
Blood Resource:
#Path("blood")
public class BloodResource {
BloodService bloodService = new BloodService();
#Path("new")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public BloodDonor addNewDonor(BloodDonor blood){
return bloodService.addNewBlood(blood);
}
}
Console:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into DONOR (age, city, cnic, contactNumber, country, email, firstName, homeNumber, houseNo, lastName, streetNo, town, donorId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into BLOOD (bloodType, donor_id, price, bloodId) values (?, ?, ?, ?)

First:
Add CascadeType:
#OneToMany(cascade = CascadeType.ALL, mappedBy="donor")
private Set<Blood> blood;
Second:
Your Entities should be interconnected e.g. Donor's Set<Blood> should contain a link to Blood and Blood's field Donor should be set to that Donor instance.
So, lets try to interconnect them:
Session session = sessionFactory.openSession();
session.beginTransaction();
Donor donor = new Donor();
Blood blood = new Blood();
blood.setDonor(donor);
HashSet<Blood> bloods = new HashSet<Blood>();
bloods.add(blood);
donor.setBlood(bloods);
//set some another fields if you want or they are NOT NULL in database
session.save(donor); //blood should be saved automatically due to cascade
session.getTransaction().commit();
session.close();
This should work if everything is alright with your database structure.

Related

Not able to retrive data from Crud Operation in Hibernate

I have a application written in Spring, Hibernate and SpringBoot,
I have 2 entities class with one to many mapping,
Here are my LeadUserDb entity class
#Entity
#Table(name="lead_user_db")
#NamedQuery(name="LeadUserDb.findAll", query="SELECT l FROM LeadUserDb l")
public class LeadUserDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name="branchcode")
private String branchcode;
#Column(name="reporting_level")
private int reportingLevel;
//bi-directional many-to-one association to UserBasicDetailsDb
#ManyToOne
#JoinColumn(name="email_Id")
private UserBasicDetailsDb userBasicDetailsDb;
public LeadUserDb() {
}
public String getBranchcode() {
return this.branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public int getReportingLevel() {
return this.reportingLevel;
}
public void setReportingLevel(int reportingLevel) {
this.reportingLevel = reportingLevel;
}
public UserBasicDetailsDb getUserBasicDetailsDb() {
return this.userBasicDetailsDb;
}
public void setUserBasicDetailsDb(UserBasicDetailsDb userBasicDetailsDb) {
this.userBasicDetailsDb = userBasicDetailsDb;
}
And This is my UserBasicDetailsDb Entity Class
#Entity
#Table(name="user_basic_details_db")
public class UserBasicDetailsDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String email;
private String address;
private String city;
private String dob;
private String mobile;
private String name;
private String pan;
private String pincode;
private String state;
#OneToMany(mappedBy="userBasicDetailsDb")
private List<LeadUserDb> leadUserDbs;
public UserBasicDetailsDb() {
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getDob() {
return this.dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPan() {
return this.pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<LeadUserDb> getLeadUserDbs() {
return this.leadUserDbs;
}
public void setLeadUserDbs(List<LeadUserDb> leadUserDbs) {
this.leadUserDbs = leadUserDbs;
}
public LeadUserDb addLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().add(leadUserDb);
leadUserDb.setUserBasicDetailsDb(this);
return leadUserDb;
}
public LeadUserDb removeLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().remove(leadUserDb);
leadUserDb.setUserBasicDetailsDb(null);
return leadUserDb;
}
what i want to achieve is to create a query like this one
SELECT a.branchcode as branchCode,b.name FROM lead_user_db a
inner join user_basic_details_db b
where b.email = a.email_id and a.reporting_level = 3
here is what I have written my Repository class
public interface GetUserList extends CrudRepository<LeadUserDb, Integer> {
#Query(value = "SELECT a.id, a.branchcode as branchCode,b.name as name,a.reporting_level,a.email_id FROM lead_user_db a\n" +
"inner join user_basic_details_db b\n" +
"where b.email = a.email_id and a.reporting_level = ?1", nativeQuery = true)
List<LeadUserDb> findByReportingLevel(int reportingLevel);
}
and this is how I am calling it
UserBasicDetailsDb details = GetUserList.findByReportingLevel(3);
NOTE
Getting a new error Cannot determine value type from string test#dev.com
I am getting a hell lot of data, and the actual output have only 2 records
My question is how can i fetch the list of user based on reportingLevel
Any help would be appreciated

JPA code not executing further after transaction.commit

Main method
EntityManagerFactory emf=Persistence.createEntityManagerFactory("manager1");
EntityManager em1=emf.createEntityManager();
EntityTransaction entityTransaction=em1.getTransaction();
entityTransaction.begin();
Person persons=JPA_basic_Example.setPerson();//fills all the fields of person
Credential cred=JPA_basic_Example.setCredential();//fills all fields of credentials
System.out.println("check1");
cred.setPerson(persons);
persons.setCredential(cred);
em1.persist(cred);
entityTransaction.commit();
em1.close();
emf.close();
Java Bean Credential oneToone Bidirectional with Person
public class Credential {
#Id
#Column(name ="credentialid")
private int credential_id;
private String UserName;
private String Password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="Personid")
private Person person;
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getCredential_id() {
return credential_id;
}
public void setCredential_id(int credential_id) {
this.credential_id = credential_id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Java Bean Person
#Entity
public class Person {
#Id
#Column(name ="Personid")
private int person_id;
//#Basic(optional = false)
//#Column(name ="Name", unique = true)
private String name;
#ElementCollection
#CollectionTable
List<String> contact=new ArrayList<String>();
private Address address=new Address();
#OneToOne(mappedBy = "person", orphanRemoval = true )
Credential credential ;
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getContact() {
return contact;
}
public void setContact(List<String> contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
}
Output Console
Hibernate:
insert
into
Person
(area, city, pincode, state, name, Personid)
values
(?, ?, ?, ?, ?, ?)
AFter this code stuck and nit moving forward nor showing any exceptions or errors

How to populate foreign key in table Spring + Hibernate + Spring Security

I want make a case, when user is authenticated by Spring Security and then he fill adres form I would like to automatically updated a foreign key column "adres_id" in user table. Please give me a tip how implement this in the most popular way
I how somethig like this
Address Table:
User Table:
Adres
#Entity
#Table(name="adres")
public class Adres {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
#OneToOne(mappedBy ="adres")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getStreet() {
return postcode;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
User
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="username", nullable=false)
private String username;
private String password;
private String email;
private Boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
private Adres adres;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
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 int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
AdresDAO
#Repository
#Transactional
public class AdresDAOImpl implements AdresDAO{
#Autowired
SessionFactory sessionFactory;
public void addAdres(Adres adres) {
sessionFactory.getCurrentSession().save(adres);
}
public List<Adres> listAdres() {
return sessionFactory.getCurrentSession().createQuery("from Adres order by id").list();
}
public void removeAdres(int id) {
Adres adres = (Adres) sessionFactory.getCurrentSession().load(
Adres.class, id);
if (null != adres) {
sessionFactory.getCurrentSession().delete(adres);
}
}
public Adres getAdres(int id) {
return (Adres)sessionFactory.getCurrentSession().get(Adres.class, id);
}
public void editAdres(Adres adres) {
sessionFactory.getCurrentSession().update(adres);
}
}
AdresService
#Service
public class AdresServiceImpl implements AdresService{
#Autowired
AdresDAO adresDAO;
#Transactional
public void addAdres(Adres adres) {
adresDAO.addAdres(adres);
}
#Transactional
public void editAdres(Adres adres) {
adresDAO.editAdres(adres);
}
#Transactional
public List<Adres> listAdres() {
return adresDAO.listAdres();
}
#Transactional
public void removeAdres(int id) {
adresDAO.removeAdres(id);
}
#Transactional
public Adres getAdres(int id) {
return adresDAO.getAdres(id);
}
}
User unidirectional relation between User and Address if Address object does not supposed to know about its owner (generally it does not). I would prefer user id in Address table if a User have more than one Address (one-to-many relation).
But for your question you may design like that,
public class User{
...
#OneToOne(CascadeType.REMOVE)//this is for to remove address when user is removed
#JoinColumn(name="HOME_ADDRESS_ID")
private Address address;
...
}
and
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
//no user object here
public int getId() {
return id;
}
...
}

Could not resolve property - Hibernate

I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}

HTTP Status 500 - Internal Server Error at saving hibernate OneTOMany reletionship

I am doing a OneToMany relationship the data is saving correctly but apache tomcat server giving error HTTP Status 500 - Internal Server Error.
Donor Class:
#Entity
public class DonorClass {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int donorId;
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;
#OneToMany(cascade = CascadeType.ALL, mappedBy="donor")
private Set<BloodDonorClass> blood;
public int getDonorId() {
return donorId;
}
public void setDonorId(int donorId) {
this.donorId = donorId;
}
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 Set<BloodDonorClass> getBlood() {
return blood;
}
public void setBlood(Set<BloodDonorClass> blood) {
this.blood = blood;
}|
}
BloodDonorClass Class:
#Entity
public class BloodDonorClass {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int bloodId;
private String bloodType;
private int price;
#ManyToOne
#JoinColumn(name="donor_id")
private DonorClass donor;
public int getBloodId() {
return bloodId;
}
public void setBloodId(int bloodId) {
this.bloodId = bloodId;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public DonorClass getDonor() {
return donor;
}
public void setDonor(DonorClass donor) {
this.donor = donor;
}
}
Blood And Donor Object class:
public class BloodDonorObjectClass {
private DonorClass donor;
private BloodDonorClass blood;
public DonorClass getDonor() {
return donor;
}
public void setDonor(DonorClass donor) {
this.donor = donor;
}
public BloodDonorClass getBlood() {
return blood;
}
public void setBlood(BloodDonorClass blood) {
this.blood = blood;
}
}
BloodDonorClassService Class:
SessionFactory sessionFactory = null;
public BloodDonorObjectClass addNewDonor(BloodDonorObjectClass bloodDonor){
try{
DonorClass donor = new DonorClass();
BloodDonorClass blood = new BloodDonorClass();
blood = (BloodDonorClass)bloodDonor.getBlood();
donor = (DonorClass)bloodDonor.getDonor();
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
blood.setDonor(donor);
HashSet<BloodDonorClass> bloods = new HashSet<BloodDonorClass>();
bloods.add(blood);
donor.setBlood(bloods);
session.save(donor);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return bloodDonor;
}
}
Blood Resource Class:
#Path("bloodresource")
public class BloodResourceNew {
BloodDonorClassService bloodService = new BloodDonorClassService();
#Path("new")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public BloodDonorObjectClass addNew(BloodDonorObjectClass blood){
return bloodService.addNewDonor(blood);
}
}
Console Output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into DonorClass (age, city, cnic, contactNumber, country, email, firstName, homeNumber, houseNo, lastName, streetNo, town, donorId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into BloodDonorClass (bloodType, donor_id, price, bloodId) values (?, ?, ?, ?)
I shall be thankful :)

Categories

Resources