MongoDB Java-driven integration with spring

Source: Internet
Author: User
Tags mongodb server mongodb support

See a lot of people search Java and MongoDB, then write point Java Operation MongoDB Project experience. MongoDB Java-driven basic operations can be seen here.

In fact, the MongoDB Java driver can accomplish most of the operations and requirements. But when your document has more than N "fields" that need to be put constantly, do you feel that the code is too trivial, messy, and not elegant. If you're doing web engineering, and engineering integrates spring, you might as well integrate spring and MongoDB.

The reason: Spring provides a MONGODB support framework for Java Pojo to MongoDB document mapping. It seems spring is still quite "evolving with the times." More background information can be referred to the official website: http://www.springsource.org/node/3032.

The benefit of taking the generated Java class object as a document operation is self-evident, think of hibernate.

Easy to use, where the key steps and code are posted, and summarized only by:

Now let's say you've got an SSH-consolidated Web application, and all the XML files are normal.

The first step is to add the relevant bean declaration to Applicationcontext.xml. Let spring help new out of the required database connections and datasource. The address of the MongoDB server is passed into the MONGO bean. Mongotemplate uses template mode to encapsulate MongoDB data object operations, which is the core class. A few parameters a database name a default collection name, compare understood.

<beanid= "MONGO" class= "Org.springframework.data.document.mongodb.MongoFactoryBean" >

<propertyname= "Host" value= "10.232.36.107"/>

</bean>

<beanid= "Mongotemplate" class= "Org.springframework.data.document.mongodb.MongoTemplate" >

<constructor-argref= "Mongo"/>

<constructor-argname= "DatabaseName" value= "Zhishudb"/>

<constructor-argname= "Defaultcollectionname" value= "Recordlib"/>

</bean>

As a minimalist application, it is sufficient that applicationcontext.xml only set up these two beans.

Step two: If your web.xml should be left with the opensessioninview of spring and hibernate integration, now you don't need it.

The third step: finally is our model. Java class persistence objects need not be set to any annotation. is a very common Java bean. Such as:

public class record{

Privatelong auction_id;

Private String title;

////

Getter ()/setter () method

....

}

Special NOTE: The model does not set the ID such a member variable, it will overwrite MongoDB for each record automatically generated _id field. The consequence of overwriting IDs is that you cannot insert the second record. Of course, if you insist on having an ID, you need to manually set a unique value for the ID, and you cannot leave it blank. This is not the same as using hibernate to MySQL or something.

Fourth step: Now the DAO operation.

Speaking of Mongotemplate, we will certainly associate a template with spring to hibernate, and we use it for database operations.

For Recorddao, you first need to get a Templat object:

@Resource

Public voidsetmongooperation (mongotemplate mongotemplate) {

this. mongotemplate= mongotemplate;

}

The other actions are:

Insert data like a database

Public voidAddRecord (Object p) {

Mongotemplate.insert (P);

}

Insert data like database specified collection, no new

Public voidAddRecord (String collection, Object p) {

Mongotemplate.insert (collection, p);

}

Fetch to all, return the cursor object for traversal

Public Dbcursorgetcollectioncursor (stringcollectionname) {

return Mongotemplate.getcollection (CollectionName). find ();

}

/**

* Update the Productlib record

*

* **/

Public voidUpdate (stringwhere, String Whereis, String whereto, Object Newobjecct) {

Mongotemplate.updatefirst ("Recordlib",

New Query (Criteria.where (where). is (Whereis)),

New Update (). Set (Whereto, NEWOBJECCT));

}

/**

* Save an updated object

*

* **/

Public voidsaveupdate (String CollectionName, record p) {

Mongotemplate.save (CollectionName, p);

}

/**

* Index the Title field

*

* **/

Public voidindex (String collectionname) {

Mongotemplate.ensureindex (CollectionName, newIndex (). On ("title", Order.ascending));

}

/**

* According to the keyword query field, return the product instance

*

* **/

Public List<record>searchrecordbykeyword (stringcollectionname, String keyword, intlimit) {

List<record> PL;

Try {

PL = Mongotemplate.find (collectionname,

New Query (WHERE ("title"). Regex (". *?") + keyword + ". *+"), record. class);

return PL;

Catch(Exception e) {

E.printstacktrace ();

}

return null;

}


At this point, has been able to complete the spring integration with the mongodb of additions and deletions to check. Upper operation, call here Conlio.

There are more operations and improvements that need to be viewed in more detail in the API.

such as the above field query operation, using the regular expression of the pattern, under some conditions or not ideal. More models to be consulted and further improvements are needed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.