Rollback in MyBatis using JDBC (no Spring, no containers) - mysql

I've seen all sorts of posts on using Spring and MyBatis with transactions, but I'm facing a problem with rollbacks not working with plain old JDBC.
My ( test / throwaway) code is pretty simple : I open a session, insert a rec, throw an error on purpose and rollback the transaction. However, it always commits.
public static void main (String[] args){
//-- omitted for brevity
try {
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sess = sqlSessionFactory.openSession(false);
BillsMapper mapper = sess.getMapper(BillsMapper.class);
BillState billState = new BillState();
billState.setBillId(-1);
billState.setLastName("TESTER");
billState.setFirstName("TESTER");
mapper.insert(billState);
logger.info("Post insert: key = {}", billState.getBillId());
if(1 == 1)
throw new RuntimeException("Error Thrown on purpose...testing rollback ");
sess.commit();
}catch(Exception e){
logger.error("Error: {}", e);
sess.rollback();
}finally{
sess.close();
logger.info("Finito!");
}
}
The logs show:
DEBUG | (BaseJdbcLogger.java:145) - ==> Preparing: insert into bills (users_userId, refId, firstName, ...
DEBUG | (BaseJdbcLogger.java:145) - ==> Parameters: 67(Integer), 67-120530180328(String), TESTER(String), ...
DEBUG | (BaseJdbcLogger.java:145) - <== Updates: 1
INFO | (TestAction.java:50) - Post insert: key = 2478
ERROR | (TestAction.java:56) - Error: {} java.lang.RuntimeException: Error Thrown on purpose...testing rollback at com.s2stest.TestAction.main(TestAction.java:53)
DEBUG | (JdbcTransaction.java:79) - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (PooledDataSource.java:344) - Returned connection 924748027 to pool.
Note the resetting of autocommit before closing the connection.... Would resetting autcommit before closing the SqlSession cause my rolled-back transaction to be committed? If so, is this a bug? Has anyone gotten JDBC working with transactions? I need it for testing, and I'd value some help. Right now, no transactions can be rolled back.
I've looked at the MyBatis source, and it indeed calls resetAutocommit before closing the connection. I'm using MySQL 5.6 and mysql-connector-java-5.1.36.jar for the driver if someone has a workaround that they've found.
--- UPDATE ---
mybatis-config.xml is as follows:
<?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>
<settings>
<setting name="logImpl" value="SLF4J" />
</settings>
<typeAliases>
<package name="com.ship2storage.domain" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mytestDb?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="--shhh!!--" />
<property name="password" value="--shhh!!--" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ship2storage/db/maps/BillsMapper.xml" />
</mappers>
</configuration>

OK, I've found the answer by digging deeper into my setup. It seems that the MySQL storage engine I installed for my test DB is ISAM. ISAM does not support transactions. I switched to InnoDB using the following SQL tidbit, and transactions now work with JDBC:
ALTER TABLE bills ENGINE=InnoDB;
I haven't tried this, but it looks like you can also do this temporarily too:
SET default_storage_engine=InnoDB;
Hopefully this will help someone. The code/config posted above works.

Related

Unable to commit against JDBC Connection

I am using springboot to connect to a mysql database. Please find my configuration below
spring.datasource.url=jdbc:<connection-url>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.min-idle=15
Api code
#CrossOrigin(origins = "*", allowedHeaders = "*")
#GetMapping(value = "/validateuser/{consumerName}")
#Transactional
public Boolean valiadateuser(#PathVariable String consumerName) {
LOGGER.info("Inside validateuser -1");
ConsumerName user = consumerRepository.findByName(consumerName);
LOGGER.info("Inside validateuser -2 :::: " + user);
if (user != null) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
Below is my exception
org.springframework.orm.jpa.JpaSystemException: Unable to commit against JDBC Connection; nested exception is org.hibernate.TransactionException: Unable to commit against JDBC Connection
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:353) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:538) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:665) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:370) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at com.server.controller.SubscribeController$$EnhancerBySpringCGLIB$$14f090fd.subscribeTopic(<generated>) [classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
Got the answer
updated the resource.properties
spring.datasource.url=jdbc:<connection-url>
spring.datasource.username=<username>
spring.datasource.password=<password>
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
I was experiencing the same exception on my Spring / Postgres stack. Basically, the DB can not return/commit all the rows that match your query in time.
It can be fixed by creating indexes on the columns used in the particular query. This speeds the query up.
CREATE INDEX index_redflag_person
ON redflag_person (firstname, alias,lastname,address,birthplace);
I use Spring and Hibernate and PostgreSQL for practice, got the similar exception:
org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction;
nested exception is org.hibernate.TransactionException:
Unable to commit against JDBC Connection] with root cause
org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.
my hibernate.prop has some config below
hibernate.dialect=org.hibernate.dialect.PostgreSQL10Dialect
hibernate.connection.handling_mode=DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT
packages.to.scan=org.practice.dao.entity
It's weird bcs the default hibernate.connection.autocommit value in hibernate 5.6 is false
After a whole day search, I could not find the same error on the internet, finally I figured it out: somehow I added hibernate.connection.handling_mode in my config file, remove it(the default is fine) and the app works as expected
so maybe check the config and use the simplest param would help someone else

EJB/Hibernate does not access MySQL Database

I'm trying to learn how to work with JavaEE/EJB and database persistence, I have a basic example where I want to save a String to a database via input field and read the list of saved items.
I have a MySQL server installed on localhost (V5.7 Community Edition) and my test server is WildFly 10.1.0 (via Eclipse). The whole project is an EAR container containing a Web and EJB Subproject.
I am using container managed transactions, as I understand it, transactions are automatically created when a method is called and flushed/committed as soon as the method exits.
The problem is, that no data is ever written to the actual database. But no errors are thrown either. I assume, the entity manager caches all supposed saves and directly reads them back on select, without even checking the database. As such, when I restart the server, nothing remains. Also, when I look into mysql db directly, nothing is there either (even while wildfly server is running, directly after supposed insert). I also tried adding some rows to db table directly, but select does not "see" them either.
As a result, it seemed to me that the database is not even accessed, despite it being configured in the persistence.xml. I tried to remove connection url/username/password there and it actually made no difference, the entity manager still throws no errors and everything seems to work. So where exactly is it saving the data and what do I have to change so that it accesses the supplied mysql database instead?
Handler (in Web Project):
#ManagedBean(name = "handlerBean")
#SessionScoped
public class HandlerBean {
#EJB
private TodoWorkerBeanRemote worker;
private String input;
public void add() {
if (input.compareTo("") != 0) {
TodoBean item = new TodoBean();
item.setText(input);
worker.saveItem(item);
input = "";
}
}
...
Session Bean / Transaction container (in EJB project)
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class TodoWorkerBean implements TodoWorkerBeanRemote {
#PersistenceContext(unitName = "EnterpriseTestEJB")
private EntityManager entityManager;
public TodoWorkerBean() {
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) // does not help
public void saveItem(TodoBean item) {
// entityManager.joinTransaction(); <- does not help
entityManager.persist(item); // tried .merge() as well
// entityManager.flush(); <-does not help
}
...
Entity Bean (in EJB project)
#Entity
#Table(name = "todobean")
#NamedNativeQueries({
#NamedNativeQuery(name = "TodoBean.getItems", query = "select * from todobean", resultClass = TodoBean.class),
#NamedNativeQuery(name = "TodoBean.clearItems", query = "delete from todobean") })
public class TodoBean implements Serializable {
private Integer id;
private String text;
...
persistence.xml (tried with hibernate.cfg.xml as well, no difference)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EnterpriseTestEJB">
<class>de.dianasalsa.ejb.TodoBean</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/feedback" /> // not used
<property name="hibernate.connection.username" value="root" /> // not used
<property name="hibernate.connection.password" value="root" /> // not used
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" /> // tried "create" as well
</properties>
</persistence-unit>
</persistence>
Log:
....
15:42:59,602 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 66) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'EnterpriseTest.ear/EnterpriseTestEJB.jar#EnterpriseTestEJB'
15:42:59,952 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 65) WFLYCLINF0002: Started client-mappings cache from ejb container
15:42:59,973 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 66) HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
15:43:00,102 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 66) Envers integration enabled? : true
15:43:00,101 INFO [org.jboss.as.protocol] (management I/O-1) WFLYPRT0057: cancelled task by interrupting thread Thread[management-handler-thread - 3,5,management-handler-thread]
15:43:00,604 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 66) HHH000228: Running hbm2ddl schema update
15:43:00,617 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:00,619 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:01,499 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 83) Mojarra 2.2.13.SP1 20160303-1204 für Kontext '/EnterpriseTestWeb' wird initialisiert.
15:43:02,379 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 83) WFLYUT0021: Registered web context: /EnterpriseTestWeb
15:43:02,414 INFO [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "EnterpriseTest.ear" (runtime-name : "EnterpriseTest.ear")
15:43:02,515 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 9581ms - Started 879 of 1127 services (422 services are lazy, passive or on-demand)
15:43:18,799 INFO [org.jboss.ejb.client] (default task-2) JBoss EJB Client version 2.1.4.Final
15:43:32,763 INFO [stdout] (default task-3) Hibernate:
15:43:32,763 INFO [stdout] (default task-3) /* insert de.dianasalsa.ejb.TodoBean
15:43:32,763 INFO [stdout] (default task-3) */ insert
15:43:32,763 INFO [stdout] (default task-3) into
15:43:32,763 INFO [stdout] (default task-3) todobean
15:43:32,763 INFO [stdout] (default task-3) (text)
15:43:32,763 INFO [stdout] (default task-3) values
15:43:32,764 INFO [stdout] (default task-3) (?)
15:43:32,786 INFO [stdout] (default task-3) Hibernate:
15:43:32,786 INFO [stdout] (default task-3) /* TodoBean.getItems */ select
15:43:32,786 INFO [stdout] (default task-3) *
15:43:32,787 INFO [stdout] (default task-3) from
15:43:32,787 INFO [stdout] (default task-3) todobean
sorry for my english...
you need to configure a JNDI name "jta-data-source", and say with "hibernate.hbm2ddl.auto" create new relations, like this example:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EnterpriseTestEJB"
transaction-type="JTA">
<jta-data-source>java:jboss/datasources/some-name</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
wildfly has a "namesever" for that you work with the JNDI name to access from your annotation like "#PersistenceContext".
And in Wildfly at selfe you must configure a new MySql connection with that JNDI name.
For MySql connection download the jdbc driver and upload it to WildFly.
https://dev.mysql.com/downloads/connector/j/5.1.html
Inser MySqgl jdbc Driver
The connection will named with the JNDI name (java:jboss/datasources/some-name).
Add new MySql Connection (1)
Add new MySql Connection (2)
When you run your programm in Wildfly the programm will look over the JNDI name in wildfly for your MySql connection.
If you would like to look an example code i have one from my study here:
https://gitlab.com/Java_Project/JavaEE2.0
I'll hope it fixe your problem.

hibernate closing connections or not?

My code is below. Possibly I am using it many times in similar manner, i.e in simple words, I am managing the session and transaction this way:
List<Login> users= null;
try{
session=HibernateUtil.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
users=session.createQuery("from Login").list();
tx.commit();
}catch(Exception e){System.out.println("commit exception:"+e);
try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);}
}finally{if(session!=null && session.isOpen()){session.close();}}
return users;
Now, when I first run the database service(using MySQL) and check from command prompt using this query ...
show status like 'Conn%';
... the result is:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 2 |
+---------------+-------+
When I start my application and use it. After opening few pages and querying the same thing. I am getting the connections as 6, I have even seen above 20.
Now I would like to know that hibernate is closing the connections or not?
I am handling all the transactions that way, I cross checked and dint see any code block without closing the session.
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/shareapp
</property>
<property name="connection.username">pluto</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
hibernateutil class
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Login.class);
config.addAnnotatedClass(FilesInfo.class);
config.addAnnotatedClass(FilesShare.class);
config.configure("hibernate.cfg.xml");
// new SchemaExport(config).create(true,true);
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Thanks!
The "Connections" status variable just refers to the
The number of connection attempts (successful or not) to the MySQL server,
and not the number of active connections.
Here is the link: http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Connections
To get the number of open connections, check the 'Threads_connected' variable, documented at
http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Threads_connected

JPA + MySQL: After Timeout --> use a local Connection

as our connection is very unstable we have decided to switch to our local read-only database if a query times out.
But here is my problem: I do not get an exception when javax.persistence tries to query:
// Attribute
EntityManagerFactory entityManagerFactory;
EntityManager manager;
entityManagerFactory = Persistence
.createEntityManagerFactory("org.hibernate.tutorial.jpa");
manager = entityManagerFactory.createEntityManager();
try {
Query query = manager.createQuery(String.format(
"SELECT u FROM User u WHERE u.id = '%s'", 116));
User user = (User) query.getSingleResult();
manager.refresh(user);
System.out.println(user.getUsername());
} catch (org.hibernate.QueryTimeoutException ex) {
throw new QueryTimeoutException("timeout");
}
}
This is just a test to demonstrate my problem.
What am I missing?
Mysql: mysql-connector-java-5.1.16-bin.jar
JPA: javax.persistence_2.0.3.v201010191057.jar
Hibernate:
115 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
124 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.7.Final
126 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
129 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
132 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
208 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.6.7.Final
persistence.xml:
<properties>
<property name="hibernate.hbm2ddl.auto" value="valide"/>
<property name="hibernate.connection.url" value="jdbc:mysql:///database?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="user"/>
<property name="hibernate.connection.password" value="pass"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.query.timeout" value="1"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
Thank you
Tobias
Solution:
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://server/database", "user", "pass");
Every time I want to start a query I test if the Connection is alive:
if (connection.isValid(1)) {
return true;
} else {
throw new NoConnectionException();
You may not be seeing a timeout because some DBs don't support that feature.
"javax.persistence.query.timeout query timeout in milliseconds
(Integer or String), this is a hint used by Hibernate but requires
support by your underlying database."
See http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html for more details.
I'd be inclined to switch to the read only all the time if you can't guarantee a reliable connection.

mongo db - can't initiate Mongo with replica set

I'm using version spring-data-mongo version 1.0.0.M4 - the latest version to this date.
I defined my bean like this:
<bean id="mongoOps" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="my_mongo" />
</bean>
<mongo:mongo id="mongo" replica-set="host1:27017,host2:27018,host3:27019" >
<mongo:options... />
</mongo:mongo>
But when I start my server it try's to connect to the default host and port on my computer, this happens because in MongoFactoryBean line 93 it says:
if (host == null) {
logger.debug("Property host not specified. Using default configuration");
mongo = new Mongo();
} else {...
//do all the stuff I want to be done...
}
So how can I define my Mongo with a replica-set without setting the host?
Thank you!
Shouldn't the bean declaration be like this - possibly you're missing the ID of the replicaset bean?
<mongo:mongo id="replicaSetMongo" replica-set="host1:27017,host2:27018"/>