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"/>
Related
I am trying to setup Telosys to work with VS Code to generate entities from a MySQL database. But when I type "cdb" to check the connection, it gives the error:
[ERROR] Exception class : TelosysToolsException
[ERROR] Exception message : Cannot connect to the database (SQLException)
I downloaded a MySQL connector from https://dev.mysql.com/downloads/connector/j/ and selected Platform independent as the platform (I didn't see an option for Windows), then moved the mysql-connector-java-8.0.19 driver file to the lib folder under TelosysTools. The following is my databases.dbcfg file:
<databases defaultId="1" maxId="10">
<db id = "1"
name = "MySql80"
driver = "com.mysql.cj.jdbc.Driver"
url = "jdbc:mysql://localhost:3306/MySQL80"
typeName = "MYSQL"
dialect = "org.hibernate.dialect.MySQLDialect"
poolSize = "3">
<property name="user" value="root"/>
<property name="password" value="********"/>
<metadata catalog="" schema="****"
table-name-pattern="%user" table-types="TABLE VIEW"
table-name-exclude="" table-name-include="" />
</db>
</databases>
The problem was that I didn't need the MySQL80 at the end of url. Just url="jdbc:mysql://localhost:3306" works.
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.
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
I'm having problems with my MDB running in JBoss 5.1.2 connecting to a remote standalone HornetQ via JMS. I know the HornetQ is up and running fine as I can connect to it and place/view messages via HermesJMS. However, my actual app does not seem to be able to successfully connect to it.
Here's my #MessageDriven annotation:
#MessageDriven(
messageListenerInterface = MessageListener.class,
activationConfig = {
#ActivationConfigProperty( //type of destination we pull messages from
propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty( //which destination JNDI suffix we pull message from
propertyName = "destination", propertyValue = "queue/inputQueue"),
#ActivationConfigProperty( //how many times to reattempt on service errors
propertyName = "dLQMaxResent", propertyValue = "1"),
#ActivationConfigProperty( //how many seconds to try a reconnect when failure to connect to jms provider
propertyName = "reconnectInterval", propertyValue = "15"),
#ActivationConfigProperty(
propertyName = "providerAdapterJNDI", propertyValue = "java:/RemoteJMSProvider")
}
)
Here's my configuration in my jms-ds.xml file:
<mbean code="org.jboss.jms.jndi.JMSProviderLoader"
name="hornetq:service=MSProviderLoader,name=RemoteJMSProvider,server=remotehost">
<attribute name="ProviderName">RemoteJMSProvider</attribute>
<attribute name="ProviderAdapterClass">org.jboss.jms.jndi.JNDIProviderAdapter</attribute>
<!-- The connection factory -->
<attribute name="FactoryRef">/LocalHornetQConnectionFactory</attribute>
<!-- The queue connection factory -->
<attribute name="QueueFactoryRef">/LocalHornetQConnectionFactory</attribute>
<!-- The topic factory -->
<attribute name="TopicFactoryRef">/LocalHornetQConnectionFactory</attribute>
<!-- Connect to JNDI on the host "the-remote-host-name" port 1099-->
<attribute name="Properties">
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=IPADDRESS:1099
</attribute> </mbean>
I can view the RemoteJMSProvider in the JBoss jmx-console. Additionally, in JNDIView, I can see the JNDI name of the Remote JMS Provider. I can also see the jms.queue.inputQueue in the JMX console, though when I attempt to view messages on it, it says there are none, even though I know there are by viewing HermesJMS.
Finally, there are no exceptions in my application. It all appears to be running fine, but it never receives any messages. Even the HornetQ logs show that my IP address has connected, so I'm not sure why I can't read off of the queues:
[RMI TCP Connection(6)-10.3.78.123] 17:02:06,837 FINER [sun.rmi.transport.tcp] RMI TCP Connection(6)-10.3.78.123: (port 1098) client using 10.3.78.123:0
Any ideas?
Here's my HornetQ (2.2.5) configuration information for reference.
hornetq-jms.xml:
<connection-factory name="LocalHornetQConnectionFactory">
<xa>true</xa>
<connectors>
<connector-ref connector-name="netty"/>
</connectors>
<entries>
<entry name="/LocalHornetQConnectionFactory"/>
</entries>
<retry-interval>5000</retry-interval>
<retry-interval-multiplier>1.0</retry-interval-multiplier>
<reconnect-attempts>-1</reconnect-attempts>
<failover-on-server-shutdown>true</failover-on-server-shutdown>
<confirmation-window-size>1048576</confirmation-window-size>
</connection-factory>
<queue name="invalidQueue">
<entry name="/queue/invalidQueue"/>
</queue>
<queue name="inputQueue">
<entry name="/queue/inputQueue"/>
</queue>
<queue name="errorQueue">
<entry name="/queue/errorQueue"/>
</queue>
<topic name="SAFEStorageAcknowledgement">
<entry name="/topic/SAFEStorageAcknowledgement"/>
</topic>
<topic name="SAFEEvents">
<entry name="/topic/SAFEEvents"/>
</topic>
hornetq-configuration.xml:
<address-settings>
<!--default for catch all-->
<address-setting match="#">
<dead-letter-address>jms.queue.errorQueue</dead-letter-address>
<expiry-address>jms.queue.errorQueue</expiry-address>
<redelivery-delay>15000</redelivery-delay>
<max-size-bytes>10485760</max-size-bytes>
<message-counter-history-day-limit>10</message-counter-history-day-limit>
<address-full-policy>BLOCK</address-full-policy>
<redistribution-delay>60000</redistribution-delay>
</address-setting>
</address-settings>
<queues>
<queue name="jms.queue.inputQueue">
<address>jms.queue.inputQueue</address>
</queue>
<queue name="jms.queue.errorQueue">
<address>jms.queue.errorQueue</address>
</queue>
<queue name="jms.queue.invalidQueue">
<address>jms.queue.invalidQueue</address>
</queue>
</queues>
All other HornetQ settings are at default.
Thanks,
Andy
You have to specify on either the ra.xml or as an annotation two activation properties:
ConnectorClassName = org.hornetq.core.remoting.impl.netty.NettyConnectorFactory
ConnectionParameters = host=127.0.0.1;port=5446
On the HornetQ distribution, there's an example called javaee/jca-remote which is using the ra.xml to configure the activation property.
I am getting this error. I have my hibernate connections and MVC all setup correct I believe.
I heard MySQL drivers have an issue for database connection.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/AdministrativeApplication] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
java.sql.SQLException: Unknown database 'testDB'
My hibernate configuration file
<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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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
">
<!-- Load Hibernate related configuration -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="myroot"/>
<property name="password" value="*****"/>
<!-- connection pooling details -->
<property name="initialSize" value="1"/>
<property name="maxActive" value="5"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!-- Declare a transaction manager-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<!-- all the annotation entity classes -->
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
Please let me know what
I could do to resolve this error.
I further added a new java file to test
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "******";
String url = "jdbc:mysql://localhost:3306/testDB";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace(System.out);
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
I get this error . Also I started the MySQL console with this command.
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
I get this error
java.sql.SQLException: Unknown database 'testdb'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:798)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3700)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1203)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:15)
Cannot connect to database server
Can some please help resolve this.
i ran netstats no luck. I do not see at what port MySQL is listening at.
Thanks again .
Dhiren
I am getting this error.
This means you did something wrong.
I have my hibernate connections and MVC all setup correct I believe.
See my previous comment - you did not do everything correctly.
I heard MySQL drivers have an issue for database connection.
Nope - MySQL drivers work fine if you set them up properly. You're doing something wrong, and you'll make progress faster if you take that attitude.
Before you run Java, start up the MySQL client, log into MySQL. If you can't, Java won't be able to, either. See if the daemon is up and running.
See if you have that database available. If not, create it.
If it is created, make sure that you have the tables you need and the user you're logging in as has appropriate permissions.
You could create a database named "testDB" in your MySQL instance.