linuxism

spring data - mongoDB Date type

Framework & Platform/Spring

spring data - mongoDB Date type

linuxism 2014. 1. 15. 17:11


Spring Data MongoDB : Insert Document

In Spring data MongoDB, you can use save()insert() to save a or a list of objects into mongoDB database.

	User user = new User("...");
 
	//save user object into "user" collection / table
	//class name will be used as collection name
	mongoOperation.save(user);
 
	//save user object into "tableA" collection
	mongoOperation.save(user,"tableA");
 
	//insert user object into "user" collection
	//class name will be used as collection name
	mongoOperation.insert(user);
 
	//insert user object into "tableA" collection
	mongoOperation.insert(user, "tableA");
 
	//insert a list of user objects
	mongoOperation.insert(listofUser);

By default, if you saved an object, and didn’t specified any of the “collection name”, the class name will be used as the collection name.

1. Save and Insert

Should you use the Save or Insert?

  1. Save – It should rename to saveOrUpdate(), it performs insert() if “_id” is NOT exist or update() if “_id” is existed”.
  2. Insert – Only insert, if “_id” is existed, an error is generated.

See example below

	//get an existed data, and update it
	User userD1 = mongoOperation.findOne(
		new Query(Criteria.where("age").is(64)), User.class);
	userD1.setName("new name");
	userD1.setAge(100);
 
	//if you insert it, 'E11000 duplicate key error index' error is generated.
	//mongoOperation.insert(userD1); 
 
	//instead you should use save.
	mongoOperation.save(userD1);

2. Insert documents example

See a full example to show you how to save a or a list of “user” object into MongoDB.

SpringMongoConfig.java – Create a mongoTemplate bean in Spring container.
package com.mkyong.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.MongoClient;
 
/**
 * Spring MongoDB configuration file
 * 
 */
@Configuration
public class SpringMongoConfig{
 
	public @Bean
	MongoTemplate mongoTemplate() throws Exception {
 
		MongoTemplate mongoTemplate = 
			new MongoTemplate(new MongoClient("127.0.0.1"),"yourdb");
		return mongoTemplate;
 
	}
 
}

Uses @Document to define a “collection name” when you save this object. In this case, when “user” object saves, it will save into “users” collection.

User.java
package com.mkyong.user;
 
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
 
@Document(collection = "users")
public class User {
 
	@Id
	private String id;
 
	@Indexed
	private String ic;
 
	private String name;
 
	private int age;
 
	@DateTimeFormat(iso = ISO.DATE_TIME)
	private Date createdDate;
 
	//getter and setter methods
}

Full examples to show you different ways of inserting data, read code and comments for self-explanatory.

App.java
package com.mkyong.core;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
 
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.user.User;
 
public class App {
 
	public static void main(String[] args) {
		// For Annotation
		ApplicationContext ctx = 
                     new AnnotationConfigApplicationContext(SpringMongoConfig.class);
		MongoOperations mongoOperation = 
                     (MongoOperations) ctx.getBean("mongoTemplate");
 
		// Case1 - insert a user, put "tableA" as collection name
		System.out.println("Case 1...");
		User userA = new User("1000", "apple", 54, new Date());
		mongoOperation.save(userA, "tableA");
 
		// find
		Query findUserQuery = new Query();
		findUserQuery.addCriteria(Criteria.where("ic").is("1000"));
		User userA1 = mongoOperation.findOne(findUserQuery, User.class, "tableA");
		System.out.println(userA1);
 
		// Case2 - insert a user, put entity as collection name
		System.out.println("Case 2...");
		User userB = new User("2000", "orange", 64, new Date());
		mongoOperation.save(userB);
 
		// find
		User userB1 = mongoOperation.findOne(
                     new Query(Criteria.where("age").is(64)), User.class);
		System.out.println(userB1);
 
		// Case3 - insert a list of users
		System.out.println("Case 3...");
		User userC = new User("3000", "metallica", 34, new Date());
		User userD = new User("4000", "metallica", 34, new Date());
		User userE = new User("5000", "metallica", 34, new Date());
		List<User> userList = new ArrayList<User>();
		userList.add(userC);
		userList.add(userD);
		userList.add(userE);
		mongoOperation.insert(userList, User.class);
 
		// find
		List<User> users = mongoOperation.find(
                           new Query(Criteria.where("name").is("metallica")),
			   User.class);
 
		for (User temp : users) {
			System.out.println(temp);
		}
 
		//save vs insert
		System.out.println("Case 4...");
		User userD1 = mongoOperation.findOne(
                          new Query(Criteria.where("age").is(64)), User.class);
		userD1.setName("new name");
		userD1.setAge(100);
 
		//E11000 duplicate key error index, _id existed
		//mongoOperation.insert(userD1); 
		mongoOperation.save(userD1);
		User userE1 = mongoOperation.findOne(
                         new Query(Criteria.where("age").is(100)), User.class);
		System.out.println(userE1);
	}
 
}

Output

Case 1...
User [id=id, ic=1000, name=apple, age=54, createdDate=Sat Apr 06 12:35:15 MYT 2013]
Case 2...
User [id=id, ic=2000, name=orange, age=64, createdDate=Sat Apr 06 12:59:19 MYT 2013]
Case 3...
User [id=id, ic=3000, name=metallica, age=34, createdDate=Sat Apr 06 12:59:19 MYT 2013]
User [id=id, ic=4000, name=metallica, age=34, createdDate=Sat Apr 06 12:59:19 MYT 2013]
User [id=id, ic=5000, name=metallica, age=34, createdDate=Sat Apr 06 12:59:19 MYT 2013]
Case 4...
User [id=id, ic=2000, name=new name, age=100, createdDate=Sat Apr 06 12:59:19 MYT 2013]

3. Mongo Console

Review Mongo console, see what are inserted and created.

> mongo
MongoDB shell version: 2.2.3
connecting to: test
 
> show dbs
admin	0.203125GB
yourdb	0.203125GB
 
> use yourdb
switched to db yourdb
> show collections
system.indexes
tableA
users
 
> db.tableA.find()
{ "_id" : ObjectId("id"), "_class" : "com.mkyong.user.User", 
"ic" : "1000", "name" : "apple", "age" : 54, "createdDate" : ISODate("2013-04-06T05:04:06.384Z") }
 
> db.users.find()
{ "_id" : ObjectId("id"), "_class" : "com.mkyong.user.User", 
"ic" : "3000", "name" : "metallica", "age" : 34, "createdDate" : ISODate("2013-04-06T05:04:06.735Z") }
{ "_id" : ObjectId("id"), "_class" : "com.mkyong.user.User", 
"ic" : "4000", "name" : "metallica", "age" : 34, "createdDate" : ISODate("2013-04-06T05:04:06.735Z") }
{ "_id" : ObjectId("id"), "_class" : "com.mkyong.user.User", 
"ic" : "5000", "name" : "metallica", "age" : 34, "createdDate" : ISODate("2013-04-06T05:04:06.735Z") }
{ "_id" : ObjectId("id"), "_class" : "com.mkyong.user.User", 
"ic" : "2000", "name" : "new name", "age" : 100, "createdDate" : ISODate("2013-04-06T05:04:06.731Z") }

P.S To remove the extra _class column, read this article – Spring Data MongoDB Remove _class Column.

Download Source Code

Download it – SpringData-MongoDB-Insert-Example.zip (24KB)

References

  1. Spring Data MongoDB – Saving, Updating, and Removing Documents
  2. Spring Data MongoDB Hello World Example



출처 - http://www.mkyong.com/mongodb/spring-data-mongodb-insert-document/









org.springframework.format.annotation 
Enum DateTimeFormat.ISO

java.lang.Object
  extended by java.lang.Enum<DateTimeFormat.ISO>
      extended by org.springframework.format.annotation.DateTimeFormat.ISO
All Implemented Interfaces:
SerializableComparable<DateTimeFormat.ISO>
Enclosing class:
DateTimeFormat

public static enum DateTimeFormat.ISO
extends Enum<DateTimeFormat.ISO>

Common ISO date time format patterns.


Enum Constant Summary
DATE 
          The most common ISO Date Format yyyy-MM-dd e.g.
DATE_TIME 
          The most common ISO DateTime Format yyyy-MM-dd'T'hh:mm:ss.SSSZ e.g.
NONE 
          Indicates that no ISO-based format pattern should be applied.
TIME 
          The most common ISO Time Format hh:mm:ss.SSSZ e.g.

 

Method Summary
static DateTimeFormat.ISOvalueOf(String name) 
          Returns the enum constant of this type with the specified name.
static DateTimeFormat.ISO[]values() 
          Returns an array containing the constants of this enum type, in the order they are declared.

 

Methods inherited from class java.lang.Enum
clonecompareToequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

 

Methods inherited from class java.lang.Object
getClassnotifynotifyAllwaitwaitwait

 

Enum Constant Detail

DATE

public static final DateTimeFormat.ISO DATE
The most common ISO Date Format yyyy-MM-dd e.g. 2000-10-31.


TIME

public static final DateTimeFormat.ISO TIME
The most common ISO Time Format hh:mm:ss.SSSZ e.g. 01:30:00.000-05:00.


DATE_TIME

public static final DateTimeFormat.ISO DATE_TIME
The most common ISO DateTime Format yyyy-MM-dd'T'hh:mm:ss.SSSZ e.g. 2000-10-31 01:30:00.000-05:00. The default if no annotation value is specified.


NONE

public static final DateTimeFormat.ISO NONE
Indicates that no ISO-based format pattern should be applied.

Method Detail

values

public static DateTimeFormat.ISO[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (DateTimeFormat.ISO c : DateTimeFormat.ISO.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in the order they are declared

valueOf

public static DateTimeFormat.ISO valueOf(String name)
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the specified name
NullPointerException - if the argument is null



출처 - http://docs.spring.io/spring/docs/3.1.4.RELEASE/javadoc-api/org/springframework/format/annotation/DateTimeFormat.ISO.html