Exception in webapp,i.e. org.apache.jasper.JasperException - java

I have built a dao layer which connects with a derby db with the use of jdbctemplate.
The insert query works fine but when I try to select all rows from the database, the webapp gives me this error:
org.apache.jasper.JasperException: An exception occurred processing
JSP page /WEB-INF/jsp/DisplayEmployee.jsp at line 26
23: 24: 25: 26: ${temp.FirstName} 27:
${temp.MiddleName} 28: ${temp.LastName}
29: ${temp.email}
avax.el.PropertyNotFoundException: Property 'FirstName' not found on
type com.user.EmployeeInfo
Code:
DAO:
public class EmployeeDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int insert(EmployeeInfo emp){
String sql = "insert into employee VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
int i=template.update(sql, emp.getFirstName(), emp.getMiddleName(), emp.getLastName(), emp.getEmail(), emp.getGender(), emp.getDob(), emp.getAddress1(), emp.getAddress2(), emp.getEmpID());
return i;
}
public List<EmployeeInfo> retrieveMultipleRowsColumns(){
String sql = "select * from employee";
//return template.queryForList(sql, elementType)
//List<EmployeeInfo> list = template.query(sql,new BeanPropertyRowMapper<EmployeeInfo>(EmployeeInfo.class));
//List<EmployeeInfo> list2 = template.queryForList(sql, EmployeeInfo.class);
List<EmployeeInfo> list3 = template.query(sql, new RowMapper<EmployeeInfo>(){
public EmployeeInfo mapRow(ResultSet rs, int rownumber) throws SQLException {
EmployeeInfo e = new EmployeeInfo();
e.setFirstName(rs.getString(1));
e.setMiddleName(rs.getString(2));
e.setLastName(rs.getString(3));
e.setEmail(rs.getString(4));
e.setGender(rs.getString(5));
e.setDob(rs.getDate(6));
e.setAddress1(rs.getString(7));
e.setAddress2(rs.getString(8));
e.setEmpID(rs.getInt(9));
return e;
}
});
return list3;
}
Controller:
public class EmployeeAddition {
#Autowired
EmployeeDao dao;
#RequestMapping("/addresult")
public ModelAndView addResult(HttpServletRequest req,HttpServletResponse res) {
String fname = req.getParameter("FirstName");
String mname = req.getParameter("MiddleName");
String middlename;
if(mname!="null"&&mname.trim()!=""){
middlename=mname;
}
else
{
middlename="-";
}
String lname = req.getParameter("LastName");
String empid = req.getParameter("empID");
int empID = Integer.parseInt(empid);
String email = req.getParameter("Email");
String gender = req.getParameter("gender");
Date dob = Date.valueOf(req.getParameter("DOB"));
String addr1 = req.getParameter("address1");
String addr2 = req.getParameter("address2");
EmployeeInfo emp = new EmployeeInfo(fname,middlename,lname,email,gender,dob,addr1,addr2,empID);
int ret = dao.insert(emp);
if(ret==0){
return new ModelAndView("EmployeeAddResult","mess","Success");
}
else
{
return new ModelAndView("EmployeeAddResult","mess","hi");
}
}
#RequestMapping("/display")
public ModelAndView viewEmployee(HttpServletRequest req,HttpServletResponse res,ModelMap model) {
List<EmployeeInfo> list=dao.retrieveMultipleRowsColumns();
model.put("list",list);
return new ModelAndView("DisplayEmployee","mess","Welcome "+(String)req.getSession().getAttribute("uname"));
}
}
The jsp where i'm displaying the result:
<div class="right_disp left">
<c:forEach items="${list}" var="temp">
<tr>
<td>${temp.FirstName}</td>
<td>${temp.MiddleName}</td>
<td>${temp.LastName}</td>
<td>${temp.email}</td>
<td>${temp.gender}</td>
<td>${temp.dob}</td>
<td>${temp.Address1}</td>
<td>${temp.Address2}</td>
<td>${temp.empID}</td>
</tr>
</c:forEach>
</div>
The variable name match the original variables of the POJO class but I don't understand why the error for Property not found on the class is coming.
Appreciate any suggestion or help.
Edit:
EmployeeInfo class(POJO)
import java.sql.Date;
public class EmployeeInfo {
String FirstName;
String MiddleName;
String LastName;
String email;
String gender;
Date dob;
String Address1;
String Address2;
int empID;
public EmployeeInfo(){
}
public EmployeeInfo(String firstName, String middleName, String lastName, String email, String gender,
Date dob, String address1, String address2, int empID) {
super();
FirstName = firstName;
MiddleName = middleName;
LastName = lastName;
this.email = email;
this.gender = gender;
this.dob = dob;
Address1 = address1;
Address2 = address2;
this.empID = empID;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getMiddleName() {
return MiddleName;
}
public void setMiddleName(String middleName) {
MiddleName = middleName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getAddress2() {
return Address2;
}
public void setAddress2(String address2) {
Address2 = address2;
}
public int getEmpID() {
return empID;
}
public void setEmpID(int empID) {
this.empID = empID;
}
}

Don't capitalise the first letter of the property names if they follow the bean properties naming convention.
If your getter and setter are named getSomeProperty and setSomeProperty then in a template you should use someProperty not SomeProperty.

Your naming conventions are the issue. try to stick with some convention across the board (for eg: camel casing)
<td>${temp.FirstName}</td>
try updating to
<td>${temp.firstName}</td>

Related

How do i override functions in a Vaadin 12 project? ValueProvider, SelectionListener and ComponentEventListener

This will be quite a bit of code as I don't know what will be important. I was trying to recreated the basic UI Alejandro made in my tutorial session with him a few months ago, substituting a table in my database for the one he used. The errors I'm getting all seem related to overriding Vaadin Flow functions. I know that replaces the behavior of the Super method. IntelliJ opens the relevant Super method when I click on the errors, which I'm assuming it wants me to edit to solve the problem, but I have no idea how to do that.
I was going to paste a link to the code but the forum told me to just place it here.
Customer.java
package com.dbproject.storeui;
import java.time.LocalDate;
public class Customer {
private Long id;
private String lastname;
private String firstname;
private String email;
private String password;
private String phone;
private String street;
private String city;
private String st;
private int zip;
private LocalDate dob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
}
CustomerRepository.java
package com.dbproject.storeui;
import org.apache.ibatis.annotations.*;
import java.util.List;
#Mapper
public interface CustomerMapper {
#Select("SELECT * FROM customer ORDER BY id")
List<Customer> findAll();
#Update("UPDATE customer" +
"SET lastname=#{lastname}, firstname=#{firstname}, email=#{email}, password=#{password}, phone=#{phone}, street=#{street}, city=#{city}, st=${st}, zip=#{zip}, dob=#{dob}" +
"WHERE id=#{id}")
void update(Customer customer);
#Insert("INSERT INTO customer(lastname, firstname, email, password, phone, street, city, st, zip, dob) VALUES(#{lastname}, #{firstname}, #{email}, #{password}, #{phone}, #{street}, #{city}, #{st}, #{zip}, #{dob})")
#Options(useGeneratedKeys = true, keyProperty = "id")
void create(Customer customer);
}
CustomerView.java (the UI class)
package com.dbproject.storeui;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
#Route("")
public class CustomerView extends Composite<VerticalLayout> {
private final CustomerMapper customerMapper;
private Grid<Customer> grid = new Grid<>();
private TextField lastname = new TextField("Last Name");
private TextField firstname = new TextField("First Name");
private Button save = new Button("Save", VaadinIcon.CHECK.create());
private Button create = new Button("New", VaadinIcon.PLUS.create());
private VerticalLayout form = new VerticalLayout(lastname, firstname, save);
private Binder<Customer> binder = new Binder<>(Customer.class);
private Customer customer;
public CustomerView(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
grid.addColumn(Customer::getLastname).setHeader("Last Name");
grid.addColumn(Customer::getFirstname).setHeader("First Name");
grid.addSelectionListener(event -> setCustomer(grid.asSingleSelect().getValue()));
updateGrid();
save.addClickListener(event -> saveClicked());
create.addClickListener(event -> createClicked());
getContent().add(grid, create, form);
binder.bindInstanceFields(this);
binder.setBean(null);
}
private void createClicked() {
grid.asSingleSelect().clear();
setCustomer(new Customer());
}
private void saveClicked() {
binder.readBean(customer);
if (customer.getId() == null) {
customerMapper.create(customer);
} else {
customerMapper.update(customer);
}
updateGrid();
Notification.show("Saved!");
}
private void setCustomer(Customer customer) {
this.customer = customer;
form.setEnabled(customer != null);
binder.setBean(customer);
}
private void updateGrid() {
grid.setItems(customerMapper.findAll());
}
}

Spring MVC form validation does't work for nested complex types

I am implementing a sample Spring MVC Form with Form Validation. I have a complex type Address as bean property for Student form bean. And I have added form validation #NotEmpty for Address bean properties. But the same is not reflecting in the UI. But form validation works for other primitive types of Student form bean.
So, Validation works perfectly for Student form bean but not for nested complex types like Address within Student form bean.
I am trying understand the reason and a fix.
Spring version 4.0+.
Hibernate Validator api:5.2.4
Student POJO:
package com.xyz.form.beans;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.DateNotEmpty;
import com.xyz.validators.ListNotEmpty;
public class Student {
#Size(min = 2, max = 30)
private String firstName;
#Size(min = 2, max = 30)
private String lastName;
#NotEmpty
private String gender;
#DateNotEmpty
#Past
private Date DOB;
private String email;
private String mobileNumber;
#ListNotEmpty
private List<String> courses;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
}
Address POJO:
package com.xyz.form.beans;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.LongNotEmpty;
public class Address {
#NotEmpty
private String houseNo;
#NotEmpty
private String street;
#NotEmpty
private String area;
#NotEmpty
private String city;
#LongNotEmpty
private Long pin;
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getPin() {
return pin;
}
public void setPin(Long pin) {
this.pin = pin;
}
}
Student Controller:
#RequestMapping(value = "/newStudentDetails.do", method = RequestMethod.POST)
public ModelAndView newStudentDetails(
#Valid #ModelAttribute("student") com.xyz.form.beans.Student studentFormBean,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ModelAndView("newStudentPage");
}
Student studentDto = new Student();
studentDto.setFirstName(studentFormBean.getFirstName());
studentDto.setLastName(studentFormBean.getLastName());
studentDto.setGender(studentFormBean.getGender());
studentDto.setDOB(new Date(studentFormBean.getDOB().getTime()));
studentDto.setEmail(studentFormBean.getEmail());
studentDto.setMobileNumber(studentFormBean.getMobileNumber());
StringBuilder sb = new StringBuilder();
sb.append(studentFormBean.getAddress().getHouseNo() + ", ");
sb.append(studentFormBean.getAddress().getStreet() + ", ");
sb.append(studentFormBean.getAddress().getArea() + ", ");
sb.append(studentFormBean.getAddress().getCity() + "-");
sb.append(studentFormBean.getAddress().getPin());
studentDto.setAddress(sb.toString());
studentDto.setCourses(studentFormBean.getCourses());
studentDao.createStudent(studentDto);
ModelAndView mav = new ModelAndView("newStudentSuccess");
return mav;
}
Thanks,
Viswanath
You need to annotate your complex types with #Valid.
This is the reference (which references here)
Hi lets try #ModelAttribute("student") #Valid com.xyz.form.beans.Student studentFormBean in place of #Valid #ModelAttribute("student")
For nested complex types, you have to activate the direct field access. Just like below:
#org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.initDirectFieldAccess();
}

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 :)

OneToMany relationship doesn't save foreign key

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.

Object returns null

Summary:
New to Java, tried looking through other posts but didn't find an answer. I'm learning inheritance and have an AddressBook class extended by a Runner class. When I write a program to test the inheritance I create a Runner object. If I get the first String parameter it returns fine but when I attempt to get the second String parameter it returns null.
Question:
Why is the second parameter returning null?
package Assignment_1;
//Begin Class Definition
public class AddressBook {
// Member variables
private String businessPhone;
private String cellPhone;
private String facebookId;
private String firstName;
private String homeAddress;
private String homePhone;
private String lastName;
private String middleName;
private String personalWebSite;
private String skypeId;
//Constructors
public AddressBook (String firstName, String middleName, String lastName, String homeAddress, String businessPhone, String homePhone, String cellPhone, String skypeId, String facebookId, String personalWebSite) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.businessPhone = businessPhone;
this.homePhone = homePhone;
this.cellPhone = cellPhone;
this.skypeId = skypeId;
this.facebookId = facebookId;
this.personalWebSite = personalWebSite;
}
public AddressBook (String firstName) {
this.firstName = firstName;
}
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
public AddressBook (String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Getters and setters
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getHomeAddress() {
return homeAddress;
}
public String getBusinessPhone() {
return businessPhone;
}
public String getHomePhone() {
return homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public String getSkypeId() {
return skypeId;
}
public String getFacebookId() {
return facebookId;
}
public String getPersonalWebsite() {
return personalWebSite;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public void setBusinessPhone(String businessPhone) {
this.businessPhone = businessPhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public void setSkypeId(String skypeId) {
this.skypeId = skypeId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public void setPersonalWebSite(String personalWebSite) {
this.personalWebSite = personalWebSite;
}
// Public methods
public static void compareNames(String name1, String name2) {
if(name1.equals(name2)) {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names are the same.");
} else {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names appear to be different.");
}
}
************************************************************
package Assignment_1;
public class BanffMarathonRunner extends AddressBook {
// Member variables
private int time;
private int years;
// Constructors
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
time = min;
years = yr;
}
// Getters and Setters
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
************************************************************
package Assignment_1;
import Assignment_1.BanffMarathonRunner;
public class TestBanffMarathonRunner {
public static void main(String[] args) {
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
System.out.print(r1.getLastName());
}
}
}
Because lastName is null.
You are calling AddressBook(String firstName, String middleName)
and setting the middleName, not the lastName.
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
calls:
// firstName = "Elena"
// lastName = "Brandon"
// min = 341
// yr = 1
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
// ...
}
which calls via super(...):
// firstName = "Elena"
// middleName = "Brandon" <-- here is your issue
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
Brandon is set in AddressBook#middleName instead of AddressBook#lastName.
Your problem is in the BanffMarathonRunner.java:
in the constructor when you are calling the
super(firstName, lastName);
Actually by the call above the super class constructor with two parameter is being called, and that constructor is the one which set the middleName not the lastName.
I think you are confused because of the lastName variable name, which is passed to the constructor with two argument and that constructor use the second argument to set the middleName.
Good Luck.

Categories

Resources