Struts 2, Spring, and Hibernate Integration : model class variable is always null - spring

I am developing an web application using Struts 2, Spring and Hibernate.
When I am running the application its always returning null in model class variables in action class.
Here are the snippets:
StudentPersonalDetails.java:
#Entity
#Table(name="STUDENT_PERSONAL_DETAILS")
public class StudentPersonalDetails {
#Id
#Column(name="Student_ID", unique=true, nullable=false, length=20)
private String StudentId;
#Column(name="FIRST_NAME", nullable=false, length=255)
private String FirstName;
#Column(name="MIDDLE_NAME", nullable=false, length=255)
private String MiddleName;
#Column(name="LAST_NAME", nullable=false, length=255)
private String LastName;
#Column(name="GENDER", nullable=false, length=255)
private String Gender;
#Temporal(TemporalType.DATE)
#Column(name="DATE_OF_BIRTH", nullable=false, length=10)
private Date DateOfBirth;
#Column(name="GUARDIAN", nullable=false, length=255)
private String Guardian;
#Column(name="GUARDIAN_FIRST_NAME", nullable=false, length=255)
private String GuardianFirstName;
#Column(name="GUARDIAN_MIDDLE_NAME", nullable=false, length=255)
private String GuardianMiddleName;
#Column(name="GUARDIAN_LAST_NAME", nullable=false, length=255)
private String GuardianLastName;
#Column(name="STATE_OF_DOMICILE", nullable=false, length=255)
private String StateOfDomicile;
#Column(name="NATIONALITY", nullable=false, length=255)
private String Nationality;
#Column(name="RELIGION", nullable=false, length=255)
private String Religion;
#Column(name="STUDENT_CATEGORY", nullable=false, length=255)
private String Category;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="highestQualification",column=#Column(name="STUDENT_HIGHEST_QUALIFICATION")),
#AttributeOverride(name="yearOfAppearence",column=#Column(name="YEAR_OF_APPEARENCE")),
#AttributeOverride(name="monthOfAppearence",column=#Column(name="MONTH_OF_APPEARENCE"))
})
private QualificationDetails qualificationDetails = new QualificationDetails();
// #ElementCollection
// #JoinTable(name="STUDENT_CONTACT_DETAILS",joinColumns=#JoinColumn(name="STUDENT_ID"))
// #GenericGenerator(name = "hilo-gen", strategy = "hilo")
// #CollectionId(columns = { #Column(name="CONTACT_DETAILS_ID") }, generator = "hilo-gen", type = #Type(type="long"))
// private Collection<ContactDetails> contactDetails = new ArrayList<ContactDetails>();
#Embedded
private ContactDetails contactDetails = new ContactDetails();
public ContactDetails getContactDetails() {
return contactDetails;
}
public void setContactDetails(ContactDetails contactDetails) {
this.contactDetails = contactDetails;
}
public String getStudentId() {
return StudentId;
}
public String getFirstName() {
return FirstName;
}
public String getMiddleName() {
return MiddleName;
}
public String getLastName() {
return LastName;
}
public String getGender() {
return Gender;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public String getGuardian() {
return Guardian;
}
public String getGuardianFirstName() {
return GuardianFirstName;
}
public String getGuardianMiddleName() {
return GuardianMiddleName;
}
public String getGuardianLastName() {
return GuardianLastName;
}
public String getStateOfDomicile() {
return StateOfDomicile;
}
public String getNationality() {
return Nationality;
}
public String getReligion() {
return Religion;
}
public String getCategory() {
return Category;
}
public void setStudentId(String studentId) {
StudentId = studentId;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public void setMiddleName(String middleName) {
MiddleName = middleName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public void setGender(String gender) {
Gender = gender;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public void setGuardian(String guardian) {
Guardian = guardian;
}
public void setGuardianFirstName(String guardianFirstName) {
GuardianFirstName = guardianFirstName;
}
public void setGuardianMiddleName(String guardianMiddleName) {
GuardianMiddleName = guardianMiddleName;
}
public void setGuardianLastName(String guardianLastName) {
GuardianLastName = guardianLastName;
}
public void setStateOfDomicile(String stateOfDomicile) {
StateOfDomicile = stateOfDomicile;
}
public void setNationality(String nationality) {
Nationality = nationality;
}
public void setReligion(String religion) {
Religion = religion;
}
public void setCategory(String category) {
Category = category;
}
public QualificationDetails getQualificationDetails() {
return qualificationDetails;
}
public void setQualificationDetails(QualificationDetails qualificationDetails) {
this.qualificationDetails = qualificationDetails;
}
}
ContactDetails.java:
#Embeddable
public class ContactDetails {
#Column(name="MOBILE_NUMBER", nullable=false, length=255)
private String MobileNumber;
#Column(name="ALTERNATE_NUMBER", nullable=false, length=255)
private String AlternateNumber;
#Column(name="EMAIL_ADDRESS", nullable=false, length=255)
private String EmailAddress;
#Column(name="STREET", nullable=false, length=255)
private String Street;
#Column(name="POST_OFFICE", nullable=false, length=255)
private String PostOffice;
#Column(name="CITY", nullable=false, length=255)
private String City;
#Column(name="PIN_CODE", nullable=false, length=255)
private String PinCode;
#Column(name="STATE", nullable=false, length=255)
private String State;
public String getMobileNumber() {
return MobileNumber;
}
public String getAlternateNumber() {
return AlternateNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
public String getStreet() {
return Street;
}
public String getPostOffice() {
return PostOffice;
}
public String getCity() {
return City;
}
public String getPinCode() {
return PinCode;
}
public String getState() {
return State;
}
public void setMobileNumber(String mobileNumber) {
MobileNumber = mobileNumber;
}
public void setAlternateNumber(String alternateNumber) {
AlternateNumber = alternateNumber;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public void setStreet(String street) {
Street = street;
}
public void setPostOffice(String postOffice) {
PostOffice = postOffice;
}
public void setCity(String city) {
City = city;
}
public void setPinCode(String pinCode) {
PinCode = pinCode;
}
public void setState(String state) {
State = state;
}
}
QualificationDetails.java:
#Embeddable
public class QualificationDetails {
#Column(name="HIGHEST_QUALIFICATION", nullable=false, length=255)
private String highestQualification;
#Column(name="MONTH_OF_APPEARENCE", nullable=false, length=255)
private String monthOfAppearence;
#Column(name="YEAR_OF_APPEARENCE", nullable=false, length=255)
private String yearOfAppearence;
public String getHighestQualification() {
return highestQualification;
}
public String getYearOfAppearence() {
return yearOfAppearence;
}
public void setHighestQualification(String highestQualification) {
this.highestQualification = highestQualification;
}
public void setYearOfAppearence(String yearOfAppearence) {
this.yearOfAppearence = yearOfAppearence;
}
public String getMonthOfAppearence() {
return monthOfAppearence;
}
public void setMonthOfAppearence(String monthOfAppearence) {
this.monthOfAppearence = monthOfAppearence;
}
}
ImplStudentsDao.java:
public class ImplStudentsDao implements StudentsDAO{
#Autowired
private SessionFactory sf;
#Override
public List<StudentPersonalDetails> allStudentsList() throws Exception {
// TODO Auto-generated method stub
return null;
}
#Override
public void Delete(int StudentId) throws Exception {
try
{
}
catch(Exception ex)
{
throw new Exception("CLASS - ImplStudentPersonalDetailsDao : Method - SAVE : MESSEGE - " +ex);
}
}
#Override
public StudentPersonalDetails FindById(int StudentId) throws Exception {
try
{
}
catch(Exception ex)
{
throw new Exception("CLASS - ImplStudentPersonalDetailsDao : Method - SAVE : MESSEGE - " +ex);
}
return null;
}
#Override
public void Save(StudentPersonalDetails spi) throws Exception {
try
{
this.sf.getCurrentSession().saveOrUpdate(spi);
}
catch(Exception ex)
{
throw new Exception("CLASS - ImplStudentPersonalDetailsDao : Method - SAVE : MESSEGE - " +ex);
}
}
#Override
public void Update(StudentPersonalDetails spi) throws Exception {
try
{
}
catch(Exception ex)
{
throw new Exception("CLASS - ImplStudentPersonalDetailsDao : Method - UPDATE : MESSEGE - " +ex);
}
}
public void setSf(SessionFactory sf) {
this.sf = sf;
}
}
Hibernate configuration hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/studentTest</property>
<property name="connection.username">root</property>
<property name="connection.password">pass</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="org.Students.Model.StudentPersonalDetails"/>
</session-factory>
</hibernate-configuration>
Bean configuration spring-bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean name="StudentPersonalDetailsBean" class="org.Students.Model.StudentPersonalDetails">
<property name="contactDetails" ref="contactDetailsBean"/>
<property name="qualificationDetails" ref="qualificationDetailsBean"/>
</bean>
<bean name="contactDetailsBean" class="org.Students.Model.ContactDetails"/>
<bean name="qualificationDetailsBean" class="org.Students.Model.QualificationDetails"/>
<bean name="ImplStudentDaoBean" class="org.Students.Dao.Impl.ImplStudentsDao">
<property name="sf" >
<ref bean="sessionFactory"/>
</property>
</bean>
<bean name="ImplStudentsBoBean" class="org.Students.BO.Impl.ImplStudentsBO">
<property name="stdDao" >
<ref bean="ImplStudentDaoBean"/>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentTest" />
<property name="username" value="root" />
<property name="password" value="pass" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.Students.Model"></property>
<property name="hibernateProperties">
<props>
<prop key="connection.pool_size">1</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
ApplicationFOrm.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Form</title>
</head>
<body>
<s:form method="post" action="addStudentAction">
<s:textfield name="spd.StudentId" label="ID" />
<s:textfield name="spd.FirstName" label="First Name" />
<s:textfield name="spd.MiddleName" label="Middle Name" />
<s:textfield name="spd.LastName" label="Last Name" />
<s:textfield name="spd.Gender" label="Gender" />
<s:textfield name="spd.DateOfBirth" label="Date Of Birth" />
<s:textfield name="spd.Guardian" label="Guardian" />
<s:textfield name="spd.GuardianFirstName" label="Guardian First Name" />
<s:textfield name="spd.GuardianMiddleName" label="Guardian Middle Name"/>
<s:textfield name="spd.GuardianLastName" label="Guardian Last Name" />
<s:textfield name="spd.StateOfDomicile" label="State Of Domicile"/>
<s:textfield name="spd.Nationality" label="Nationality" />
<s:textfield name="spd.Religion" label="Religion" />
<s:textfield name="spd.Category" label="Category" />
<s:textfield name="qd.highestQualification" label="Highest Qualification" />
<s:textfield name="qd.monthOfAppearence" label="Month Of Appearence" />
<s:textfield name="qd.yearOfAppearence" label="Year Of Appearence"/>
<s:textfield name="cd.MobileNumber" label="Mobile Number" />
<s:textfield name="cd.AlternateNumber" label="Alternate Number"/>
<s:textfield name="cd.EmailAddress" label="Email Address" />
<s:textfield name="cd.Street" label="Street" />
<s:textfield name="cd.PostOffice" label="Post Office"/>
<s:textfield name="cd.City" label="City"/>
<s:textfield name="cd.PinCode" label="Pin Code"/>
<s:textfield name="cd.State" label="State"/>
<s:submit />
</s:form>
</body>
</html>
ApplicationAction.java:
public class ApplicationAction extends ActionSupport implements Preparable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(ApplicationAction.class);
private StudentPersonalDetails spd ;
private ContactDetails cd ;
private QualificationDetails qd ;
private StudentsBO Sbo ;
public String execute()
{
System.out.println("Registration Successful!");
return "success";
}
public void validate()
{
System.out.println("validate Method Called");
spd = new StudentPersonalDetails();
System.out.println(spd.getStudentId());
System.out.println(spd.getFirstName());
System.out.println(spd.getMiddleName());
System.out.println(spd.getLastName());
System.out.println(spd.getGender());
System.out.println(spd.getDateOfBirth());
System.out.println(spd.getGuardian());
System.out.println(spd.getGuardianFirstName());
System.out.println(spd.getGuardianMiddleName());
System.out.println(spd.getGuardianLastName());
System.out.println(spd.getStateOfDomicile());
System.out.println(spd.getNationality());
System.out.println(spd.getReligion());
System.out.println(spd.getCategory());
System.out.println(qd.getHighestQualification());
System.out.println(qd.getMonthOfAppearence());
System.out.println(qd.getYearOfAppearence());
System.out.println(cd.getAlternateNumber());
System.out.println(cd.getCity());
System.out.println(cd.getEmailAddress());
System.out.println(cd.getMobileNumber());
System.out.println(cd.getPinCode());
System.out.println(cd.getPostOffice());
System.out.println(cd.getState());
System.out.println(cd.getStreet());
if (spd.getStudentId() == null || spd.getStudentId().trim().equals(""))
{
addFieldError("spd.StudentId","The Student Id is required");
}
if (spd.getFirstName() == null || spd.getFirstName().trim().equals(""))
{
addFieldError("spd.FirstName","The First Name is required");
}
if (spd.getMiddleName() == null || spd.getMiddleName().trim().equals(""))
{
addFieldError("spd.MiddleName","The Middle Name is required");
}
if (spd.getLastName() == null || spd.getLastName().trim().equals(""))
{
addFieldError("spd.LastName","The Last Name is required");
}
if (spd.getGender() == null || spd.getGender().trim().equals(""))
{
addFieldError("spd.Gender","The Gender is required");
}
if (spd.getDateOfBirth() == null || spd.getDateOfBirth().toString().trim().equals(""))
{
addFieldError("spd.DateOfBirth","The Date Of Birth is required");
}
if (spd.getGuardian() == null || spd.getGuardian().trim().equals(""))
{
addFieldError("spd.Guardian","The Guardian is required");
}
if (spd.getGuardianFirstName() == null || spd.getGuardianFirstName().trim().equals(""))
{
addFieldError("spd.GuardianFirstName","The Guardian FirstName is required");
}
if (spd.getGuardianMiddleName() == null || spd.getGuardianMiddleName().trim().equals(""))
{
addFieldError("spd.GuardianMiddleName","The Guardian MiddleName is required");
}
if (spd.getGuardianLastName() == null || spd.getGuardianLastName().trim().equals(""))
{
addFieldError("spd.GuardianLastName","The Guardian LastName is required");
}
if (spd.getStateOfDomicile() == null || spd.getStateOfDomicile().trim().equals(""))
{
addFieldError("spd.StateOfDomicile","The State Of Domicile is required");
}
if (spd.getNationality() == null || spd.getNationality().trim().equals(""))
{
addFieldError("spd.Nationality","The Nationality is required");
}
if (spd.getReligion() == null || spd.getReligion().trim().equals(""))
{
addFieldError("spd.Religion","The Religion is required");
}
if (spd.getCategory() == null || spd.getCategory().trim().equals(""))
{
addFieldError("spd.Category","The Category is required");
}
if (qd.getHighestQualification() == null || qd.getHighestQualification().trim().equals(""))
{
addFieldError("qd.highestQualification","Highest Qualification is required");
}
if (qd.getMonthOfAppearence() == null || qd.getMonthOfAppearence().trim().equals(""))
{
addFieldError("qd.monthOfAppearence","Month Of Appearence is required");
}
if (qd.getYearOfAppearence() == null || qd.getYearOfAppearence().trim().equals(""))
{
addFieldError("qd.yearOfAppearence","The Year Of Appearence is required");
}
if (cd.getAlternateNumber() == null || cd.getAlternateNumber().trim().equals(""))
{
addFieldError("cd.AlternateNumber","The Alternate Number is required");
}
if (cd.getStreet() == null || cd.getStreet().trim().equals(""))
{
addFieldError("cd.Street","Street is required");
}
if (cd.getCity() == null || cd.getCity().trim().equals(""))
{
addFieldError("cd.City","The City is required");
}
if (cd.getEmailAddress() == null || cd.getEmailAddress().trim().equals(""))
{
addFieldError("cd.EmailAddress","The Email Address is required");
}
if (cd.getMobileNumber() == null || cd.getMobileNumber().trim().equals(""))
{
addFieldError("cd.MobileNumber","The Mobile Number is required");
}
if (cd.getPinCode() == null || cd.getPinCode().trim().equals(""))
{
addFieldError("cd.PinCode","The Pin Code is required");
}
if (cd.getPostOffice() == null || cd.getPostOffice().trim().equals(""))
{
addFieldError("cd.PostOffice","The Post Office is required");
}
if (cd.getState() == null || cd.getState().trim().equals(""))
{
addFieldError("cd.State","The State is required");
}
}
public String addStudent()
{
System.out.println("addStudent Method Called");
System.out.println(spd.getStudentId());
System.out.println(spd.getFirstName());
System.out.println(spd.getMiddleName());
System.out.println(spd.getLastName());
System.out.println(spd.getGender());
System.out.println(spd.getDateOfBirth());
System.out.println(spd.getGuardian());
System.out.println(spd.getGuardianFirstName());
System.out.println(spd.getGuardianMiddleName());
System.out.println(spd.getGuardianLastName());
System.out.println(spd.getStateOfDomicile());
System.out.println(spd.getNationality());
System.out.println(spd.getReligion());
System.out.println(spd.getCategory());
System.out.println(qd.getHighestQualification());
System.out.println(qd.getMonthOfAppearence());
System.out.println(qd.getYearOfAppearence());
System.out.println(cd.getAlternateNumber());
System.out.println(cd.getCity());
System.out.println(cd.getEmailAddress());
System.out.println(cd.getMobileNumber());
System.out.println(cd.getPinCode());
System.out.println(cd.getPostOffice());
System.out.println(cd.getState());
System.out.println(cd.getStreet());
spd.setQualificationDetails(qd);
spd.setContactDetails(cd);
try {
Sbo.saveOrUpdate(spd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
#Override
public void prepare() throws Exception {
}
public void setSpd(StudentPersonalDetails spd) {
this.spd = spd;
}
public void setCd(ContactDetails cd) {
this.cd = cd;
}
public void setQd(QualificationDetails qd) {
this.qd = qd;
}
public void setSbo(StudentsBO sbo) {
Sbo = sbo;
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<import resource="classpath*:SusBusinessServiceLayerSpringConfig*.xml"/>
<bean name="ApplicationAction" class="org.Student.ActionClasses.ApplicationAction" scope="prototype">
<property name="spd">
<ref bean="StudentPersonalDetailsBean"/>
</property>
</bean>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Embedded Student Test</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Now the thing is that when I deploy the war file in the apache tomcat and fill up the jsp form the action class model variable printing null values. I don't understand why .
I forgot to mention, here is the
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache software foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="messages" />
<package name="default" extends="struts-default">
<action name="addStudentAction" class="org.Student.ActionClasses.ApplicationAction" method="addStudent" >
<result name="success">/ApplyOnline/RegistrationSucessful.jsp</result>
<result name="input">/ApplyOnline/ApplicationForm.jsp</result>
<result name="failure">/ApplyOnline/ApplicationForm.jsp</result>
</action>
</package>
</struts>

Because you instantiate a model class too late. You should do it before the params interceptor. You can do it inline or in constructor, but not in the validate method.
private StudentPersonalDetails spd = new StudentPersonalDetails();
private ContactDetails cd = new ContactDetails() ;
private QualificationDetails qd = new QualificationDetails() ;
public void validate() {
System.out.println("validate Method Called");
spd = new StudentPersonalDetails();
EDIT:
The spring configuration should be
<bean id="ApplicationAction" class="org.Student.ActionClasses.ApplicationAction" scope="prototype"/>
Struts configuration:
<action name="addStudentAction" class="ApplicationAction">

Related

Spring JPA with Eclipselink save operation does not persist

I've been trying for some couple of days now I just can't seem to figure out why my Eclipselink persistence unit does not perform write operations on my DB. We used to be running OpenJPA and everything was working fine, but with the new EclipseLink config, only thing entities are capable of doing is read data. Write operations do not occur. I'm hoping someone with a better understanding of this can help me out. Maybe I'm missing something.
This is my persistence.xml
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="EclipseLink-PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<!--
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
Optimization - avoid auto flush cost on query execution -->
<!-- property name="eclipselink.batch.size" value="100"/-->
<property name="javax.persistence.validation.group.pre-persist" value=""/>
<property name="javax.persistence.validation.group.pre-update" value="none"/>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.persistence-context.close-on-commit" value="true"/>
<property name="eclipselink.persistence-context.flush-mode" value="commit"/>
<property name="eclipselink.weaving" value="static"/>
<property name="eclipselink.logging.level" value="ALL"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.level.sql" value="ALL"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
</properties>
</persistence-unit>
My infrastructure.xml with configs for transactionManager
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<!-- Necessary to get the entity manager injected into the factory bean -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Define EclipseLink JPA Vendor Adapter -->
<bean id="eclipseLinkAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
depends-on="tenantDatabaseUpgradeService">
<property name="dataSource" ref="routingDataSource" />
<property name="persistenceUnitName" value="EclipseLink-PU" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform"/>
</bean>
</property>
<!--
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
<bean class="org.springframework.instrument.classloading.tomcat.TomcatLoadTimeWeaver" />
</property>-->
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Create instance of transaction template for programmatic transaction manipulation -->
<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
</bean>
Here I have a sample entity I want to persist
#Entity
#Table(name = "m_office", uniqueConstraints = { #UniqueConstraint(columnNames = { "name" }, name = "name_org"),
#UniqueConstraint(columnNames = { "external_id" }, name = "externalid_org") })
public class Office extends AbstractPersistableCustom implements Serializable {
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "parent_id")
private List<Office> children = new LinkedList<>();
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "parent_id")
private Office parent;
#Column(name = "name", nullable = false, length = 100)
private String name;
#Column(name = "hierarchy", nullable = true, length = 50)
private String hierarchy;
#Column(name = "opening_date", nullable = false)
#Temporal(TemporalType.DATE)
private Date openingDate;
#Column(name = "external_id", length = 100)
private String externalId;
public static Office headOffice(final String name, final LocalDate openingDate, final String externalId) {
return new Office(null, name, openingDate, externalId);
}
public static Office fromJson(final Office parentOffice, final JsonCommand command) {
final String name = command.stringValueOfParameterNamed("name");
final LocalDate openingDate = command.localDateValueOfParameterNamed("openingDate");
final String externalId = command.stringValueOfParameterNamed("externalId");
return new Office(parentOffice, name, openingDate, externalId);
}
protected Office() {
this.openingDate = null;
this.parent = null;
this.name = null;
this.externalId = null;
}
private Office(final Office parent, final String name, final LocalDate openingDate, final String externalId) {
this.parent = parent;
this.openingDate = openingDate.toDateTimeAtStartOfDay().toDate();
if (parent != null) {
this.parent.addChild(this);
}
if (StringUtils.isNotBlank(name)) {
this.name = name.trim();
} else {
this.name = null;
}
if (StringUtils.isNotBlank(externalId)) {
this.externalId = externalId.trim();
} else {
this.externalId = null;
}
}
private void addChild(final Office office) {
this.children.add(office);
}
public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<>(7);
final String dateFormatAsInput = command.dateFormat();
final String localeAsInput = command.locale();
final String parentIdParamName = "parentId";
if (command.parameterExists(parentIdParamName) && this.parent == null) { throw new RootOfficeParentCannotBeUpdated(); }
if (this.parent != null && command.isChangeInLongParameterNamed(parentIdParamName, this.parent.getId())) {
final Long newValue = command.longValueOfParameterNamed(parentIdParamName);
actualChanges.put(parentIdParamName, newValue);
}
final String openingDateParamName = "openingDate";
if (command.isChangeInLocalDateParameterNamed(openingDateParamName, getOpeningLocalDate())) {
final String valueAsInput = command.stringValueOfParameterNamed(openingDateParamName);
actualChanges.put(openingDateParamName, valueAsInput);
actualChanges.put("dateFormat", dateFormatAsInput);
actualChanges.put("locale", localeAsInput);
final LocalDate newValue = command.localDateValueOfParameterNamed(openingDateParamName);
this.openingDate = newValue.toDate();
}
final String nameParamName = "name";
if (command.isChangeInStringParameterNamed(nameParamName, this.name)) {
final String newValue = command.stringValueOfParameterNamed(nameParamName);
actualChanges.put(nameParamName, newValue);
this.name = newValue;
}
final String externalIdParamName = "externalId";
if (command.isChangeInStringParameterNamed(externalIdParamName, this.externalId)) {
final String newValue = command.stringValueOfParameterNamed(externalIdParamName);
actualChanges.put(externalIdParamName, newValue);
this.externalId = StringUtils.defaultIfEmpty(newValue, null);
}
return actualChanges;
}
public boolean isOpeningDateBefore(final LocalDate baseDate) {
return getOpeningLocalDate().isBefore(baseDate);
}
public boolean isOpeningDateAfter(final LocalDate activationLocalDate) {
return getOpeningLocalDate().isAfter(activationLocalDate);
}
public LocalDate getOpeningLocalDate() {
LocalDate openingLocalDate = null;
if (this.openingDate != null) {
openingLocalDate = LocalDate.fromDateFields(this.openingDate);
}
return openingLocalDate;
}
public void update(final Office newParent) {
if (this.parent == null) { throw new RootOfficeParentCannotBeUpdated(); }
if (identifiedBy(newParent.getId())) { throw new CannotUpdateOfficeWithParentOfficeSameAsSelf(getId(), newParent.getId()); }
this.parent = newParent;
generateHierarchy();
}
public boolean identifiedBy(final Long id) {
return getId().equals(id);
}
public void generateHierarchy() {
if (this.parent != null) {
this.hierarchy = this.parent.hierarchyOf(getId());
} else {
this.hierarchy = ".";
}
}
private String hierarchyOf(final Long id) {
return this.hierarchy + id.toString() + ".";
}
public String getName() {
return this.name;
}
public String getHierarchy() {
return this.hierarchy;
}
public Office getParent() {
return this.parent;
}
public boolean hasParentOf(final Office office) {
boolean isParent = false;
if (this.parent != null) {
isParent = this.parent.equals(office);
}
return isParent;
}
public boolean doesNotHaveAnOfficeInHierarchyWithId(final Long officeId) {
return !hasAnOfficeInHierarchyWithId(officeId);
}
private boolean hasAnOfficeInHierarchyWithId(final Long officeId) {
boolean match = false;
if (identifiedBy(officeId)) {
match = true;
}
if (!match) {
for (final Office child : this.children) {
final boolean result = child.hasAnOfficeInHierarchyWithId(officeId);
if (result) {
match = result;
break;
}
}
}
return match;
}
public void loadLazyCollections() {
this.children.size() ;
}
}
Any help will be much appreciated.
Using saveAndFlush where appropriate did the trick for me.

Hibernate Tool :Foreign key must have same number of columns as the referenced primary key

I am trying to implement Hibernate tool(Reverse Engineering). This is .hbm.xml generated by the tool.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 28, 2016 1:37:34 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.telemune.bean.CrbtSubscriberMaster" table="CRBTSUBSCRIBERMASTER">
<id name="corpId" type="int">
<column name="CORPID" />
<generator class="assigned" />
</id>
<property name="msisdn" type="java.lang.String">
<column name="MSISDN" />
</property>
<property name="status" type="java.lang.String">
<column name="STATUS" />
</property>
<property name="dateRegistered" type="java.util.Date">
<column name="DATEREGISTERED" />
</property>
<property name="planIndicator" type="short">
<column name="PLANINDICATOR" />
</property>
<property name="rbtCode" type="long">
<column name="RBTCODE" />
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" />
</property>
<property name="tpin" type="java.lang.String">
<column name="TPIN" />
</property>
<property name="freeEventsUsed" type="byte">
<column name="FREEEVENTSUSED" />
</property>
<property name="blackListed" type="boolean">
<column name="BLACKLISTED" />
</property>
<property name="language" type="boolean">
<column name="LANGUAGE" />
</property>
<primitive-array name="defaultGroupSetting" table="CRBTSUBSCRIBERMASTER">
<key>
<column name="CORPID" />
</key>
<index></index>
<element type="byte">
<column name="DEFAULTGROUPSETTING" />
</element>
</primitive-array>
<primitive-array name="defaultSingleSetting" table="CRBTSUBSCRIBERMASTER">
<key>
<column name="CORPID" />
</key>
<index></index>
<element type="byte">
<column name="DEFAULTSINGLESETTING" />
</element>
</primitive-array>
<property name="dateSettingValidity" type="boolean">
<column name="DATESETTINGVALIDITY" />
</property>
<property name="imsi" type="java.lang.String">
<column name="IMSI" />
</property>
<property name="lastCharged" type="java.util.Date">
<column name="LASTCHARGED" />
</property>
<property name="isMonthlyChargeable" type="java.lang.String">
<column name="ISMONTHLYCHARGEABLE" />
</property>
<property name="subType" type="java.lang.String">
<column name="SUBTYPE" />
</property>
<property name="renewMode" type="byte">
<column name="RENEWMODE" />
</property>
<property name="expiryDate" type="java.util.Date">
<column name="EXPIRYDATE" />
</property>
<property name="activeFeatures" type="java.lang.Boolean">
<column name="ACTIVEFEATURES" />
</property>
<property name="inUseRbt" type="java.lang.Integer">
<column name="INUSERBT" />
</property>
<property name="updateTime" type="java.util.Date">
<column name="UPDATETIME" />
</property>
<property name="corpExpiry" type="java.util.Date">
<column name="CORPEXPIRY" />
</property>
</class>
And this is the code where I'm trying to apply the query(HQL):
public void getDetails() {
try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql = "select c.msisdn, c.password FROM CrbtSubscriberMaster c where rownum<20";
Query query = session.createQuery(hql);
List<Object[]> itr = query.list();
// System.out.println("[" + itr+ "]");
session.getTransaction().commit();
for (Object[] object : itr) {
// CrbtSubMasterDemo pojo = (CrbtSubMasterDemo) iterator.next();
System.out.println("["
+ String.format("mobile:%s, password:%s", object[0],
object[1]) + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}
And this the Excetion Stack:
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.
Exception in thread "main" org.hibernate.MappingException: Foreign key (FK3CFB77CBCAD1A7D6:CRBTSUBSCRIBERMASTER [CORPID])) must have same number of columns as the referenced primary key (CRBTSUBSCRIBERMASTER [CORPID,idx])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:112)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:95)
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1805)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1726)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1393)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1826)
at com.telemune.demoHibernate.QueryTester.<init>(QueryTester.java:14)
at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:18)
I am new to Hibernate Please Help me Understand and Resolve the cause. Thank s in Advance.
Update: The DB Desc of CRBT_SUBSCRIBER_MASTER
Name Null? Type
----------------------------------------- ---------
MSISDN NOT NULL VARCHAR2(15)
STATUS NOT NULL VARCHAR2(3)
DATE_REGISTERED NOT NULL DATE
PLAN_INDICATOR NOT NULL NUMBER(3)
RBT_CODE NOT NULL NUMBER(10)
PASSWORD NOT NULL VARCHAR2(15)
TPIN NOT NULL VARCHAR2(4)
FREE_EVENTS_USED NOT NULL NUMBER(2)
BLACK_LISTED NOT NULL NUMBER(1)
LANGUAGE NOT NULL NUMBER(1)
DEFAULT_GROUP_SETTING NOT NULL RAW(30)
DEFAULT_SINGLE_SETTING NOT NULL RAW(30)
DATE_SETTING_VALIDITY NOT NULL NUMBER(1)
IMSI NOT NULL VARCHAR2(20)
LAST_CHARGED DATE
IS_MONTHLY_CHARGEABLE VARCHAR2(1)
CORP_ID NOT NULL NUMBER(5)
And some more colums are there.
According to my knowledge MSISDN is the Primary key but the tool is seems to take Corp Id as Primary Key.
Update 2: The Pojo class created by the tool itself
#Entity
#Table(name = "CRBT_SUBSCRIBER_MASTER", schema = "SDP")
public class CrbtSubscriberMaster implements java.io.Serializable {
private String msisdn;
private String status;
private Date dateRegistered;
private short planIndicator;
private long rbtCode;
private String password;
private String tpin;
private byte freeEventsUsed;
private boolean blackListed;
private boolean language;
private byte[] defaultGroupSetting;
private byte[] defaultSingleSetting;
private boolean dateSettingValidity;
private String imsi;
private Date lastCharged;
private String isMonthlyChargeable;
private int corpId;
private String subType;
private byte renewMode;
private Date expiryDate;
private Boolean activeFeatures;
private Integer inUseRbt;
private Date updateTime;
private Date corpExpiry;
public CrbtSubscriberMaster() {
}
public CrbtSubscriberMaster(String msisdn, String status,
Date dateRegistered, short planIndicator, long rbtCode,
String password, String tpin, byte freeEventsUsed,
boolean blackListed, boolean language, byte[] defaultGroupSetting,
byte[] defaultSingleSetting, boolean dateSettingValidity,
String imsi, int corpId, byte renewMode, Date updateTime) {
this.msisdn = msisdn;
this.status = status;
this.dateRegistered = dateRegistered;
this.planIndicator = planIndicator;
this.rbtCode = rbtCode;
this.password = password;
this.tpin = tpin;
this.freeEventsUsed = freeEventsUsed;
this.blackListed = blackListed;
this.language = language;
this.defaultGroupSetting = defaultGroupSetting;
this.defaultSingleSetting = defaultSingleSetting;
this.dateSettingValidity = dateSettingValidity;
this.imsi = imsi;
this.corpId = corpId;
this.renewMode = renewMode;
this.updateTime = updateTime;
}
public CrbtSubscriberMaster(String msisdn, String status,
Date dateRegistered, short planIndicator, long rbtCode,
String password, String tpin, byte freeEventsUsed,
boolean blackListed, boolean language, byte[] defaultGroupSetting,
byte[] defaultSingleSetting, boolean dateSettingValidity,
String imsi, Date lastCharged, String isMonthlyChargeable,
int corpId, String subType, byte renewMode, Date expiryDate,
Boolean activeFeatures, Integer inUseRbt, Date updateTime,
Date corpExpiry) {
this.msisdn = msisdn;
this.status = status;
this.dateRegistered = dateRegistered;
this.planIndicator = planIndicator;
this.rbtCode = rbtCode;
this.password = password;
this.tpin = tpin;
this.freeEventsUsed = freeEventsUsed;
this.blackListed = blackListed;
this.language = language;
this.defaultGroupSetting = defaultGroupSetting;
this.defaultSingleSetting = defaultSingleSetting;
this.dateSettingValidity = dateSettingValidity;
this.imsi = imsi;
this.lastCharged = lastCharged;
this.isMonthlyChargeable = isMonthlyChargeable;
this.corpId = corpId;
this.subType = subType;
this.renewMode = renewMode;
this.expiryDate = expiryDate;
this.activeFeatures = activeFeatures;
this.inUseRbt = inUseRbt;
this.updateTime = updateTime;
this.corpExpiry = corpExpiry;
}
#Id
#Column(name = "MSISDN", unique = true, nullable = false, length = 15)
public String getMsisdn() {
return this.msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
#Column(name = "STATUS", nullable = false, length = 3)
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#Temporal(TemporalType.DATE)
#Column(name = "DATE_REGISTERED", nullable = false, length = 7)
public Date getDateRegistered() {
return this.dateRegistered;
}
public void setDateRegistered(Date dateRegistered) {
this.dateRegistered = dateRegistered;
}
#Column(name = "PLAN_INDICATOR", nullable = false, precision = 3, scale = 0)
public short getPlanIndicator() {
return this.planIndicator;
}
public void setPlanIndicator(short planIndicator) {
this.planIndicator = planIndicator;
}
#Column(name = "RBT_CODE", nullable = false, precision = 10, scale = 0)
public long getRbtCode() {
return this.rbtCode;
}
public void setRbtCode(long rbtCode) {
this.rbtCode = rbtCode;
}
#Column(name = "PASSWORD", nullable = false, length = 15)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "TPIN", nullable = false, length = 4)
public String getTpin() {
return this.tpin;
}
public void setTpin(String tpin) {
this.tpin = tpin;
}
#Column(name = "FREE_EVENTS_USED", nullable = false, precision = 2, scale = 0)
public byte getFreeEventsUsed() {
return this.freeEventsUsed;
}
public void setFreeEventsUsed(byte freeEventsUsed) {
this.freeEventsUsed = freeEventsUsed;
}
#Column(name = "BLACK_LISTED", nullable = false, precision = 1, scale = 0)
public boolean isBlackListed() {
return this.blackListed;
}
public void setBlackListed(boolean blackListed) {
this.blackListed = blackListed;
}
#Column(name = "LANGUAGE", nullable = false, precision = 1, scale = 0)
public boolean isLanguage() {
return this.language;
}
public void setLanguage(boolean language) {
this.language = language;
}
#Column(name = "DEFAULT_GROUP_SETTING", nullable = false)
public byte[] getDefaultGroupSetting() {
return this.defaultGroupSetting;
}
public void setDefaultGroupSetting(byte[] defaultGroupSetting) {
this.defaultGroupSetting = defaultGroupSetting;
}
#Column(name = "DEFAULT_SINGLE_SETTING", nullable = false)
public byte[] getDefaultSingleSetting() {
return this.defaultSingleSetting;
}
public void setDefaultSingleSetting(byte[] defaultSingleSetting) {
this.defaultSingleSetting = defaultSingleSetting;
}
#Column(name = "DATE_SETTING_VALIDITY", nullable = false, precision = 1, scale = 0)
public boolean isDateSettingValidity() {
return this.dateSettingValidity;
}
public void setDateSettingValidity(boolean dateSettingValidity) {
this.dateSettingValidity = dateSettingValidity;
}
#Column(name = "IMSI", nullable = false, length = 20)
public String getImsi() {
return this.imsi;
}
public void setImsi(String imsi) {
this.imsi = imsi;
}
#Temporal(TemporalType.DATE)
#Column(name = "LAST_CHARGED", length = 7)
public Date getLastCharged() {
return this.lastCharged;
}
public void setLastCharged(Date lastCharged) {
this.lastCharged = lastCharged;
}
#Column(name = "IS_MONTHLY_CHARGEABLE", length = 1)
public String getIsMonthlyChargeable() {
return this.isMonthlyChargeable;
}
public void setIsMonthlyChargeable(String isMonthlyChargeable) {
this.isMonthlyChargeable = isMonthlyChargeable;
}
#Column(name = "CORP_ID", nullable = false, precision = 5, scale = 0)
public int getCorpId() {
return this.corpId;
}
public void setCorpId(int corpId) {
this.corpId = corpId;
}
#Column(name = "SUB_TYPE", length = 3)
public String getSubType() {
return this.subType;
}
public void setSubType(String subType) {
this.subType = subType;
}
#Column(name = "RENEW_MODE", nullable = false, precision = 2, scale = 0)
public byte getRenewMode() {
return this.renewMode;
}
public void setRenewMode(byte renewMode) {
this.renewMode = renewMode;
}
#Temporal(TemporalType.DATE)
#Column(name = "EXPIRY_DATE", length = 7)
public Date getExpiryDate() {
return this.expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
#Column(name = "ACTIVE_FEATURES", precision = 1, scale = 0)
public Boolean getActiveFeatures() {
return this.activeFeatures;
}
public void setActiveFeatures(Boolean activeFeatures) {
this.activeFeatures = activeFeatures;
}
#Column(name = "IN_USE_RBT", precision = 8, scale = 0)
public Integer getInUseRbt() {
return this.inUseRbt;
}
public void setInUseRbt(Integer inUseRbt) {
this.inUseRbt = inUseRbt;
}
#Temporal(TemporalType.DATE)
#Column(name = "UPDATE_TIME", nullable = false, length = 7)
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
#Temporal(TemporalType.DATE)
#Column(name = "CORP_EXPIRY", length = 7)
public Date getCorpExpiry() {
return this.corpExpiry;
}
public void setCorpExpiry(Date corpExpiry) {
this.corpExpiry = corpExpiry;
}
}
The tool most probably has a bug or a missing feature. It didn't generate a correct array index column.
<index></index>
should be something like this:
<index column="idx"></index>
The index is part of the primary kay of the table where the array is stored in. It is required to store the order within the array.
Well guys. This is a bug in The Hibernate tool that I have download using Eclipse Luna's Help. And the Bug is that it took the wrong name for the Table name Mapping. i.e.
<class name="com.telemune.bean.CrbtSubscriberMaster" table="CRBTSUBSCRIBERMASTER">
where as the real name of the Table is CRBT_SUBSCRIBER_MASTER. i.e. the mapping should be:
<class name="com.telemune.bean.CrbtSubscriberMaster" table="CRBT_SUBSCRIBER_MASTER">
I just tried it and it solved my problem. If someone has the Explanation why is it so? please explain.
UPDATE :
and another important thing that I have noticed here is that selecting the option showing in the image Use Java 5 Syntax may be helpful.

Spring Constructor Injection Weird Error

I have encountered below BeanDefinitionDecorator error at below constructor-arg dependency line in Bean XML (root-context.xml) in Eclipse, but no issue when using setter injection with property element, appreciate if anyone here could provide advice, as not able to identify the root cause even after search through Internet. Thanks in advance.
Error encountered
"Multiple annotations found at this line:
Cannot locate BeanDefinitionDecorator for element [constructor-arg]
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'.
Configuration problem: Cannot locate BeanDefinitionDecorator for element [constructor-arg] Offending resource: file [C:/Users/Administrator/
workspace/EsmProject/src/main/webapp/WEB-INF/spring/root-context.xml]"
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean id="myObject" class="com.packapp.MyObject"></beans:bean>
<beans:bean id="homeDAO" class="com.packapp.HomeDAOImpl">
<constructor-arg><ref bean="myObject"/></constructor-arg>
</beans:bean>
<beans:bean id = "homeService" class="com.packapp.HomeServiceImpl">
<beans:property name="homeDAO" ref="homeDAO"></beans:property>
</beans:bean>
<context:component-scan base-package="com.packapp" />
</beans:beans>
public class MyObject {
private String homeName;
private String homeAddress;
public String getHomeName(){
return homeName;
}
public void setHomeName(String homeName){
this.homeName = homeName;
}
public String getHomeAddress(){
return homeAddress;
}
public void setHomeAddress(String homeAddress){
this.homeAddress = homeAddress;
}
}
#Repository
public class HomeDAOImpl implements HomeDAO {
private MyObject obj;
public HomeDAOImpl(MyObject obj){
this.obj = obj;
}
public String getAddress() {
return this.obj.getHomeAddress();
}
}
#Service
public class HomeServiceImpl implements HomeService {
private HomeDAO homeDAO;
public void setHomeDAO(HomeDAO homeDAO){
this.homeDAO = homeDAO;
}
public String getAddress() {
return this.homeDAO.getAddress();
}
}
#Controller
#RequestMapping("ctrl2")
public class HomeController2 {
private HomeService homeService;
#Autowired(required=true)
#Qualifier(value="homeService")
public void setHomeService (HomeService hs){
this.homeService = hs;
}
#RequestMapping(value = "/site2", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate + this.homeService.getAddress());
return "home2";
}
}
I think <constructor-arg><ref bean="myObject"/></constructor-arg>
must be <beans:constructor-arg><beans:ref bean="myObject"/></beans:constructor-arg>
because you have a prefix for elements in spring-beans.xsd.

#XmlPath not working

#XmlPath is not working.
Customer.java
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name= "Customer")
public class Customer {
private String CustomerId;
private String organizationCode;
private Extn extn;
private String organizationName;
private int reset;
private CustomerSchedulingPreferences customerSchedulingPreferences;
private ArrayList<RestrictedState> restrictedStateList;
#XmlAttribute
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
#XmlAttribute
public String getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
#XmlElement(name="Extn")
public Extn getExtn() {
return extn;
}
public void setExtn(Extn extn) {
this.extn = extn;
}
#XmlPath("BuyerOrganization/#OrganizationName")
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList")
#XmlElement(name = "USSCORestrictedState")
public ArrayList<RestrictedState> getRestrictedStateList() {
return restrictedStateList;
}
public void setRestrictedStateList(ArrayList<RestrictedState> restrictedStateList) {
this.restrictedStateList = restrictedStateList;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList/#Reset")
public int getReset() {
return reset;
}
public void setReset(int reset) {
this.reset = reset;
}
#XmlElement(name="CustomerSchedulingPreferences")
public CustomerSchedulingPreferences getCustomerSchedulingPreferences() {
return customerSchedulingPreferences;
}
public void setCustomerSchedulingPreferences(
CustomerSchedulingPreferences customerSchedulingPreferences) {
this.customerSchedulingPreferences = customerSchedulingPreferences;
}
}
Client.java
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class Client
{
public static void main(String[] args)throws IOException
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
Customer customer=new Customer();
customer.setCustomerId("12345");
customer.setOrganizationCode("SUPPLY");
Extn extn = new Extn();
extn.setExtnBillCreditCode("000");
extn.setExtnBillSubscriptionId("132131");
customer.setExtn(extn);
RestrictedState resState1= new RestrictedState();
resState1.setOrgCode("952121");
resState1.setRestrictedStateCode("IN");
RestrictedState resState2= new RestrictedState();
resState2.setOrgCode("60325");
resState2.setRestrictedStateCode("IL");
ArrayList<RestrictedState> restrictedStateList = new ArrayList<RestrictedState>();
restrictedStateList.add(resState1);
restrictedStateList.add(resState2);
CustomerSchedulingPreferences custSchedPref = new CustomerSchedulingPreferences();
custSchedPref.setIsLineShipComplete("Y");
custSchedPref.setIsLineShipSingleNode("N");
custSchedPref.setOptimizationType("03");
customer.setCustomerSchedulingPreferences(custSchedPref);
customer.setRestrictedStateList(restrictedStateList);
marshaller.marshal(customer, new StreamResult(new FileWriter("customer.xml")));
System.out.println("XML Created Sucessfully");
}
}
applicationContext.Xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<oxm:jaxb2-marshaller id="jaxbMarshallerBean">
<oxm:class-to-be-bound name="com.javatpoint.Customer"/>
</oxm:jaxb2-marshaller>
</beans>
Structure of Output needed :
<Customer CustomerID="952121" OrganizationCode="SUPPLY" >
<Extn ExtnBillCreditCode="000" ExtnBillSubscriptionID="952121" />
<BuyerOrganization OrganizationName="Buy.com1" >
<Extn>
<USSCORestrictedStateList Reset="Y">
<USSCORestrictedState OrganizationCode="952121" RestrictedStateCode="IN"/>
</USSCORestrictedStateList>
</Extn>
</BuyerOrganization>
<CustomerSchedulingPreferences IsLineShipComplete="" IsLineShipSingleNode="" />
</Customer>
================================================================================
Please help me in resolving this:
Currently i am getting output like below :
<Customer organizationCode="SUPPLY" customerId="12345">
<CustomerSchedulingPreferences IsLineShipSingleNode="N" IsLineShipComplete="Y"/>
<Extn ExtnBillSubscriptionID="132131" ExtnBillCreditCode="000"/>
<reset>0</reset>
<USSCORestrictedState restrictedStateCode="IN" OrganizationCode="952121"/>
<USSCORestrictedState restrictedStateCode="IL" OrganizationCode="60325"/>
</Customer>
To leverage the #XmlPath extension you need to be using EclipseLink MOXy as your JAXB provider.
eclipselink.jar on your classpath
a jaxb.properties file in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Below is a link that will help set this up:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/Spring

Error message is not displayed in freemarker template for custom FieldMatchValidator in Spring application

As stated in the title I can't make the error message for the FieldMatchValidator to show in my freemarker template. All the other "regular" error messages, such as #NotNull are displayed with the accurate message from message.properties. The validation with FieldMatchValidator works since the result.hasErrors() returns true and the result objects holds the FieldMatch error. What have I missed?
applicationContext.xml:
<!-- Invokes Spring MVC #Controller methods -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<!-- Configures Spring MVC DataBinder instances -->
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator"/>
</bean>
</property>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="messageInterpolator">
<bean class="com.reco.web.mvc.validator.CustomMessageInterpolator">
<property name="messageSource" ref="messageSource"/>
</bean>
</property>
</bean>
Controller:
#Controller
public class RegisterController extends MyWebController{
private static final String REGISTER_FORM_VIEW = "/action/register/register";
private static final String REGISTER_SUCCESS_VIEW = "/action/register/success";
private org.springframework.validation.Validator validator;
#Autowired
public RegisterController(MessageSource messageSource, Validator validator) {
super(messageSource);
this.validator = validator;
}
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator((org.springframework.validation.Validator)validator);
}
#RequestMapping(value = "/action/register", method = RequestMethod.GET)
public ModelAndView getRegisterForm() {
ModelAndView mav = new ModelAndView(REGISTER_FORM_VIEW);
mav.addObject("registerForm", new RegisterForm());
return mav;
}
#RequestMapping(value = "/action/register", method = RequestMethod.POST)
public final String register(#Valid RegisterForm registerForm, BindingResult result, ModelMap model, HttpServletRequest request) {
if (result.hasErrors()) {
return REGISTER_FORM_VIEW;
}
return "redirect:" + REGISTER_SUCCESS_VIEW;
}
}
Annotation:
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = FieldMatchValidator.class)
#Documented
public #interface FieldMatch {
String message() default "{constraints.fieldmatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* #return The first field
*/
String first();
/**
* #return The second field
*/
String second();
/**
* Defines several <code>#FieldMatch</code> annotations on the same element
*
* #see FieldMatch
*/
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Documented
#interface List {
FieldMatch[] value();
}
}
Validator:
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final FieldMatch constraintAnnotation)
{
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
try
{
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
}
catch (final Exception ignore)
{
// ignore
}
return true;
}
}
freemarker template:
<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body id="register">
<div id="content">
<form id="registerForm" action="${rc.contextPath}/action/register" method="POST">
<p>
<label for="firstname">firstname</label>
<#spring.formInput "registerForm.firstName" />
<#spring.showErrors "", "error"/>
</p>
<p>
<label for="lastname">lastname</label>
<#spring.formInput "registerForm.lastName" />
<#spring.showErrors "", "error"/>
</p>
<p>
<label for="email">email</label>
<#spring.formInput "registerForm.email" />
<#spring.showErrors "", "error"/>
</p>
<p>
<label for="email_again">email_again</label>
<#spring.formInput "registerForm.confirmEmail" />
<#spring.showErrors "", "error"/>
</p>
<p>
<label for="password">password</label>
<#spring.formPasswordInput "registerForm.password" />
<#spring.showErrors "", "error"/>
</p>
<p>
<label for="password_again">password_again</label>
<#spring.formPasswordInput "registerForm.confirmPassword" />
<#spring.showErrors "", "error"/>
<#spring.showErrors "", "confirmPassword"/>
</p>
<input type="submit"/>
</form>
</div>
</body>
</html>
FormObject:
#FieldMatch.List({
#FieldMatch(first = "password", second = "confirmPassword", message = "validation.message.confirm.password"),
#FieldMatch(first = "email", second = "confirmEmail", message = "validation.message.confirm.email")
})
public class RegisterForm implements Serializable {
private static final int MAX_TEXT_FIELD_SIZE = 32;
/**
* Password min size.
*/
private static final int PASSWORD_MIN_SIZE = 8;
/**
* Password max size.
*/
private static final int PASSWORD_MAX_SIZE = 36;
#NotNull(message = "validation.message.firstname.empty")
#Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.firstname.length")
#Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
private String firstName;
#NotNull(message = "validation.message.lastname.empty")
#Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.lastname.length")
#Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
private String lastName;
#NotNull(message = "validation.message.email.empty")
#Pattern(regexp = ".+#.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
private String email;
#NotNull(message = "validation.message.email.empty")
#Pattern(regexp = ".+#.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
private String confirmEmail;
#NotNull
#Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
private String password;
#NotNull
#Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
private String confirmPassword;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getConfirmEmail() {
return confirmEmail;
}
public void setConfirmEmail(String confirmEmail) {
this.confirmEmail = confirmEmail;
}
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;
}
}
I solved the problem by adding the proper constraint validation message:
errorMessage = constraintAnnotation.message();
to the proper field inside the custom FieldMatchValidator. In my case I added the error to the second field:
context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();
FieldMatchValidator
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
private String firstFieldName;
private String secondFieldName;
private String errorMessage;
#Override
public void initialize(final FieldMatch constraintAnnotation)
{
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
errorMessage = constraintAnnotation.message();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
try
{
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
boolean valid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
if(!valid){
context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();
}
return valid;
}
catch (final Exception ignore)
{
// ignore
}
return true;
}
}

Resources