Initialising static list using spring - 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.

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.

Error reading 'nom' on type dao.Etudiant_$$_jvst1a2_0 Hibernate

I want to search on a table by ID , the search work fine , but when hibernate don t find any row it s return this error :
Error reading "nom" on type dao.Etudiant , and sometimes it s return : No row with the given identifier exists:[dao.Etudiant#4]
I want to show nothing when hibernate don t find that ID on the table , need your helps thanks , I m stack my learning, I googled a lot without any solution. this is my code :
Controller :
package controller;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import dao.DaoEtudiant;
import dao.Etudiant;
import service.EtudiantMetier;
#Controller
public class EtudiantController {
#Autowired
EtudiantMetier service;
#RequestMapping("afficherId")
public String afficheId(Model mod,#RequestParam(value="id") Long id)
{
List <Etudiant> ets1=new ArrayList<Etudiant>();
ets1.add(service.chercheEtudiantID(id));
mod.addAttribute("etudiants",ets1);
return "etudiant1";
}
}
Class : Etudiant :
package dao;
import java.util.Date;
public class Etudiant {
private Long idEtudiant;
private String nom;
private String prenom;
private Date dateNaissance;
private String email;
public Etudiant() {
super();
}
public Long getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Long idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Etudiant.hbm.xml:
<?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 Oct 20, 2016 7:42:26 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="dao.Etudiant" table="etudiant">
<id name="idEtudiant">
<column name="ID_ETUDIANT" />
<generator class="native" />
</id>
<property name="nom" column="NOM" />
<property name="prenom" >
<column name="PRENOM" />
</property>
<property name="dateNaissance" >
<column name="DATE_NAISSANCE" />
</property>
<property name="email" >
<column name="EMAIL" />
</property>
</class>
Hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class"> com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/etudes</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop the existing tables and create new one -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.enable_lazy_load_no_trans" >
true
</property>
<!-- Mention here all the model classes along with their package name -->
<mapping resource="dao/Etudiant.hbm.xml"/>
</session-factory>
Etudiantmetierimpl.java:
#Override
public Etudiant chercheEtudiantID(Long idEtudiant) {
Session session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("avant load session");
Etudiant et=session.load (Etudiant.class, idEtudiant);
//Etudiant et=session.get (Etudiant.class, idEtudiant); // presque meme chose que load
System.out.println("apres load session et ");
session.close();
return et;
}
find it finally. I change this line :
Etudiant et=session.load (Etudiant.class, idEtudiant)
to :
Etudiant et=session.get (Etudiant.class, idEtudiant)
doc:
session.load()
• It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
• If no row found , it will throws an ObjectNotFoundException.
session.get()
• It always hit the database and return the real object, an object that represent the database row, not proxy.
• If no row found , it return null.

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?

Autowiring String property through application context

I want to autowire a String bean as below
<bean id="name" class="java.lang.String" autowire="byName">
<constructor-arg value="Aravind"/>
</bean>
<bean id="employee" class="Employee" autowire="byName"/>
public Class Employee
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
When I try to access the name attribute in the employee is null
Employee emp=(Employee)getApplicationContext().getBean("employee");
System.out.println(emp.getName()==null);
It prints true.
Can someone help on this?
You still need to set the property on the Employee somehow.
Setting the name can be done in multiple ways.
XML configuration.
<bean id="employee" class="Employee" autowire="byName">
<property name="name">
<ref bean="name" />
</property>
</bean>
Using #Autowired
public Class Employee {
#Autowired
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
}

Sql is required error Spring StoredProcedure

I am getting property "sql" is required error when i execute below code. can someone help me? i dont know how do i inject Datasource in TestDAO calss so that it works properly.
public class TestDAO extends BaseStoredProcedure
{
final protected Logger logger = Logger.getLogger(this.getClass().getName());
private static final String SPROC_NAME = "dbo.SP1";
#Autowired
private JdbcTemplate jdbcTemplate;
public java.util.ArrayList<IssuerProductResponse> validIssuersProducts(java.util.ArrayList<IssuerProductRequest> issuersProducts)
{
//PARAM MAP set here
//compile SP
HIOSBaseStoredProcedure hiosBaseSP = new HIOSBaseStoredProcedure(jdbcTemplate.getDataSource(),SPROC_NAME,inMap,null,null,null);
//now set parameters
Map<String, Object> result = super.execute(parameters);
System.out.println(result);
return liReponse;
}
}
BaseStoreProcedure class
public class BaseStoredProcedure extends StoredProcedure {
public BaseStoredProcedure() {
super();
// TODO Auto-generated constructor stub
}
/**
*
* #param ds
* #param spname
* #param map
* #param sqlOutKey
* #param returnType
* #param rowmapper
*/
public BaseStoredProcedure (DataSource ds, String spname,
Map<String, Integer> map, String sqlOutKey, Integer returnType,
RowMapper rowmapper) {
super();
setDataSource(ds);
/* resultset has to be declared first over other declare parameters */
if (rowmapper != null) {
declareParameter(new SqlReturnResultSet(sqlOutKey, rowmapper));
}
if (map != null) {
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
Integer value = (Integer) map.get(key);
declareParameter(new SqlParameter(key, value.intValue()));
}
}
/*
* sql out paramter has to be declared based on the order in stored
* procedures, In all our stored procedures we have it after input
* parameters
*/
if (returnType != null) {
declareParameter(new SqlOutParameter(sqlOutKey, returnType
.intValue()));
}
setSql(spname);
compile();
}
}
Spring configuration
<bean id="dao" class="test.dao.TestDAO"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean>
<bean id="baseSP" class="test.dao.BaseStoredProcedure"> </bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value="jdbc:sqlserver://IP:1433;databaseName=DB;" /> <property name="username" value="username" /> <property name="password" value="password" /> <property name="validationQuery" value="SELECT 1" /> <property name="initialSize" value="1"/> <property name="maxActive" value="20"/> </bean>

Resources