标签归档:spring

Spring 批量执行语句

   使用Spring ScriptUtils 批量执行Sql语句,如批量执行update table1 set status=0, dprice=55 where id in (9600980);insert into table1 (dprice,status) values(46,0),(55,1);这两条语句。

方法

 public void executeSqlScript(Connection connection,StringBuffer sql)throws SQLException{ try {
			 connection.setAutoCommit(false);//设置为手工提交模式  ScriptUtils.executeSqlScript(connection, new ByteArrayResource(sql.toString().getBytes()));
			 connection.commit();//提交事务  } catch (SQLException e) {
			connection.rollback();
		}finally{
			connection.close();
		}
	 }

error at ::0 can’t find referenced pointcut解决方法

在项目中遇到 error at ::0 can't find referenced pointcut 的解决方法
具体错误如下:
 Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut addHanderat org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:315)at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206)at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:193)at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:174)at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:195)at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:250)at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:284)at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:113)at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:85)at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:66)at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:325)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:361)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1344)at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)... 14 more
 出现error at ::0 can't find referenced pointcut...这样的错误原因是:如果你用的JDK版本是1.6的话,而引用的aspectjrt.jar是spring-2.0中包含的jar包的情况下就会报这样的错误。 

解决的办法就是下载最新的aspectjrt的jar包即可aspectj-1.6.6.jar 

下载地址http://www.eclipse.org/aspectj/downloads.php

Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V

Spring3 HIbernate3.6 Struts2.1.8结合时配置 AOP事物, 出现错误:

Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

将cglib.jar 由2.2版本 改为 2.1.

下载 http://www.java2s.com/Code/Jar/ABC/cglib.jar.htmhttp://sourceforge.net/projects/cglib/files/

本文来自:http://www.cnblogs.com/tyler2000/archive/2011/01/07/1929407.html#

Spring & MongoDB初试

最近在学习Spring和MongoDB的结合,在Spring官网下载了Spring Data MongoDB hello world example 例子,配置过程种出现各种错误。和大家分享下,有兴趣的可以一起研究下:

错误一:
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.springframework.context.support.AbstractApplicationContext.<init>

(AbstractApplicationContext.java:160)
at org.springframework.context.support.AbstractApplicationContext.<init>

(AbstractApplicationContext.java:213)
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:101)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>

(AnnotationConfigApplicationContext.java:63)
at com.mkyong.core.App.main(App.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 5 more
这是因为缺少包commons-logging-1.1.1.jar把包加入项目问题就解决了。

错误二:
如果你运行的是//For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
出现如下错误:
Exception in thread “main” java.lang.IllegalStateException: Cannot load configuration class: 

com.mkyong.config.SpringMongoConfig
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses

(ConfigurationClassPostProcessor.java:246)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory

(ConfigurationClassPostProcessor.java:160)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors

(AbstractApplicationContext.java:663)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors

(AbstractApplicationContext.java:602)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:407)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>

(AnnotationConfigApplicationContext.java:65)
at com.mkyong.core.App.main(App.java:21)
Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer

(ConfigurationClassEnhancer.java:101)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance

(ConfigurationClassEnhancer.java:89)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses

(ConfigurationClassPostProcessor.java:238)
… 6 more
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 12 more
这是因为项目中SpringMongoConfig文件中多了一个注解@Configuration,把它注释就可以。

错误三:
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception 

parsing XML document from class path resource [mongo-config.xml]; nested exception is 

java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.GenericXmlApplicationContext.load

(GenericXmlApplicationContext.java:105)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:68)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.data.document.mongodb.config.MongoParser.getBeanClass(MongoParser.java:38)
at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal

(AbstractSingleBeanDefinitionParser.java:66)
at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse

(AbstractBeanDefinitionParser.java:59)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement

(BeanDefinitionParserDelegate.java:1335)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement

(BeanDefinitionParserDelegate.java:1325)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions

(DefaultBeanDefinitionDocumentReader.java:135)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions

(DefaultBeanDefinitionDocumentReader.java:93)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions

(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:390)
… 9 more
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.support.PersistenceExceptionTranslator
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 31 more
缺少包spring-tx-3.0.5.RELEASE.jar

错误四:
Exception in thread “main” org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 84 in XML 

document from class path resource [mongo-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; 

systemId: http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd; lineNumber: 84; columnNumber: 51; 

src-resolve: 无法将名称 ‘repository:repository’ 解析为 ‘type definition’ 组件。
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:396)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions

(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions

(AbstractBeanDefinitionReader.java:212)
at org.springframework.context.support.GenericXmlApplicationContext.load

(GenericXmlApplicationContext.java:105)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:68)
at com.mkyong.core.App.main(App.java:24)
Caused by: org.xml.sax.SAXParseException; systemId: http://www.springframework.org/schema/data/mongo/spring-mongo-

1.0.xsd; lineNumber: 84; columnNumber: 51; src-resolve: 无法将名称 ‘repository:repository’ 解析为 ‘type definition’ 

组件。
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getGlobalDecl(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseComplexContent

(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseComplexTypeDecl

(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDComplexTypeTraverser.traverseGlobal(Unknown 

Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.traverseSchemas(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.emptyElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown 

Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions

(XmlBeanDefinitionReader.java:388)
… 9 more
缺少包spring-data-commons-core-1.0.0.RC1.jar

错误五:
Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name 

‘mongo’: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: 

Could not instantiate bean class [org.springframework.data.document.mongodb.MongoFactoryBean]: Constructor threw 

exception; nested exception is java.lang.NoClassDefFoundError: 

org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean

(AbstractAutowireCapableBeanFactory.java:965)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance

(AbstractAutowireCapableBeanFactory.java:911)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean

(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean

(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton

(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons

(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization

(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:425)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:69)
at com.mkyong.core.App.main(App.java:24)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class 

[org.springframework.data.document.mongodb.MongoFactoryBean]: Constructor threw exception; nested exception is 

java.lang.NoClassDefFoundError: org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:141)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate

(SimpleInstantiationStrategy.java:74)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean

(AbstractAutowireCapableBeanFactory.java:958)
… 12 more
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/document/UncategorizedDocumentStoreException
at org.springframework.data.document.mongodb.MongoFactoryBean.<init>(MongoFactoryBean.java:54)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126)
… 14 more
Caused by: java.lang.ClassNotFoundException: org.springframework.data.document.UncategorizedDocumentStoreException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 20 more
缺少包spring-data-document-core-1.0.0.M2.jar

错误六:
Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/expression/PropertyAccessor
at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory

(AbstractApplicationContext.java:483)
at org.springframework.context.support.AbstractApplicationContext.refresh

(AbstractApplicationContext.java:400)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:69)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.PropertyAccessor
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 4 more
缺少包org.springframework.expression-3.0.5.RELEASE.jar

错误七:
Exception in thread “main” java.lang.NoClassDefFoundError: org/springframework/asm/ClassVisitor
at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:103)
at org.springframework.context.support.GenericXmlApplicationContext.<init>

(GenericXmlApplicationContext.java:67)
at com.mkyong.core.App.main(App.java:24)
Caused by: java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 3 more
缺少包org.springframework.asm-3.0.5.RELEASE.jar

最后介绍几个下载包的地方:


 http://www.findjar.com/index.x

Maven-Focused Java Class and Archive Search Enginehttp://www.jarvana.com/jarvana/

Programming tutorials and source code examples http://www.java2s.com/

http://www.jar114.com/


Spring Data & MongoDB

In this article we are going to cover the following topics:

  1. MongoDB Installation on Windows Machine.
  2. MongoDB Java Example.
  3. Spring Data & MongoDB.

  MongoDB Installation on Windows Machine:

     Download MongoDB from official MongoDB website.

     Unzip MongoDB files to your prefer location, for example : “D:mongodb-win32-x86_64-1.8.3“.

     MongoDB won’t create data directory automatically. You need to create a data directory for MongoDB, for example : “D:mongodb-data“.

    mongod.exe is the database server daemon, run it and point it to the data directory, via “–dbpath” argument.

D:mongodb-win32-x86_64-1.8.3bin>mongod --dbpath "D:mymongodb-data" 

  In the output, you will notice that MongoDB started a web admin interface listening on port 28017.

   To access it, just type http://your-ipaddress:28017.

   In order to connect to your MongoDB server type D:mongodb-win32-x86_64-1.8.3bin>mongo

   If you are able to view the MongoDB web admin interface and also connected to the database server via mongo.exe, then your MongoDB is installed on the Windows successfully.

 

  MongoDB Java Example:

    A simple Java MongoDB example.

    Technologies and tools used:

  1. MongoDB 1.8.3
  2. MongoDB-Java-Driver 2.6.5
  3. JDK 1.6
package edu.seua.mongo;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB Example
 * 
 */
public class MongoApp {

    public static void main(String[] args) {

	try {
	    // connect to mongoDB
	    Mongo mongo = new Mongo("localhost", 27017);

	    // if database doesn't exists, mongoDB will create it
	    DB db = mongo.getDB("mydb");

	    // Get collection from MongoDB, database named "mydb"
	    // if collection doesn't exists, mongoDB will create it
	    DBCollection collection = db.getCollection("myCollection");

	    // create a document to store attributes
	    BasicDBObject document = new BasicDBObject();
	    document.put("id", 100);
	    document.put("name", "simple name");
	    document.put("message", "simple message");
	    

	    // save it into collection named "myCollection"
	    collection.insert(document);

	    // search query
	    BasicDBObject searchQuery = new BasicDBObject();
	    searchQuery.put("id", 100);

	    DBCursor cursor = collection.find(searchQuery);

	    // loop over the cursor and display the result
	    while (cursor.hasNext()) {
		System.out.println(cursor.next());
	    }

	} catch (UnknownHostException e) {
	    e.printStackTrace();
	} catch (MongoException e) {
	    e.printStackTrace();
	}
    }
}

Output

{ 
   "_id" : { "$oid" : "4e5936ca602fbf0c50e0c9d0"} , 
   "id" : 100 , "name" : "simple name" , "message" : "simple message"
}

Now it’s time for Spring Data & MongoDB:

    Technologies and jars used:

  1. MongoDB 1.8.3
  2. JDK 1.6
  3. mongo-2.6.5.jar
  4. org.springframework.context-3.0.5.RELEASE.jar
  5. org.springframework.core-3.0.5.RELEASE.jar
  6. org.springframework.beans-3.0.5.RELEASE.jar
  7. commons-logging-1.1.1.jar
  8. org.springframework.asm-3.0.5.RELEASE.jar
  9. spring-data-mongodb-1.0.0.M2.jar
  10. slf4j-api-1.6.1.jar
  11. slf4j-jdk14-1.6.1.jar
  12. spring-dao-2.0.8.jar
  13. spring-expression-3.1.0.M2.jar
  14. spring-data-commons-core-1.1.0.M1.jar
  15. spring-tx-3.1.0.M1.jar
  16. spring-data-document-core-1.0.0.M2.jar



Spring XML configuration file (mongo-config.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
	<mongo:mongo host="localhost" port="27017" />
 
	<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
		<constructor-arg ref="mongo" />
		<constructor-arg name="databaseName" value="myNewdb" />
		<constructor-arg name="defaultCollectionName" value="myNewCollection" />
	</bean>
 
	<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
	<context:annotation-config />
 
</beans>

  Let’s create Employee DTO

package edu.seua.mongo;

public class Employee {

    private String id;
    private String firstname;
    private String lastname;
    private int age;

    public Employee() {
    }

    public Employee(String id, String firstname, String lastname, int age) {
	super();
	this.id = id;
	this.firstname = firstname;
	this.lastname = lastname;
	this.age = age;
    }

    public String getId() {
	return id;
    }

    public void setId(String id) {
	this.id = id;
    }

    public String getFirstname() {
	return firstname;
    }

    public void setFirstname(String firstname) {
	this.firstname = firstname;
    }

    public String getLastname() {
	return lastname;
    }

    public void setLastname(String lastname) {
	this.lastname = lastname;
    }

    public int getAge() {
	return age;
    }

    public void setAge(int age) {
	this.age = age;
    }

    @Override
    public String toString() {
	return "Employee [age=" + age + ", firstname=" + firstname + ", id="
		+ id + ", lastname=" + lastname + "]";
    }

}

Full Example   

    Full example shows you how to use Spring data to perform CRUD operations in mongoD.

    The employee object is saved into a collection named employees.

package edu.seua.mongo;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;

/**
 * Java Spring Data & MongoDB Example
 * 
 */
public class SpringDataMongoApp {

    public static void main(String[] args) {

	ApplicationContext ctx = new ClassPathXmlApplicationContext("edu/seua/mongo/mongo-config.xml");

	MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

	Employee employee = new Employee("100", "firstName", "lastName", 23);

	// save
	mongoOperation.save("employees", employee);

	// find
	Employee savedEmployee = mongoOperation.findOne("employees", new Query(Criteria.where(
		"id").is("100")), Employee.class);

	System.out.println("Saved Employee: " + savedEmployee);

	// update
	mongoOperation.updateFirst("employees", new Query(Criteria.where(
		"firstname").is("firstName")), Update.update("lastname",
		"new lastName"));

	// find
	Employee updatedEmployee = mongoOperation.findOne("employees", new Query(
		Criteria.where("id").is("100")), Employee.class);

	System.out.println("Updated Employee: " + updatedEmployee);

	// delete
	mongoOperation.remove("employees", new Query(Criteria.where("id").is(
		"100")), Employee.class);

	// List
	List<Employee> listEmployee = mongoOperation.getCollection("employees", Employee.class);
	System.out.println("size of employees = " + listEmployee.size());

    }
}

  Output

Saved Employee: Employee [age=23, firstname=firstName, id=100, lastname=lastName]
Updated Employee: Employee [age=23, firstname=firstName, id=100, lastname=new lastName]
size of employees = 0
Article Type: 
Opinion/Editorial