Spring JPA with Eclipselink save operation does not persist - spring

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.

Related

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.

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

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">

Batch insertion with Spring MVC and Hibernate 3

I am using Spring MVC + Hibernate and try to save bulk record using "hibernate batch procession technique" but getting below exception when I am doing session.flush() and session.clear().
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
following is my code sample
DaoImpl method
#SuppressWarnings("unchecked")
#Override
public String transferPsalesDataToMisSales() {
Session session = null;
Transaction tx=null;
String result="failed";
try {session = this.getSessionFactory().openSession();
tx = session.beginTransaction();
Criteria criteria=session.createCriteria(PsalesInfo.class);
List<PsalesInfo> pSalesData=criteria.list();
if(pSalesData.size() >0){
Iterator<PsalesInfo> it=pSalesData.iterator();
int index=0;
MisSalesInfo mis=null;
while(it.hasNext()){
mis=new MisSalesInfo();
PsalesInfo psales=it.next();
StockistInfo stockistInfo=psales.getStockistInfo();
TalukaInfo talukaInfo=stockistInfo.getTalukaInfo();
IsrInfo isr=(IsrInfo) session.get(IsrInfo.class, stockistInfo.getIsrId());
//mis settters
mis.setMisSalesId(psales.getPsalesId());
mis.setStateName(talukaInfo.getDistrictInfo().getStateInfo().getStateName());
mis.setDistName(talukaInfo.getDistrictInfo().getDistName());
mis.setTalukaName(talukaInfo.getTalukaName());
mis.setAsmId(talukaInfo.getAsmInfo().getAsmId());
mis.setTsoId(stockistInfo.getTsoInfo().getTsoId());
if(null!=isr){
mis.setIsrId(isr.getIsrId());
mis.setIsrName(isr.getIsrName());
}
mis.setUnitNo(stockistInfo.getUnitNo());
mis.setBillNo(psales.getBillNo());
session.save(mis);
if(index % 50==0){
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
index++;
}//end of while
tx.commit();
result=pSalesData.size()+" Psales are Successfully transfered to MIS Sales";
}
else{
result="No Psales is available to transfer since are already available in MIS Sales";
}
} catch (HibernateException e) {
tx.rollback();
logger.error("error in MasterDaoImpl transfer data:"+e);
}finally {
if (null != session)
session.close();
}
return result;
}
POJOs
#Entity
#Table(name = "psales_info", catalog = "secondary_sales")
public class PsalesInfo implements java.io.Serializable {
private static final long serialVersionUID = 5578632011679493005L;
private Integer psalesId;
private StockistInfo stockistInfo;
//and some other attributes
//getter and setters
#Id
#GenericGenerator(name="generator", strategy="increment")
#GeneratedValue(generator="generator")
#Column(name = "psales_id", unique = true, nullable = false)
public Integer getPsalesId() {
return this.psalesId;
}
public void setPsalesId(Integer psalesId) {
this.psalesId = psalesId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "pcode", nullable = false)
public StockistInfo getStockistInfo() {
return this.stockistInfo;
}
//and others
#Entity
#Table(name = "stockist_info", catalog = "secondary_sales")
public class StockistInfo implements java.io.Serializable {
private String stockistId;
private TalukaInfo talukaInfo;
//and rest attributes
//getters and setters
// Property accessors
#Id
#Column(name = "stockist_id", unique = true, nullable = false, length = 10)
public String getStockistId() {
return this.stockistId;
}
public void setStockistId(String stockistId) {
this.stockistId = stockistId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "taluka_sid", nullable = false)
public TalukaInfo getTalukaInfo() {
return this.talukaInfo;
}
ServiceImpl
#Service
#Transactional
public class TransactionServiceImpl implements TransactionService {
#Autowired
private TransactionDAO transactionDAO;
#Override
public String transferPsalesDataToMisSales() {
return this.getTransactionDAO().transferPsalesDataToMisSales();
}
}
dispature-servlet.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.default_catalog">${hibernate.default_catalog}</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
Need help here why it is throwing LazyInitializationException when I'm clearing the session.
But when I'm not clearing the session ie. wihtout session.clear() and session.flush() application is running properly.
but I know it may lead to OutOfMemoryException in case of more bulk record.
so plz tell how to deal with this situation now?
Your dao code is flawed... Don't open new sessions yourself and don't mess aroudn with transactions yourself either. Remove the transaction stuff from your dao method and the call to openSession should be replaced with getCurrentSession.
#SuppressWarnings("unchecked")
#Override
public String transferPsalesDataToMisSales() {
Session session = this.getSessionFactory().getCurrentSession();
Criteria criteria=session.createCriteria(PsalesInfo.class);
List<PsalesInfo> pSalesData=criteria.list();
int index=0;
for (PsalesInfo psales : pSalesData) {
MisSalesInfo mis=new MisSalesInfo();
StockistInfo stockistInfo=psales.getStockistInfo();
TalukaInfo talukaInfo=stockistInfo.getTalukaInfo();
IsrInfo isr=(IsrInfo) session.get(IsrInfo.class, stockistInfo.getIsrId());
//mis settters
mis.setMisSalesId(psales.getPsalesId());
mis.setStateName(talukaInfo.getDistrictInfo().getStateInfo().getStateName());
mis.setDistName(talukaInfo.getDistrictInfo().getDistName());
mis.setTalukaName(talukaInfo.getTalukaName());
mis.setAsmId(talukaInfo.getAsmInfo().getAsmId());
mis.setTsoId(stockistInfo.getTsoInfo().getTsoId());
if(null!=isr){
mis.setIsrId(isr.getIsrId());
mis.setIsrName(isr.getIsrName());
}
mis.setUnitNo(stockistInfo.getUnitNo());
mis.setBillNo(psales.getBillNo());
session.save(mis);
if(index % 50==0){
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
index++;
}//end of loop
if (pSalesData.isEmpty() ) {
return "No Psales is available to transfer since are already available in MIS Sales";
} else {
return pSalesData.size()+" Psales are Successfully transfered to MIS Sales";
}
}

String to Date Conversion in Spring 4.0

I am educating myself on Spring 4.0.0 M3
Following is the code,
Bean
package org.chebus.springs;
import java.util.Date;
public class Traingle {
private String name;
private int height;
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void drawShape() {
System.out.println(getName() + " Traingle height " + getHeight()
+ " Date = " + getDate());
}
}
Main
ApplicationContext ctx = new ClassPathXmlApplicationContext("org/chebus/springs/Spring.xml");
Traingle traingle = ctx.getBean("traingle",Traingle.class);
traingle.drawShape();
XML Config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id = "traingle" class="org.chebus.springs.Traingle">
<property name="name" value = "RightAngled"/>
<property name="height" value = "20"/>
<property name="date" value = "2013-09-10"/>
</bean>
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<ref local="dateEditor" />
</entry>
</map>
</property>
</bean>
</beans>
Exception:
java.lang.IllegalArgumentException: Cannot convert value of type
[org.springframework.beans.propertyeditors.CustomDateEditor] to
required type [java.lang.Class] for property
'customEditors[java.util.Date]': PropertyEditor
[org.springframework.beans.propertyeditors.ClassEditor] returned
inappropriate value of type
[org.springframework.beans.propertyeditors.CustomDateEditor] at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:260)
at
org.springframework.beans.TypeConverterDelegate.convertToTypedMap(TypeConverterDelegate.java:620)
at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:205)
at
org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:459)
... 17 more
Not sure where i am going wrong. Appreciate your help. Thanks!
Good catch, this seems to be a new behavior with Spring 4.0+, your code works cleanly with 3.2.x version of Spring.
The reason appears to be because the type of customEditors in
CustomEditorConfigurer has changed with Spring 4.0+. Whereas it was of type Map<String, ?> with Spring 3.2.x it is Map<Class<?>, Class<? extends PropertyEditor>> with Spring 4.0+.
The fix is to instead create a custom PropertyEditorRegistrar, this way:
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
#Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
}
and to use this in the configuration:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="dateeditor.CustomDateEditorRegistrar"/>
</list>
</property>
</bean>
There is no builtin of Date values by default in spring.
Here you go :
How to initialize a Java Date object in Spring xml configuration file?

Initialising static list using spring

I have a class as below:
public class SensitivityDescription {
private final String measureId;
private final ColumnType type; private final String sensName;
private final SensType sensType;
private final ServicePhase svcPhase;
private final AggregateFunction agFn;
private final String positionEnum;
private static List <SensitivityDescription> senRecordList = new ArrayList<SensitivityDescription> ();
public SensitivityDescription(String measureId, ColumnType type,
String sensName, SensType sensType, ServicePhase svcPhase,
AggregateFunction agFn, String positionEnum) {
super();
this.measureId = measureId;
this.type = type;
this.sensName = sensName;
this.sensType = sensType;
this.svcPhase = svcPhase;
this.agFn = agFn;
this.positionEnum = positionEnum;
}
I need to populate the static senRecordList with objects of the SensitivityDescription class.How do I do this in spring xml.
Based on this link everything is working:
Class
package com.sopovs.moradanen.test;
import java.util.List;
public class SensitivityDescription {
private String name;
private static List<SensitivityDescription> senRecordList;
public SensitivityDescription(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void setSenRecordList(List<SensitivityDescription> senRecordList) {
SensitivityDescription.senRecordList = senRecordList;
}
public static List<SensitivityDescription> getSenRecordList() {
return senRecordList;
}
}
Xml config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="first" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="first" />
</bean>
<bean id="second" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="second" />
</bean>
<bean id="third" class="com.sopovs.moradanen.test.SensitivityDescription">
<constructor-arg name="name" value="third" />
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="com.sopovs.moradanen.test.SensitivityDescription.setSenRecordList" />
<property name="arguments">
<list>
<ref bean="first" />
<ref bean="second" />
<ref bean="third" />
</list>
</property>
</bean>
</beans>
And test:
package com.sopovs.moradanen.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:test.xml")
public class SpringTest {
#Test
public void test() {
assertEquals(3, SensitivityDescription.getSenRecordList().size());
}
}
Spring way of thinking does not play well with your approach.
But you can work around this.
Add a public setter for senRecordList for SensitivityDescription.
Add default constructor
public class SensitivityDescription {
private final String measureId;
...
private static List <SensitivityDescription> senRecordList = new ArrayList<SensitivityDescription> ();
public SensitivityDescription(String measureId,..) {
...
}
/** new code */
public SensitivityDescription() {super();}
public void setSenRecordList(List<SensitivityDescription> senRecordList) {
SensitivityDescription.senRecordList = senRecordList;
}
}
Instance the bean once, that way the list will be injected to your field.
<bean class="...SensitivityDescription">
<property name="senRecordList">
<util:list value-type="...SensitivityDescription">
<bean class="...SensitivityDescription">
<constructor-arg name="name" “measureId”
<value>id1</value>
</constructor-arg>
<constructor-arg name="name" "sensName"
<value>name1</value>
</constructor-arg>
...
</bean>
<bean class="...SensitivityDescription">
<constructor-arg name="name" "measureId"
<value>id2</value>
</constructor-arg>
<constructor-arg name="name" "sensName"
<value>name2</value>
</constructor-arg>
...
</bean>
</util:list>
</property>
</bean>
If this is not a legacy code and you can change it, I suggest defining a singleton for those values and not a static field. Spring will like it better.

Resources