I have tried this:
<util:list id="list1">
<value>foo#bar.com</value>
<value>foo1#bar.com</value>
</util:list>
<util:list id="list2">
<value>foo2#bar.com</value>
<value>foo3#bar.com</value>
</util:list>
<util:map id="emailMap" value-type="java.util.List">
<!-- Map between String key and List -->
<entry key="entry1" value-ref="list1" />
<entry key="entry2" value-ref="list2" />
...
</util:map>
calling this map like this
<bean id="myBean" class="com.sample.beans">
<property name="mapArray" ref="emailMap" />
</bean>
I have written a test case to see if this being populated, but where this is being called i have added a Map.isEmpty() and it always returns true, meaning map is not getting populated. Could you please guide me?
public class beans()
{
Map<String, List<String>> mapArray= new HashMap<String,ArrayList<String>>();
public void setMapArray(Map<String, List<String>> map)
{
this.mapArray= map;
}
public Array<String, List<String>> getMapArray()
{
return mapArray;
}
public void makeObject(String key)
throws Exception {
System.out.println(mapArray.isEmpty());
}
}
The test case calls a function makeobject. Here the value returned is true always
TEST:
public class testing{
#Test(enabled=true)
public void call1() throws {
ApplicationContext context = new ClassPathXmlApplicationContext("call.the.xml");
BeanFactory factory = context;
KeyedPoolFactory test = (KeyedPoolFactory) factor.getBean("myBean");
// CALLED MakeObject here. So the make object is being called for sure since it returning true for isEmpty();
}
Related
I am using dozer version 5.5.1. And i want to configure my custom converter so i have this
import org.dozer.DozerConverter;
import com.example.movies.api.models.response.ClientResponseDTO;
public class MyCustomConverter
extends DozerConverter<ClientResponseDTO, String> {
public MyCustomConverter() {
super(ClientResponseDTO.class, String.class);
}
#Override
public String convertTo(ClientResponseDTO source, String destination) {
return "ClientResponseDTO Converted to string!";
}
#Override
public ClientResponseDTO convertFrom(String source, ClientResponseDTO destination) {
return new ClientResponseDTO();
}
}
Which i am loading with Spring like this:
#Bean
public Mapper dozerBeanMapper() {
DozerBeanMapper mapper = new DozerBeanMapper();
List<CustomConverter> converters = new ArrayList<>();
converters.add(new MyCustomConverter(ClientResponseDTO.class, String.class));
mapper.setCustomConverters(converters);
return mapper;
}
Then, i have this usage:
#Autowired Mapper mapper;
...
ClientResponseDTO clientResponseDTO = clientService.getClient(id);
String conversion = this.mapper.map(clientResponseDTO, String.class);
And the custom converter is never being called. Do you know why is that ? Regards!
Refer to dozer documentation you should add mapping to bean description.
Eg.
<bean id="org.dozer.Mapper" class="org.dozer.DozerBeanMapper">
<property name="mappingFiles">
<list>
<value>systempropertymapping1.xml</value>
<value>dozerBeanMapping.xml</value>
<value>injectedCustomConverter.xml</value>
</list>
</property><property name="customConvertersWithId">
<map>
<entry key="CustomConverterWithId" ref="configurableConverterBeanInstance1" />
<entry key="CustomConverterWithId2" ref="configurableConverterBeanInstance2" />
</map>
</property>
</bean>
I am wondering how to implement batch operations with my insert statements using MyBatis 3 & Spring 3?
For example, here is what is currently being done:
spring.xml:
<bean id="jndiTemplateDatasource" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">${context.factory}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateDatasource"/>
<property name="jndiName" value="${connectionpool.jndi}"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test" />
</bean>
MyService.xml:
<insert id="insertMyRecord" parameterType="com.test.MyRecord" >
insert into ... // code removed
</insert>
MyService.java:
public interface MyService {
public void insertMyRecord (MyRecord);
}
MyController.java:
#Controller
public class MyController {
#Autowired
private MyService myService;
#Transactional
#RequestMapping( .... )
public void bulkUpload (#RequestBody List<MyRecord> myRecords) {
for (MyRecord record : myRecords) {
myService.insertMyRecord(record);
}
}
}
Disclaimer: That is just pseudo code for demonstration purposes
So what can I do to turn that into a batch process?
Ideally I want to be able to do it with least "intrusion" into code, i.e. use annotations more preferred, but if not possible what is the next best thing?
Also, this needs to be configured just for this one service, not for everything in the project.
The accepted answer above doesn't actually get you batch mode for MyBatis. You need to choose the proper Executor via ExecutorType.BATCH. That is either passed as a parameter to SqlSession.openSession in standard MyBatis API or, if using MyBatis-Spring, as an option to the SqlSessionTemplate. That is done via:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH" />
</bean>
There is nothing else that needs to be done.
This is running and tested example ...
Update multiple rows using batch (ibatis + java )
In this ex. I am updating attending count from table with respective to partyid.
public static int updateBatch(List<MyModel> attendingUsrList) {
SqlSession session = ConnectionBuilderAction.getSqlSession();
PartyDao partyDao = session.getMapper(PartyDao.class);
try {
if (attendingUsrList.size() > 0) {
partyDao.updateAttendingCountForParties(attendingUsrList);
}
session.commit();
} catch (Throwable t) {
session.rollback();
logger.error("Exception occurred during updateBatch : ", t);
throw new PersistenceException(t);
} finally {
session.close();
}
}
Model class where variable is defined :
public class MyModel {
private long attending_count;
private String eid;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public long getAttending_count() {
return attending_count;
}
public void setAttending_count(long attending_count) {
this.attending_count = attending_count;
}
}
party.xml code
Actual query where batch execute
<foreach collection="attendingUsrList" item="model" separator=";">
UPDATE parties SET attending_user_count = #{model.attending_count}
WHERE fb_party_id = #{model.eid}
</foreach>
Interface code here
public interface PartyDao {
int updateAttendingCountForParties (#Param("attendingUsrList") List<FBEventModel>attendingUsrList);
}
Here is my batch session code
public static synchronized SqlSession getSqlBatchSession() {
ConnectionBuilderAction connection = new ConnectionBuilderAction();
sf = connection.getConnection();
SqlSession session = sf.openSession(ExecutorType.BATCH);
return session;
}
SqlSession session = ConnectionBuilderAction.getSqlSession();
I'm not sure I understand the question fully correct but I will try to give you my thoughts.
For making the single service I would recommend to generify the service interface:
public void bulkUpload (#RequestBody List<T> myRecords)
Then you can check the type of the object and call the propper mapper repository.
Then you can generify it more by creating a common interface:
public interface Creator<T> {
void create(T object);
}
and extend it by your mapper interface:
public interface MyService extends Creator<MyRecord>{}
Now the most complicated step: you get the object of a particular type, see what exact mapper implements the Creator interface for this class (using java reflection API) and invoke the particular method.
Now I give you the code I use in one of my projects:
package com.mydomain.repository;
//imports ...
import org.reflections.Reflections;
#Repository(value = "dao")
public class MyBatisDao {
private static final Reflections REFLECTIONS = new Reflections("com.mydomain");
#Autowired
public SqlSessionManager sqlSessionManager;
public void create(Object o) {
Creator creator = getSpecialMapper(Creator.class, o);
creator.create(o);
}
// other CRUD methods
#SuppressWarnings("unchecked")
private <T> T getSpecialMapper(Class<T> specialClass, Object parameterObject) {
Class parameterClass = parameterObject.getClass();
Class<T> mapperClass = getSubInterfaceParametrizedWith(specialClass, parameterClass);
return sqlSessionManager.getMapper(mapperClass);
}
private static <T, P> Class<? extends T> getSubInterfaceParametrizedWith(Class<T> superInterface, Class<P> parameterType) {
Set<Class<? extends T>> subInterfaces = REFLECTIONS.getSubTypesOf(superInterface);
for (Class<? extends T> subInterface: subInterfaces) {
for (Type genericInterface : subInterface.getGenericInterfaces()) {
if (!(genericInterface instanceof ParameterizedType)) continue;
ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class<?> && ((Class<?>) rawType).isAssignableFrom(superInterface)) {
for (Type type: parameterizedType.getActualTypeArguments()) {
if (type instanceof Class<?> && ((Class<?>) type).isAssignableFrom(parameterType)) {
return subInterface;
}
}
}
}
}
throw new IllegalStateException(String.format("No extension of %s found for parametrized type %s ", superInterface, parameterType));
}
}
Warning! This approach can have bad performance impact so use it in non-performance-critical actions
If you want bulk insert I would recommend to use mybatis foreach for bulk insert as described here.
If you think you don't want to write sql for every type of objects you better use Hibernate or any other advanced ORM. MyBatis is just an SQL mapping interface.
I'm trying to add some Spring configuration to an existing utility class. It doesn't seem to work and I'm not sure why (my first time using these Spring options, I'm not even sure I'm doing it correctly).
The class in question
#Configurable(autowire=Autowire.BY_NAME, preConstruction=true)
public class DataUtility
{
private static final DataUtility INSTANCE = new DataUtility();
#Autowired(required=true) //This is the new field and annotation
private Map<String,String> dataFileMapping = new HashMap<String, String>();
public static DataUtility getInstance()
{
return INSTANCE;
}
private DataUtility()
{
//Do a bunch of setup work here
for (String s : dataFileMapping)
{
addDataToCache(dataFileMapping(s))
}
}
The spring config looks like this:
<context:annotation-config/>
<context:spring-configured/>
<bean id="util" class="com.myCompany.DataUtility">
<property name="dataFileMapping">
<map>
<entry key="data1" value="data/file1.dat"/>
<entry key="data2" value="data/file2.dat"/>
<entry key="data3" value="data/file3.dat"/>
</map>
</property>
</bean>
The problem is that when I step through my code in the debugger, I can see that dataFileMapping is empty. I'm not even sure if the spring config is even running.
I think you just need to add getters and setters for dataFileMapping
Also, remember that you can't iterate through the map in the constructor, spring wouldn't have had a chance to set it until after the constructor executes.
In addition to this, you can't make your constructor private and expect spring to be able to instantiate it.
The root of your problem is that you seem to be using a static reference INSTANCE to access the object. Spring is making a bean named 'util' and setting it up with your data, but that isn't becoming the object that INSTANCE points to. The initialization of static fields happens when the class is first loaded, long before spring ever gets a chance to create and inject beans.
You can sort of fake it like this, but of course attempts to access instance before bean initialization will fail:
#Configurable(autowire=Autowire.BY_NAME, preConstruction=true)
public class DataUtility
{
private static final DataUtility INSTANCE = null;
#Autowired(required=true) //This is the new field and annotation
private Map<String,String> dataFileMapping = new HashMap<String, String>();
public static DataUtility getInstance()
{
return INSTANCE;
}
public postInit()
{
INSTANCE = this;
//Do a bunch of setup work here
for (String s : dataFileMapping)
{
addDataToCache(dataFileMapping(s))
}
}
<bean id="util" class="com.myCompany.DataUtility" init-method="postInit">
<property name="dataFileMapping">
<map>
<entry key="data1" value="data/file1.dat"/>
<entry key="data2" value="data/file2.dat"/>
<entry key="data3" value="data/file3.dat"/>
</map>
</property>
</bean>
How to conditionally initialization a class via spring?
If some condtion is true then i want one argument to be passed else some other
argument
<bean id="myFactory" class="Factory">
if something then
<constructor-arg>
<util:map>
<!-- configure your map here, or reference it as a separate bean -->
<entry key="java.lang.String" value="key">....</entry>
</util:map>
</constructor-arg>
else
<constructor-arg>
<util:map>
<!-- configure your map here, or reference it as a separate bean -->
<entry key="java.lang.String" value="key">....</entry>
</util:map>
</constructor-arg>
</bean>
How?
Spring Expression Language might do the trick for you. link
You can do it exactly the way that you have specified. Define a FactoryBean this way, say for eg. For generating a Customer Bean:
public class CustomFactoryBean implements FactoryBean<Customer>{
private int customProperty;
public int getCustomProperty() {
return customProperty;
}
public void setCustomProperty(int customProperty) {
this.customProperty = customProperty;
}
#Override
public Customer getObject() throws Exception {
if (customProperty==1)
return new Customer("1", "One");
return new Customer("999", "Generic");
}
#Override
public Class<?> getObjectType() {
return Customer.class;
}
#Override
public boolean isSingleton() {
return true;
}
}
That is basically it, now based on how you inject in th properties of the factory bean, the actual bean instantiation can be controlled in the getObject method above
i just wonder, can i convert uri string to another object type ?
#RequestMapping(value="/key/{keyDomain}", method=RequestMethod.GET)
public String propertyEditor(#PathVariable(value="keyDomain") KeyDomain key, Model model){
model.addAttribute("key", key);
return "propertyEditor";
}
and here my configuration
<beans:bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<beans:property name="customEditors">
<beans:map>
<!-- <beans:entry key="com.template.baseline.domain.KeyDomain" value="com.template.baseline.propertyEditor.KeyPropertyEditor"/> -->
<beans:entry key="com.template.baseline.domain.KeyDomain">
<beans:ref bean="keyDomainPropertyEditor" />
</beans:entry>
</beans:map>
</beans:property>
</beans:bean>
<!-- key domain property editor bean -->
<beans:bean id="keyDomainPropertyEditor" class="com.template.baseline.propertyEditor.KeyPropertyEditor">
<beans:property name="keyDomain">
<beans:bean class="com.template.baseline.domain.KeyDomain" />
</beans:property>
</beans:bean>
and propertyEditor Class :
public class KeyPropertyEditor extends PropertyEditorSupport{
private KeyDomain keyDomain;
/**
* example : 10435
* - 10 will be keyId
* - 435 will be baseOfficeId
*/
#Override
public void setAsText(String text) throws IllegalArgumentException{
KeyDomain keyDomain = new KeyDomain();
keyDomain.setKeyId(Integer.parseInt(text.substring(0,1)));
keyDomain.setBaseOfficeId(Integer.parseInt(text.substring(2,4)));
setValue(keyDomain);
}
#Override
public String getAsText() {
KeyDomain value = (KeyDomain) getValue();
return (value != null ? value.toString() : "");
}
public void setKeyDomain(KeyDomain keyDomain) {
this.keyDomain = keyDomain;
}
}
i thought that i can use Property Editor to convert my URI string become appropriate object type. i already made an implementation and configure CustomEditorConfigurer, but i always get ConversionNotSupportedException.
if i add initBinder at my controller, everything will just fine :
#InitBinder
public void setBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(KeyDomain.class, new KeyPropertyEditor());
}
and i get Warning something like this
WARN : org.springframework.beans.factory.config.CustomEditorConfigurer - Passing PropertyEditor instances into CustomEditorConfigurer is deprecated: use PropertyEditorRegistrars or PropertyEditor class names instead. Offending key [com.template.baseline.domain.KeyDomain; offending editor instance: com.template.baseline.propertyEditor.KeyPropertyEditor#1a271f5
thanks for the answer.
ps : webBindingInitalizer injected on AnnotationMethodHandlerAdapter
<beans:bean id="AnnotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="webBindingInitializer">
<beans:bean class="com.template.baseline.initialize.CustomWebBindingInitializer" />
</beans:property>
</beans:bean>
and Implementation
public class CustomWebBindingInitializer implements WebBindingInitializer {
public CustomWebBindingInitializer(){
System.out.println("******** constructor *********");
}
public void initBinder(WebDataBinder binder, WebRequest request) {
System.out.println("******** initBinder *********");
binder.registerCustomEditor(KeyDomain.class, new KeyDomainPropertyEditor());
}
}
CustomEditorConfigurer has nothing to do with web request data binding.
If you want to register your PropertyEditor globablly, you need to implement WebBindingInitializer and supply AnnotationMethodHandlerAdapter with it:
<bean
class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<proeprty name = "webBindingInitializer">
<bean class = "MyWebBindingInitializer" />
</property>
</bean>
Another option is to implement your conversion logic as a Formatter and configure it via FormattingConversionServiceFactoryBean and <mvc:annotation-driven>, see mvc-showcase sample.