spring data mongo repository is null - java

I am writing a standalone java program that call spring data repository for manging enities. I am using mongo db for persistence. I am following stackoverflow posts and some projects from github but when I run my program it fails since the repository is null. I am not expert in spring so it would be helpful if someone could show me the issue with the posted program.
Application-context.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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo id="mongo" host="monopolyvm3" port="27017" />
<mongo:db-factory dbname="test" mongo-ref="mongo" />
<mongo:db-factory id="mongoDbFactory" dbname="cloud"
mongo-ref="mongo" />
<bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey"><null/></constructor-arg>
</bean>
<bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
<property name="writeConcern" value="SAFE" />
</bean>
<context:component-scan base-package="com.xxxx"></context:component-scan>
<mongo:repositories base-package="com.xxxx.yyyy" />
Repository
public interface SlpRepository extends MongoRepository<Slp, Long> {
}
main program
public class App {
#Autowired
static
SlpRepository slpRepository;
public static void main(String[] args) {
ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
Slp slp = new Slp();
slp.setClientCount(100000L);
slp.setPolicyName("testing");
slp.setSlpName("slp_testing");
slpRepository.save(slp);
}
}
Object to store
------------------
#Document(collection="slps")
public class Slp implements Serializable {
private Long slpId;
private String slpName;
private String policyName;
private Long clientCount;
}
.....all getters and setters
JFYI..I tried to save object using mongotemplate and it works well.

The problem in this example is that you create the context in your App class but never get a handle to the repository from the application context. You cannot auto wire into the same class that holds the application context. What you can try is the get the instance of the repository from the context (i.e ctx.getBean(SlpRepository.class)).

Related

Integrate Spring Socials (Facebook) with Spring MVC XML Based

I have a working spring mvc webapp and it is xml based so i have to use the same procedures and not "pure java configs".
I'm trying to integrate facebook sign in to my app and i have tried to follow many tutorials but couldn't manage to make them work.
Here is one of my tries: (https://spring.io/guides/gs/accessing-facebook/)
EDIT:
My XML is now this:
<?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:facebook="http://www.springframework.org/schema/social/facebook"
xmlns:twitter="http://www.springframework.org/schema/social/twitter"
xmlns:social="http://www.springframework.org/schema/social"
xmlns:linkedin="http://www.springframework.org/schema/social/linkedin"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/social/facebook http://www.springframework.org/schema/social/spring-social-facebook.xsd
http://www.springframework.org/schema/social/linkedin http://www.springframework.org/schema/social/spring-social-linkedin.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/social/twitter http://www.springframework.org/schema/social/spring-social-twitter.xsd
http://www.springframework.org/schema/social http://www.springframework.org/schema/social/spring-social.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="connectionFactoryLocator"
class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<bean class="org.springframework.social.facebook.connect.FacebookConnectionFactory">
<constructor-arg value="${facebook.clientId}" />
<constructor-arg value="${facebook.clientSecret}" />
</bean>
</list>
</property>
</bean>
<bean id="usersConnectionRepository"
class="org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository">
<constructor-arg ref="dataSource" />
<constructor-arg ref="connectionFactoryLocator" />
<constructor-arg ref="textEncryptor" />
</bean>
<bean id="connectionRepository" factory-method="createConnectionRepository"
factory-bean="usersConnectionRepository" scope="request">
<constructor-arg value="#{request.userPrincipal.name}" />
<aop:scoped-proxy proxy-target-class="false" />
</bean>
<bean class="org.springframework.social.connect.web.ConnectController">
<!-- relies on by-type autowiring for the constructor-args -->
</bean>
<bean class="org.springframework.social.connect.web.ConnectController">
<!-- relies on by-type autowiring for the constructor-args -->
<property name="applicationUrl" value="${application.url}" />
</bean>
<facebook:config app-id="962223610477458" app-secret="b7dfec28b08ac4e8c2a09cbac4662c15" app-namespace="setelog_selectandwin" />
</beans>
HomeController:
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
private Facebook facebook;
private ConnectionRepository connectionRepository;
#Inject
public HomeController(Facebook facebook, ConnectionRepository connectionRepository) {
this.facebook = facebook;
this.connectionRepository = connectionRepository;
}
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
if (connectionRepository.findPrimaryConnection(Facebook.class) == null) {
return "redirect:/connect/facebook";
}
model.addAttribute("facebookProfile", facebook.userOperations().getUserProfile());
PagedList<Post> feed = facebook.feedOperations().getFeed();
model.addAttribute("feed", feed);
return "facebook/hello";
}
}
NOW the error is
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'scopedTarget.connectionFactoryLocator' is defined
If I remove th facebook:config tag it gives me the following error because there is no such bean:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.social.facebook.api.Facebook] found for dependency: expected at least 1 bean which
Any suggestions?
You need not add spring's facebook interface as class in your xml. Instead create FacebookConnectionFactory using your facebook client id and secret using xml or java code.
#Configuration
public class SocialConfig implements SocialConfigurer {
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
cfConfig.addConnectionFactory(new FacebookConnectionFactory(
env.getProperty("facebook.clientId"),
env.getProperty("facebook.clientSecret")));
}
...
}
or
Using Spring Social Facebook’s XML configuration namespace:
<facebook:config app-id="${facebook.clientId}"
app-secret="${facebook.clientSecret}"
app-namespace="socialshowcase" />
Refer : Spring Social Facebook Reference
taken from spring social quickstart example. Probably you cant inject it by yourself, instead you have to use factory-like method:
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Facebook facebook() {
return connectionRepository().getPrimaryConnection(Facebook.class).getApi();
}
it needs other dependencies, no point to copy-paste them all here. Take a look at: https://github.com/spring-projects/spring-social-samples/blob/master/spring-social-quickstart/src/main/java/org/springframework/social/quickstart/config/SocialConfig.java

Import own enum converter

I have a class which contains enum property.
public class Car{
private UserAction action;
//getters setters
}
And I want to save/read it from/to Mongo db. I am using Spring framework.
SpringConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="dbName" />
<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey"><null/></constructor-arg>
</bean>
<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
</bean>
<!--CODE BELOW CASES PROBLEMS-->
<mongo:mapping-converter id="mappingConverter">
<mongo:custom-converters>
<mongo:converter>
<bean class="myapp.mongo.converters.UserActionReadConverter"/>
</mongo:converter>
<mongo:converter>
<bean class="myapp.mongo.converters.UserActionWriteConverter"/>
</mongo:converter>
</mongo:custom-converters>
</mongo:mapping-converter>
</beans>
UserActionReadConverter.java
package myapp.mongo.converters;
import myapp.model.UserAction;
import com.mongodb.DBObject;
import org.springframework.core.convert.converter.Converter;
public class UserActionReadConverter implements Converter<DBObject, UserAction> {
public UserAction convert(DBObject source) {
String val = (String) source.get("value");
return (val.equals("PROCESSED_BY_USER" ) ? UserAction.PROCESSED_BY_USER : UserAction.UNPROCESSED_BY_USER);
}
}
UserActionWriteConverter.java
package myapp.mongo.converters;
import myapp.model.UserAction;
import org.springframework.core.convert.converter.Converter;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class UserActionWriteConverter implements Converter<UserAction, DBObject> {
public DBObject convert(UserAction userAction) {
DBObject dbo = new BasicDBObject();
dbo.put("value", userAction.toString());
return dbo;
}
}
operations initialisation
...
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
this.operations = (MongoOperations) ctx.getBean(beamName);
...
I have no idea, how to map converters into config .xml properly. It returns me error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
The second question is. I want to convert simple enum, to do that I use a "supporting identificator" value. Can I transform enum without using it, that data in database will be stores as {car.userAction : "data value" } instead of {car.value.userAction : "data value" } .Thanks.
Missing validator library.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.3.Final</version>
</dependency>

Iterating list in spring

Is there a way to iterate list or map in spring? I am not able to find any references for this online.
This is what I defined-
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<util:list id="myList" value-type="java.lang.String">
<value>foo</value>
<value>bar</value>
</util:list>
<bean id="bean1" class="com.StaticClass" factory-method="createObject">
<constructor-arg value="foo" />
</bean>
<bean id="bean2" class="com.StaticClass" factory-method="createObject">
<constructor-arg value="bar" />
</bean>
<bean id="myMap" class="java.util.HashMap">
<constructor-arg index="0" type="java.util.Map">
<map key-type="java.lang.Integer" value-type="java.lang.Float">
<entry key="foo" value-ref=bean1 />
<entry key="bar" value-ref=bean2 />
</map>
</constructor-arg>
</bean>
Instead of creating multiple bean objects, I want to iterate over this list and create a map, using following logic-
for (String m : myList) {
myMap.put(m, MyStaticFactory.createObject(m));
}
Can I do this in Spring?
How about using spring #Configuration (see explanation in this link) instead of spring XML?
#Configuration
public class MySpringContext {
#Bean(name="myMap")
public Map<String, StaticClass> getMyMapBean() {
// I'm not sure where you create 'm' but if that's a bean you can inject it to the class and use it.
for (String m : myList) {
myMap.put(m, MyStaticFactory.createObject(m));
}
}
}
#Configuration classes are a way to define your beans programatically instead of XMLs which gives you much more flexibility to do whatever you want.
Something like this maybe:
public class MyMapBean extends HashMap {
public MyMapBean(List<String> beanNames) {
for(name: beanNames) put(name, MyStaticFactory.createObject(name));
}
}
and then in application context:
<bean id="myMap" class="MyMapBean">
<constructor-arg index="0" value-ref="myList" />
</bean>

Trying to Get JPA/Hibernate working with REST -- TransactionRequiredException: No Transaction is in progress error

I've been trying to get Hibernate / JPA working with my simple Spring 3.2 REST application.
Hibernate/JPA successfully create my table in MySQL, but the transaction fails once it gets into the Repository -- saying no transaction is in progress. I'm really out of my element here and not even sure how to troubleshoot this as it seems most of the code is happening behind the scenes in xml.
Any help much appreciated.
UPDATE -- jpaContext.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.saltcitywifi"></context:component-scan>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="create" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<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/salt_city_wifi?autoReconnect=true" />
<property name="username" value="wifi_admin" />
<property name="password" value="password" />
</bean>
Controller:
#Controller
public class HotSpotController {
#Autowired
private HotSpotService hotSpotService;
#RequestMapping(value = "/hotSpots", method = RequestMethod.GET)
public #ResponseBody
List<HotSpot> getHotSpots() {
hotSpotService = new HotSpotServiceImpl();
List<HotSpot> spots = hotSpotService.getAllHotSpots();
return spots;
}
#RequestMapping(value = "/hotSpot", method = RequestMethod.POST)
public #ResponseBody
HotSpot addHotSpot(#RequestBody HotSpot hotSpot) {
hotSpotService.addHotSpot(hotSpot);
return hotSpot;
}
}
Service:
#Service("hotSpotService")
#Transactional
public class HotSpotServiceImpl implements HotSpotService {
#Autowired
private HotSpotRepository hotSpotRepository;
private AtomicLong counter = new AtomicLong();
public List<HotSpot> getAllHotSpots() {
List<HotSpot> spots = new ArrayList<HotSpot>();
HotSpot spot;
for (int i = 0; i < 10; i++) {
spot = new HotSpot("location " + i, "http://www.url" + i + ".com",
counter.incrementAndGet());
spots.add(spot);
}
return spots;
}
public HotSpot getHotSpotById(long id) {
HotSpot spot = new HotSpot("New Spot", "New Url", id);
return spot;
}
#Transactional
public HotSpot addHotSpot(HotSpot hotSpot) {
return hotSpotRepository.addHotSpot(hotSpot);
}
}
#Repository("hotSpotRepository")
public class HotSpotRepositoryImpl implements HotSpotRepository {
#PersistenceContext
private EntityManager em;
public HotSpot addHotSpot(HotSpot hotSpot) {
em.persist(hotSpot);
em.flush();
return hotSpot;
}
}
OK I finally figured out what was going on here:
I have two component scanners, one for my controllers in servlet-config.xml and one for my JPA stuff in jpaContext.xml.
They were both scanning basically my whole application:
<context:component-scan base-package="com.saltcitywifi" />
When I forced the component scanner for controllers to only look in the controller package:
<context:component-scan base-package="com.saltcitywifi.controller" />
All of a sudden my requests worked and were processed in the database.
I can only assume since my servlet-config.xml configuration only contains:
<context:component-scan base-package="com.saltcitywifi.controller" />
<mvc:annotation-driven />
That Spring was somehow letting servlet-config.xml register the JPA beans, so the transactional annotations weren't being picked up. This is still confusing to me, so if anyone can help explain why this occurs that would be very helpful. I might just ask another stack overflow question on this subject.

MyBatis+Redis caching. Is it possible?

I have a small project just to check how everything works. I've implemented the usage of MyBatis and the project just works, I was able to retrieve some data from a database. But right now I need the result to be cached for the 2nd time. I've already tested redis to be an embedded cache manager in spring(cache abstraction: http://static.springsource.org/spring-data/data-redis/docs/current/reference/html/redis.html and liker here: http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html). I've implemented everything and cached one method. BUT!!!
I can't really understand was it cached or not. The first time when I marked up the method, redis said, that there are changes to the db and saved it.. but then I changed the key, and nothing changed... How do I understand, that the method was cached or not?? I will put some code here for you to understand what I'm doing.
Spring Context:
<?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:cache="http://www.springframework.org/schema/cache"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:redis="http://www.springframework.org/schema/redis"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
">
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="file:src/main/java/schema.sql" />
<jdbc:script location="file:src/main/java/test-data.sql" />
</jdbc:embedded-database>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven />
<context:component-scan base-package="com.mycompany.mybatisproject.serviceimpl" />
<!-- Define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="file:src/main/java/com/mycompany/mybatisproject/persistence/ContactMapper.xml" />
<property name="typeAliasesPackage" value="com.mycompany.mybatisproject.data" />
</bean>
<!-- classpath*:com/mycompany/mybatisproject/persistence/*.xml -->
<!-- Scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mycompany.mybatisproject.persistence" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="localhost" p:port="6379" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
c:template-ref="redisTemplate" />
</beans>
Implementation of service:
#Service("contactService")
#Repository
#Transactional
public class ContactServiceImpl implements ContactService {
private Log log = LogFactory.getLog(ContactServiceImpl.class);
#Autowired
private ContactMapper contactMapper;
#Cacheable("pacan")
#Transactional(readOnly=true)
public List<Contact> findAll() {
List<Contact> contacts = contactMapper.findAll();
return contacts;
}
}
ContactMapper.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mycompany.mybatisproject.persistence.ContactMapper">
<resultMap id="contactResultMap" type="Contact">
<id property="id" column="ID" />
<result property="firstName" column="FIRST_NAME" />
<result property="lastName" column="LAST_NAME" />
<result property="birthDate" column="BIRTH_DATE" />
</resultMap>
<select id="findAll" resultMap="contactResultMap">
SELECT ID, FIRST_NAME, LAST_NAME, BIRTH_DATE
FROM CONTACT
</select>
And finally the main class:
public class App {
private static void ListContacts(List<Contact> contacts) {
System.out.println("");
System.out.println("Listing contacts without details: ");
for (Contact contact : contacts) {
System.out.println(contact);
System.out.println();
}
}
public static void main( String[] args ) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("file:src/main/java/app-context.xml");
ctx.refresh();
ContactService contactService = ctx.getBean("contactService", ContactService.class);
List<Contact> contacts;
contacts = contactService.findAll();
ListContacts(contacts);
}
}
Thanks in advance.
You're caching invocation of ContactServiceImpl.findAll method. For test purpose you can add System.out.println("Method invoked") in findAll method. If the cache works the body of findAll method should be invoked only once, next invocations should read value (result) from cache so you shouldn't see "Method invoked" on console.
Don't use Spring 3.1.0.M1 documentation it is different from 3.1.0.RELEASE: http://static.springsource.org/spring/docs/3.1.0.RELEASE/spring-framework-reference/html/cache.html.

Categories