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 :)
Related
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
This is my 1st project in Java/Hibernate.
I m trying to join two tables but even after searching a lot, I couldn't find the proper solution to achieve what i want.
Let me explain you what i have currently.
I have two entities:
#Entity
#Table(name = "admin")
public class AdminLogin {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private String username;
private String password;
private String status;
private String userRole;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
}
#Entity
#Table(name = "user_balance_log")
public class UserBalanceLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int userId;
private int adminId;
private Float balance;
private String balanceType;
private String message;
#Temporal(javax.persistence.TemporalType.DATE)
private Date dateCreated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getAdminId() {
return adminId;
}
public void setAdminId(int adminId) {
this.adminId = adminId;
}
public Float getBalance() {
return balance;
}
public void setBalance(Float balance) {
this.balance = balance;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getBalanceType() {
return balanceType;
}
public void setBalanceType(String balanceType) {
this.balanceType = balanceType;
}
}
I want to join the adminId from User Balance Log Entity to Admin Login Entity.
This is what i have currently.
Session session = this.sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(UserBalanceLog.class, "ubl");
criteria.setProjection(Projections.projectionList().add(Projections.property("balance"),"balance").add(Projections.property("balanceType"),"balanceType").add(Projections.property("message"),"message").add(Projections.property("dateCreated"),"dateCreated"));
criteria.addOrder(Order.desc("id"));
if (parameters.get("userId") != null) {
criteria.add(Restrictions.eq("userId", new Integer(parameters.get("userId"))));
}
if (parameters.get("balanceType") != null) {
criteria.add(Restrictions.eq("balanceType", parameters.get("balanceType")));
}
if (parameters.get("dateCreated") != null) {
criteria.add(Restrictions.eq("dateCreated", parameters.get("dateCreated")));
}
List userBalanceList = criteria.list();
Please guide me.
Thanks
Finally i figured it out myself of course with the help/guidance of #vc73.
This is the updation i had to do in model:
#Entity
#Table(name = "user_balance_log")
public class UserBalanceLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int userId;
#ManyToOne
#JoinColumn(name="adminId")
private AdminLogin adminId;
private Float balance;
private String balanceType;
private String message;
#Temporal(javax.persistence.TemporalType.DATE)
private Date dateCreated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public AdminLogin getAdminId() {
return adminId;
}
public void setAdminId(AdminLogin adminId) {
this.adminId = adminId;
}
public Float getBalance() {
return balance;
}
public void setBalance(Float balance) {
this.balance = balance;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getBalanceType() {
return balanceType;
}
public void setBalanceType(String balanceType) {
this.balanceType = balanceType;
}
}
and in the DAO:
Session session = this.sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(UserBalanceLog.class, "ubl");
criteria.createAlias("ubl.adminId", "a");
criteria.setProjection(Projections.projectionList().add(Projections.property("balance").as("balance")).add(Projections.property("balanceType").as("balanceType")).add(Projections.property("message").as("message")).add(Projections.property("dateCreated").as("dateCreated")).add(Projections.property("a.username").as("username")));
criteria.addOrder(Order.desc("id"));
if (parameters.get("userId") != null) {
criteria.add(Restrictions.eq("userId", new Integer(parameters.get("userId"))));
}
if (parameters.get("balanceType") != null) {
criteria.add(Restrictions.eq("balanceType", parameters.get("balanceType")));
}
if (parameters.get("dateCreated") != null) {
criteria.add(Restrictions.eq("dateCreated", parameters.get("dateCreated")));
}
criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
criteria.setFirstResult(start);
criteria.setMaxResults(Pagination.limitPerPage);
List userBalanceList = criteria.list();
I hope it will help someone else.
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
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;
}
...
}
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.