I have a test like the following
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:META-INF/spring/testDataSpringContext.xml" })
#Transactional
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
public class AgenceDAOTest {
#Autowired
private AgenceDAO mAgenceDAO;
#Test
#DatabaseSetup(value = "/META-INF/db-test/sampleData.xml", type = DatabaseOperation.REFRESH)
public void listAgences() {
List<AgenceVO> vListeAgences = mAgenceDAO.getAgences();
Assert.notNull(vListeAgences);
Assert.notEmpty(vListeAgences);
List<AgenceVO> vListeAgencesTrouvees = ListUtils.select(vListeAgences, new Predicate<AgenceVO>() {
public boolean evaluate(AgenceVO pAgenceVO) {
return pAgenceVO.getLibelle().startsWith("TEST_");
}
});
Assert.notNull(vListeAgencesTrouvees);
Assert.notEmpty(vListeAgencesTrouvees);
Assert.isTrue(vListeAgencesTrouvees.size() == 1);
}
}
Everything seems ok because in the log I see the following:
[TransactionalTestExecutionListener: startNewTransaction];Began transaction (1): transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager#39d325]; rollback [true]
[DbUnitTestExecutionListener: setupOrTeardown];Executing Setup of #DatabaseTest using REFRESH on /META-INF/db-test/sampleData.xml
[AbstractTableMetaData: getDataTypeFactory];Potential problem found: The configured data type factory 'class org.dbunit.dataset.datatype.DefaultDataTypeFactory' might cause problems with the current database 'Oracle' (e.g. some datatypes may not be supported properly). In rare cases you might see this message because the list of supported database products is incomplete (list=[derby]). If so please request a java-class update via the forums.If you are using your own IDataTypeFactory extending DefaultDataTypeFactory, ensure that you override getValidDbProducts() to specify the supported database products.
[SQL: logStatement];select this_.AGC_ID as AGC1_0_0_, this_.AGC_CP as AGC2_0_0_, this_.AGC_ADR1 as AGC3_0_0_, this_.AGC_COMMUNE as AGC4_0_0_, this_.AGC_ADR2 as AGC5_0_0_, this_.AGC_LIBELLE as AGC6_0_0_, this_.AGC_MAIL as AGC7_0_0_, this_.AGC_NOM as AGC8_0_0_, this_.AGC_TEL as AGC9_0_0_ from FTN_AGENCE_AGC this_
[DbUnitTestExecutionListener: verifyExpected];Skipping #DatabaseTest expectation due to test exception class java.lang.IllegalArgumentException
[TransactionalTestExecutionListener: endTransaction];Rolled back transaction after test execution for test context [[TestContext#cdd54e testClass = AgenceDAOTest, locations = array<String>['classpath:META-INF/spring/testDataSpringContext.xml'], testInstance = com.edf.ftn.data.admin.AgenceDAOTest#16f2067, testMethod = listAgences#AgenceDAOTest, testException = java.lang.IllegalArgumentException: [Assertion failed] - this collection must not be empty: it must contain at least 1 element]]
The dbunit dataset is loaded after the transaction is created, so dataset data should be visible in select, but it is not visible. When the select is executed records in the dataset are not retrieved.
To verify if the dataset is being loaded I've tried to insert a duplicate key and an exception is launched, so I supose that de dataset is loaded correctly.
The datasource and transactionmanager configuration is:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#${ip}:${port}:${schema}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
The DAO is not configured as transactional, because in the application it isn't. But I have also tried to make it transactional, and the result is the same.
I do not understand why in this line:
List<AgenceVO> vListeAgences = mAgenceDAO.getAgences();
The dataset is not visible.
Solution found
I fixed the problem by using TransactionAwareDataSourceProxy
Finally I've got the following configuration for datasource:
<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#${ip}:${port}:${schema}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg ref="dbcpDataSource" />
</bean>
<bean id="futunoaTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
Related
We are able to fetch access token using attached code snapshot but didn't find any way to set connection timeout as we do with spring restTemplate.Is there any way to set a connection timeout with OAuth2RestTemplate.
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="detail" ref="resourceDetails" />
</bean>
<bean id="context" class="org.springframework.security.oauth2.client.DefaultOAuth2ClientContext">
<constructor-arg name="accessTokenRequest" ref="request" />
</bean>
<bean id="request" class="org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest"/>
<bean id="resourceDetails" class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails"/>
A little late to the party, but in case you're wondering how to do this with springboot, this is a way:
#Bean
protected OAuth2RestTemplate oauth2RestTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(oAuthDetails());
oAuth2RestTemplate.setRequestFactory(clientHttpRequestFactory);
return oAuth2RestTemplate;
}
#Bean
protected ClientHttpRequestFactory requestFactory() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000); //timeout in milliseconds
requestFactory.setReadTimeout(10000); //timeout in milliseconds
return requestFactory;
}
Where oAuthDetails() is a method that reads the oauth configuration properties, similar to this:
#Bean
#ConfigurationProperties("path.to.your.oauth.properties.on.yml")
protected ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
If I'm right, the way you give the connection timeout to the Spring RestTemplate as a constructor argument is through giving a ClientHttpRequestFactory as an argument to the constructor
RestTemplate(ClientHttpRequestFactory requestFactory)
Using for example the HttpComponentsClientHttpRequestFactory, one can set the connection timeout to the RestClient in XML as follows
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</constructor-arg>
</bean>
RestTemplate also offers a way to set the requestFactory property through a setter, which it inherits from InterceptingHttpAccessor, and in fact the constructor itself seems to use that setter to set the requestFactory given as constructor argument.
Thus, you can set the requestFactory for the OAuth2RestTemplate through the setter. In XML:
<bean id="oauth2RestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg name="resource" ref="resourceDetails" />
<constructor-arg name="context" ref="context" />
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
Or, in your case, you can for example give your class com.test.Provider a constructor argument requestFactory and then use that to set the request factory in the OAuth2RestTemplate as follows:
XML:
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="resourceDetails" ref="resourceDetails" />
<constructor-arg name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</constructor-arg>
</bean>
And in your code set
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resourceDetails, this.context);
restTemplate.setRequestFactory(this.requestFactory);
String tokenString = restTemplate.getAccessToken().getValue();
after setting the value of this.requestFactory in the constructor.
PS. I would prefer to create a single OAuth2RestTemplate for the entire class as a private field and reuse it in that class, unless you have a reason to create a new one for each request. You could create it in the constructor, as you are giving the context and details as constructor arguments, or then in a post-construct/init-method. Or even give it as a constructor-argument or as a property to your class in the XML, in case the context and resourceDetails are not used outside the restTemplate.
EDIT
After doing some more research, it seems that the problem might be harder than I thought. OAuth2RestTemplate uses an AccessTokenProvider to get the access tokens, by default it uses a chain of AccessTokenProviders through a instance of AccessTokenProviderChain in order to support the different types of grant types. It seems that each of these uses their own RestTemplate to send the requests to obtain the access token. Unfortunately, it seems that OAuth2RestTemplate doesn't offer a simple way to set the requestFactory of the default AccessTokenProviders' restTemplates.
So, if the solution that I proposed above is not working (which I suspect), I would use the following approach which I believe to work.
All the default AccessTokenProviders in Spring Security Oauth2 extend the class OAuth2AccessTokenSupport, which also is the class that creates the internal RestTemplate. Fortunately, this class offers a setter to set the requestFactory of the internal RestTemplate. So, one can create for example an instance of a ClientCredentialsAccessTokenProvider and give set the requestFactory through the setRequestFactory(...) method. In XML:
<bean id="clientCredentialsAccessTokenProvider class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider">
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
For some reason the OAuth2RestTemplate doesn't offer a way to access the default AccessTokenProviders, but one can set them through the setAccessTokenProvider(AccessTokenProvider accessTokenProvider) setter. To replicate the original default behaviour of the OAuth2RestTemplate, one would have to give an instance of a AccessTokenProviderChain, together with four default AccessTokenProviders and set their requestFactories. However, as you know that the accessed resource is of type ClientCredentialsResourceDetails, it suffices to set a single ClientCredentialsAccessTokenProvider in the setAccessTokenProvider(...) setter and set the requestFactory of the ClientCredentialsAccessTokenProvider.
So we would get the following code:
XML:
<bean id="bean" class="com.test.Provider">
<constructor-arg name="context" ref="context" />
<constructor-arg name="resourceDetails" ref="resourceDetails" />
<constructor-arg name="accessTokenProvider" ref="clientCredentialsAccessTokenProvider" />
</bean>
<bean id="clientCredentialsAccessTokenProvider" class="org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider">
<property name="requestFactory">
<bean id="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="2000" />
<property name="readTimeout" value="10000" />
</bean>
</property>
</bean>
And in your code, set the AccessTokenProvider:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resourceDetails, this.context);
restTemplate.setAccessTokenProvider(this.accessTokenProvider);
String tokenString = restTemplate.getAccessToken().getValue();
after setting the value of this.accessTokenProvider in the constructor. If you decide to create the OAuth2RestTemplate in the XML, you can write
<bean id="oauth2RestTemplate" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg name="resource" ref="resourceDetails" />
<constructor-arg name="context" ref="context" />
<property name="accessTokenProvider" ref="clientCredentialsAccessTokenProvider" />
</bean>
where the bean "clientCredentialsAccessTokenProvider" is defined as above.
Hope that this works.
One issue with above solution is that ClientCredentialsAccessTokenProvider uses a bit enhanced requestFactory:
private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory() {
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
...
}
...
};
So in order to preserve the original functionality you should set up the same implementation of the factory.
I have mysql server in linux server. It contains 5 database for 5 different clients. so far, I have created 5 tomcat instances to deploy 5 war based on client and accessing database from servelet.xml file like below,
client1 instance war :
<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/client1" />
<property name="username" value="rootuser" />
<property name="password" value="pswd" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" >
<constructor-arg ref="dataSource"/>
</bean>
client2 instance war :
<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/client2" />
<property name="username" value="rootuser" />
<property name="password" value="pswd" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" >
<constructor-arg ref="dataSource"/>
</bean>
Config class :
public class JdbcRepository {
#Autowired
#Qualifier("jdbcTemplate")
protected JdbcTemplate jdbcTemplate;
#Autowired
#Qualifier("namedParameterJdbcTemplate")
protected NamedParameterJdbcTemplate namedParameterJdbcTemplate ;
#Autowired
#Qualifier("dataSource")
private DataSource dataSource; //mysqlSource;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public Long findMemberIdByUserName(String username) {
try{
String sql = "SELECT userLoginId FROM user WHERE userName = ?";
Long id = jdbcTemplate.queryForObject(sql, new Object[]{username}, Long.class);
return id;
}
catch(Exception e){
return 0l;
}
}
But now I want to create single instance and deploy single war for all clients and access the database based on user login. Like below,
<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/{DBBasedOnLoginUser}" />
<property name="username" value="rootuser" />
<property name="password" value="pswd" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" >
<constructor-arg ref="dataSource"/>
</bean>
How to achieve this?
So, you want to communicate with different databases depending upon some condition.
Changing datasource connection url runtime
This is exactly what you need.
I'm integrate spring with hibernate , I'm using dropwizard configaration files as : persistence file have the configuration files are in resources folder no issue with loading xml files. There is issue with found table .
persistence.xml file as :
<persistence-unit name="bfm" transaction-type="RESOURCE_LOCAL" >
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.bcits.parkingmanagement.model.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/anuj" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</persistence-unit>
</persistence>
In spring application config xml as : there I show only hibernate configuration
<context:annotation-config />
<context:component-scan base-package="com.bcits.parkingmanagement.model" />
<jdbc:embedded-database id="dataSource" type="HSQL" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:spring/persistence.xml" />
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
Table User missing
javax.persistence.PersistenceException: [PersistenceUnit: bfm] Unable to build EntityManagerFactory
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 18 more
Caused by: org.hibernate.HibernateException: Missing table: user
Please anyone help me how can I resolve this error. I want to configuration of spring with hibernate.I thing it is connect to database but can't found table. Table name and colume name exactly same. Database name also correct and no issue with username and password of database .
User model is: Here User is model name and user is table which have two column one is user_id and user_name. Issue is that i had used user instead of User in query. Because User is model name and user is table name .Correct model is given below
#NamedQueries({
#NamedQuery( name="getUserName" , query="select name from User")
})
#Entity
#Table( name ="user")
public class User {
#Id
#Column( name="user_id")
private int id;
#Column( name="user_name")
private String name;
//getter setter
}
HINT : My hosting tomcat system provides only 20 db connections
My working project in localhsot
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
This worked good in localhost, but in production it run for a while and Exception : "user has allready max no of connection".
After many google
I used c3p0
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
This worked in localhost, but same problem in production server
Hint: I think some config in c3p0 can solve this. Please help me with you suggestion (My hosting provides only 20 connections)
Also i tried tomcat
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSourceFactory">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="20"/>
</bean>
The above tomcat code is wrong and will not work - because wrong property (I know that). How to set this for my production use(only 20 connections)
If you know how to use tomcat pool please help us.
I also used bonecp
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="idleConnectionTestPeriod" value="60"/>
<property name="idleMaxAge" value="240"/>
<property name="maxConnectionsPerPartition" value="10"/>
<property name="minConnectionsPerPartition" value="5"/>
<property name="partitionCount" value="1"/>
<property name="acquireIncrement" value="5"/>
<property name="statementsCacheSize" value="1000"/>
<property name="releaseHelperThreads" value="3"/>
</bean>
This worked in localhost but same problem in production "user has to many connections".
I also tried apache-dbcp
As per tomcat 7 documentation - dbcp is no longer and tomcat will be bundled with pool. Even though i used dbcp and i cannot run my program. (I added only one jar and error was some class not found during project run)
As per my own idea :
I think above mentioned settings will be problem. Please help me with your suggestions. I'm not using hibernate up to now because of heavy weight. If hibernate can solve this problem please let us know.
EDITED
Currently I'm using this code. Is this code correct to my use(20 connection)
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}" p:password="${jdbc.password}"
p:acquireIncrement="1"
p:checkoutTimeout="1"
p:idleConnectionTestPeriod="5"
p:maxIdleTime="5"
p:maxIdleTimeExcessConnections="1"
p:maxPoolSize="20" p:maxStatements="0" p:maxStatementsPerConnection="0"
p:minPoolSize="1"
p:numHelperThreads="100"
p:overrideDefaultUser="${jdbc.username}" p:overrideDefaultPassword="${jdbc.password}"
p:propertyCycle="3"
p:testConnectionOnCheckin="true"
p:unreturnedConnectionTimeout="5" />
DAO code :
#Repository
public class TutorialsDAOImpl implements TutorialsDAO {
//---
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
#Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
//---
#Override
public List<TutorialsCategory_vo> getTutorialsCategory() {
sql = "SELECT * FROM `tutorials_category` ORDER BY `slug` ASC;";
List<TutorialsCategory_vo> vo = null;
try {
vo = this.jdbcTemplate.query(sql, new Object[]{}, tutorialsCategory_mapper);
} catch (Exception e) {
log.log(Level.SEVERE, null, e);
}
return vo;
}
These are the codes i'm using. If there is any error/corrections pls correct me.
Edited (for Arun P Johny 's question)
My current project url.
I updated my current code above.
This is my final c3p0 settings:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}" p:password="${jdbc.password}"
p:acquireIncrement="1"
p:checkoutTimeout="3000"
p:idleConnectionTestPeriod="5"
p:maxIdleTime="3"
p:maxIdleTimeExcessConnections="1"
p:maxPoolSize="20" p:maxStatements="20000" p:maxStatementsPerConnection="1000"
p:minPoolSize="1"
p:numHelperThreads="1000"
p:overrideDefaultUser="${jdbc.username}" p:overrideDefaultPassword="${jdbc.password}"
p:propertyCycle="3"
p:statementCacheNumDeferredCloseThreads="1"
p:testConnectionOnCheckin="true"
p:unreturnedConnectionTimeout="7" />
This works fine, but taking more time(1 or 2 secounds - not more than 3 secounds).
I also checked this code by shutting down mysql. My program waited up to, i start mysql. This is good. This code waits for all db connections to complete and out put correctly.
Can we make this settings even faster? Hint: my server provides only 20 connections.
If you provide a correct answer i'll make it as right answer, after checking.
I am doing unit testing and I expect that all data committed to the MySQL database will be rolled back... but this isn't the case. The data is being committed, even though my log was showing that the rollback was happening. I've been wrestling with this for a couple days so my setup has changed quite a bit, here's my current setup.
LoginDAOTest.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:web/WEB-INF/applicationContext-test.xml", "file:web/WEB-INF/dispatcher-servlet-test.xml"})
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class UserServiceTest {
private UserService userService;
#Test
public void should_return_true_when_user_is_logged_in ()
throws Exception
{
String[] usernames = {"a","b","c","d"};
for (String username : usernames)
{
userService.logUserIn(username);
assertThat(userService.isUserLoggedIn(username), is(equalTo(true)));
}
}
ApplicationContext-Text.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:p="http://www.springframework.org/schema/p"
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-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/******"/>
<property name="username" value="*****"/>
<property name="password" value="*****"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="userService" class="Service.UserService">
<property name="userDAO" ref="userDAO"/>
</bean>
<bean id="userDAO" class="DAO.UserDAO">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>/himapping/User.hbm.xml</value>
<value>/himapping/setup.hbm.xml</value>
<value>/himapping/UserHistory.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
I have been reading about the issue, and I've already checked to ensure that the MySQL database tables are setup to use InnoDB. Also I have been able to successfully implement rolling back of transactions outside of my testing suite. So this must be some sort of incorrect setup on my part.
Any help would be greatly appreciated :)
The problem turned out to be that the connection was auto-committing BEFORE the transaction could be rolled back. I had to change my dataSource bean to include a defaultAutoCommit property:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="Ecosim07"/>
<property name="defaultAutoCommit" value="false" />
</bean>
For me defaultAutoCommit and #Transactional didn't help. I had to change db type to InnoDB
Another way to fix your problem:
Instead of using:
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
, which creates a MyISAM table by default, hence not supporting transactions
Try using
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
, which creates InnoDB tables, and thus supports transactions.
This must be used
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#TestExecutionListeners({ TransactionalTestExecutionListener.class })
#Transactional
TransactionalTestExecutionListener contains isRollback() which rollbacks the
transaction after the test method.
I hope I am right and that this is a simple one. You are missing the #Transactional annotation on your test class. This means that the test method itself isn't run in a transaction and thus there is nothing to roll back. Hope this helps.