I got this exception when I executed this app:
public class MainApp {
private static ApplicationContext context = null;
static SqlSession session = null;
public static void main(String[] args) throws IllegalArgumentException {
try {
context = new FileSystemXmlApplicationContext(
"src/main/webapp/WEB-INF/applicationContext.xml");
session = (SqlSession) context.getBean("sqlSession");
OrderMapper orderMapper = session.getMapper(OrderMapper.class);
int orderQuantity = orderMapper.getAllOrder().size();
System.out.println("Order quantity: " + orderQuantity);
session.commit();
session.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Here is my OrderMapper interface:
public interface OrderMapper {
public List<Order> getAllOrder();
}
OrderMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thonglm1.spring.mappers.OrderMapper">
<resultMap id="result" type="order">
<result property="orderId" column="cartid" />
<result property="type" column="type" />
<result property="saleId" column="saleId" />
<result property="status" column="status" />
<result property="info1" column="info1" />
<result property="info2" column="info2" />
<result property="info3" column="info3" />
</resultMap>
<select id="getAllOrder" resultMap="result">
select cartId, type,
info1
from TRAIN_ORDER;
</select>
</mapper>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.21.8.62:1521:SHESVDEV" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="src/main/webapp/WEB-INF/mybatis-config.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.thonglm1.spring.mappers" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
mybatis-config.xml
?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.thonglm1.spring.domain.Order" alias="order" />
</typeAliases>
<mappers>
<package name="com.thonglm1.spring.mappers" />
</mappers>
</configuration>
And finally, the exception I got:
java.lang.IllegalArgumentException: Mapped Statements collection does
not contain value for
com.thonglm1.spring.mappers.OrderMapper.getAllOrder at
org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:672)
at
org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:507)
at
org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:500)
at
org.apache.ibatis.binding.MapperMethod.setupCommandType(MapperMethod.java:240)
at
org.apache.ibatis.binding.MapperMethod.(MapperMethod.java:71)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:39)
at $Proxy6.getAllOrder(Unknown Source) at
MainApp.main(MainApp.java:21)
And 1 more thing, since I quite new to this, is there any bad practices in my code ? Or anything I could improve ? Please feel free to comment, I'd really appreciate it.
Where have you specified the mapper XML location? You could add it in sqlSessionFactory's property mapperLocations. Since you are using maven. I believe it is better to move the mapper XML file to a folder inside resources directory. When You add more number of XML files it will be easier to maintain. I think the below folder structure would make sense as all the related stuff are grouped together with all your JDBC related stuff under one package with subpackages as domain, mappers, service interfaces and service interface implementation.
In this case since all the configurations go inside WEB-INF/classes directory during compile/packaging, which is also a classpath, this application configuration should hold good.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.21.8.62:1521:SHESVDEV" />
<property name="username" value="test" />
<property name="password" value="test" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:sqlmap/*.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.thonglm1.spring.mappers" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
And the mybatis-config.xml, by default all the aliases in the domain package will be class name with the first letter being smaller.
?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.thonglm1.spring.domain" />
</typeAliases>
</configuration>
If the package cannot be read you can try adding the resource directly:
?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="com.thonglm1.spring.domain.Order" alias="order" />
</typeAliases>
<mappers>
<mapper resource="folderWhereIsXMLMapperIssaved/orderMapper.xml" />
</mappers>
</configuration>
Related
I am having trouble configuring JPA global type mappings via the package-info.java file, which looks like this:
#TypeDefs({
#TypeDef(
typeClass = MyCustomUserType.class,
defaultForType = MyType.class
)
})
package my.entity.package;
import...
My spring configuration file looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.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:spring-configured />
<context:annotation-config />
<context:component-scan base-package="my.package"/>
<context:property-placeholder location="classpath:/my.properties" />
<bean id="testDataSource" class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.ibm.db2.jcc.DB2Driver"
p:url="jdbc:db2://${database.host}:50000/${database.dbname}:currentSchema=I0071DBA;"
p:username="${database.username}"
p:password="${database.password}"
p:initialSize="5"
p:maxActive="10">
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="testDataSource" />
<property name="persistenceProviderClass" value="org.hibernate.jpa.HibernatePersistenceProvider"/>
<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.DB2Dialect"/>
<entry key="hibernate.default_schema" value="MySchema"/>
<entry key="hibernate.cache.use_query_cache" value="false"/>
<entry key="hibernate.cache.use_second_level_cache" value="false"/>
</map>
</property>
<property name="packagesToScan" value="my.entity.package"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
I believe the packagesToScan property is being used, because all my entity classes are configured into the EntityManagerFactory. Only the package-info.java file is not being used. Any suggestions for configuring the package-info.java file into the EntityManagerFactory?
I am trying to access a property file containing db configurations in a Maven + Spring project.
I get following error:
Cannot load JDBC driver class '${db_driver}'
My Property file is placed in src/resources folder.
Below is the tag to load property files:
<bean id="dbPropertyReader"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="locations">
<value>classpath:${appenv.deployment}.properties</value>
</property>
</bean>
Following tag uses properties loaded:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="url" value="${db_url}" />
<property name="driverClassName" value="${db_driver}" />
<property name="username" value="${db_username}" />
<property name="password" value="${db_password}" />
</bean>
Below are contents of properties file:
#JDBC Properties
db_driver=com.mysql.jdbc.Driver
db_url=jdbc\:mysql\://hostname\:3306/xxx_dbxxx?useUnicode\=true
db_username=abcdefgh
db_password=ijklmnopq
db_removeabadoned=true
db_initialsize=1
db_maxactive=2
${appenv.deployment} is a VMArgument set as follows:
-Dappenv.deployment=development
I have checked, this value is getting populated properly.
I am getting following line in logs:
Found key 'appenv.deployment' in [systemProperties] with type [String] and value 'development'
Then after this I am also getting following:
Loading properties file from class path resource [development.properties]
But some how, the values are not getting loaded.
Spring-Datasource.xml
<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="dbPropertyReader"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="locations">
<value>classpath:${appenv.deployment}.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="url" value="${db_url}" />
<property name="driverClassName" value="${db_driver}" />
<property name="username" value="${db_username}" />
<property name="password" value="${db_password}" />
<property name="initialSize" value="${db_initialsize}" />
<property name="maxActive" value="${db_maxactive}" />
</bean>
<bean id="firstConfigDataFromDB" class="org.apache.commons.configuration.DatabaseConfiguration">
<constructor-arg type="javax.sql.DataSource" ref="dataSource" />
<constructor-arg index="1" value="tablename1" />
<constructor-arg index="2" value="propertyname2" />
<constructor-arg index="3" value="propertyvalue2" />
</bean>
<bean id="firstConfigDataFromDBFactory"
class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<constructor-arg ref="firstConfigDataFromDB" />
</bean>
<!-- DB Properties Initialization -->
<bean id="firstConfigurationPlaceHolder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="2" />
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="properties" ref="firstConfigDataFromDBFactory" />
</bean>
<bean id="secondConfigurationFromDB"
class="org.apache.commons.configuration.DatabaseConfiguration">
<constructor-arg type="javax.sql.DataSource" ref="dataSource" />
<constructor-arg index="1" value="tablename2" />
<constructor-arg index="2" value="propertyname2" />
<constructor-arg index="3" value="propertyvalue2" />
</bean>
<bean id="secondConfigurationFromDBFactory"
class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<constructor-arg ref="secondConfigurationFromDB" />
</bean>
<!--
Error Map Initialization
Subtype of org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
-->
<bean id="secondConfigurationPlaceHolder"
class="com.application.SecondConfigurationPlaceHolder">
<property name="order" value="3" />
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="properties" ref="secondConfigurationFromDBFactory" />
</bean>
</beans>
Generic.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<!-- Enable annotation scanning -->
<context:annotation-config/>
<!-- Initialise connection to Database -->
<import resource="Spring-Datasource.xml"/>
<!-- Initialize mail connection -->
<import resource="Spring-Mail.xml"/>
<!-- Inject database connection to DAO -->
<import resource="Spring-DAO.xml"/>
<!-- Other Beans Below -->
</beans>
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<import resource="generic.xml" />
<bean id="applicationBean" class="com.application.ApplicationBean" scope="singleton" >
<property .. />
<property .. />
</bean>
</beans>
I am loading applicationContext.xml with following statement in code:
`appContext = new ClassPathXmlApplicationContext("applicationContext.xml");`
applicationContext.xml imports generic.xml.
generic.xml imports Spring-DataSource.xml.
have you added this to your application context file
<context:property-placeholder location="Path for .properties file"/>
add this line before the beans
I have a simple Hello World example that passes a Map to Camel and displays the values to the console via Log4J. I want to expand this example to render this map in JSON by adding the Jackson library to my Camel applicationContext.xml
First I tried adding the following XML tags to my applicationContext.xml (as specified at
http://camel.apache.org/json.html under "Using JSON in Spring DSL")
<camel:dataFormats>
<camel:json id="jack" library="Jackson"/>
</camel:dataFormats>
But when I add this to my applicationContext.xml, and run my Java code I get the following XmlBeanDefinitionStoreException message:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'dataFormats'. One of '{"http://camel.apache.org/schema/
spring":route}' is expected.
Moving these tags inside or outside of my camelContext yields the same error (just a longer list of URLs when inside the camelContext).
Is there something else I need to specify in my ApplicationContext.xml?
Here is my current applicationContext.xml:
UPDATED: The following xml now works. Had to move the location of the dataFormats XML tags.
<?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:camel="http://camel.apache.org/schema/spring"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:component-scan base-package="sample" />
<context:annotation-config />
<camel:camelContext id="HelloWorldContext">
<camel:dataFormats>
<camel:json id="jack" library="Jackson"/>
</camel:dataFormats>
<camel:route>
<camel:from
uri="timer://hello.world.request.timer?fixedRate=true&period=10000" />
<camel:to uri="log:hello.world.request?level=INFO?showAll=true" />
<camel:bean ref="helloWorld" />
<camel:to uri="log:hello.world.response?level=INFO?showAll=true" />
</camel:route>
</camel:camelContext>
<bean id="jms" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="configuration" ref="jmsConfig" />
</bean>
<bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration">
<property name="connectionFactory" ref="jmsConnectionFactory" />
<property name="transacted" value="false" />
<property name="concurrentConsumers" value="1" />
</bean>
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost" />
<property name="redeliveryPolicy" ref="redeliveryPolicy" />
<property name="prefetchPolicy" ref="prefetchPolicy" />
</bean>
<bean id="prefetchPolicy" class="org.apache.activemq.ActiveMQPrefetchPolicy">
<property name="queuePrefetch" value="5" />
</bean>
<bean id="redeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
<property name="maximumRedeliveries" value="1" />
<property name="backOffMultiplier" value="2" />
<property name="initialRedeliveryDelay" value="2000" />
<property name="useExponentialBackOff" value="true" />
</bean>
</beans>
The dateFormats and json elements are part of the camel namespace. You need to specify that
<camel:dataFormats>
<camel:json id="jack" library="Jackson"/>
</camel:dataFormats>
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.
I have a simple Java application and I'm trying to integrate Hibernate in Spring but it seems that the Spring configuration file can't find the *.hbm.xml (the mapping resource):
I have a file named persistence-context.xml that I use it as a Spring config file and I have the following bean declared:
org.hibernate.dialect.MySQLDialect
But is being thrown the exception:
java.io.FileNotFoundException: class path resource [pool.hbm.xml] cannot be opened because it does not exist
I've even tried giving the mapping resources property an absolute path value. It doesn't work.
Thank you!
UPDATE:
My Spring conf file:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value='jdbc:mysql://localhost/bestofs_seinfeld' />
<property name="username" value="root" />
<property name="password" value="futifuti825300" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources" value="pool.hbm.xml" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="mySessionFactory"/>
</property>
</bean>
<bean id="voteDao" class="bestofs.persistence.HibernatePoolDao">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
</property>
</bean>
</beans>
And my pool.hbm.xml is:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="bestofs.persistence.PoolBean" table="sein_pool">
<id name="idVote" column="ID_Vote">
<generator class="assigned"/>
</id>
<property name="IdActor">
<column name="ID_Actor"/>
</property>
<property name="IdUser">
<column name="ID_User"/>
</property>
<property name="IdSession">
<column name="ID_Session"/>
</property>
</class>
</hibernate-mapping>
And both configuration files are on the same folder.
If you are giving absolute path to the file location on disk (e.g. c:/mapings/pool.hbm.xml), it will not work, because it searches for mapping on a class path. Mapping file should be inside your jar or in IDE class path.
If you are using Tomcat + web project, you should create resource folder inside your src folder and put your mapping files there it will be equal to:
<property name="mappingResources">
<list>
<value>object.hbm.xml</value>
</list>
</property>
Hope it helps.
Use
<property name="mappingResources" value="pool.hbm.xml" />
and put pool.hbm.xml in the root of your classpath. I.e. your bestofs.persistence.PoolBean will be in a directory structure like <somewhere>/bestofs/persistence/PoolBean.class. The mapping file should be inside <somewhere>, right alongside bestofs.
That's all you need to do unless you have some strange ClassLoader magic happening.