Store ID as long in Mongodb Using Spring Data

Posted By : Prabjot Singh | 06-Jun-2015

We had a requirement to store id as long in mongodb,because we were using mahout item base recommendation engine,mahout required user_id,item_id as long data type.But bydefault mongodb store id as object id in database.I am going to show you how you can store long type id is in mongodb using tricky way

Steps to Add a Counter

I will create a counter in database,while I will set id of any entity,i have to call counter service,counter service will increment value in database and return long value. So this value we will set to entity,and save into database. Let 's do it using follow steps. I am using spring data mongodb for persistance value in database because I am comfortable with mongotemplate's criteria to write queries

So, I am assuming that you know well about how to inject “spring-data-mongodb” in project.

1) Create your entity class

 public class User {
	
    private Long userId;

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

}
 

2) Create a Service to persist entity

 @Service
public class UserService {
	
	@Autowired MongoTemplate mongoTemplate;
	@Autowired CounterService counterService;
	
	public void saveUser(){
		User user = new User();
		user.setUserId(counterService.getNextUserIdSequence());
		mongoTemplate.save(user);
	}
}
 

Now Create a Counter entity 

You will have name of counter and parameter which you have to increment while you will set id of entity

 public class Counter {
	
	private String name;
    
    private long sequence;

	public long getSequence() {
		return sequence;
	}

	public void setSequence(long sequence) {
		this.sequence = sequence;
	}
}
 

3) Counter Service

With the help of counter service,you will get last counter value from database and then increment on while you will set id of any entity

 public class CounterService {
	
	@Autowired MongoTemplate mongoTemplate;
	
	public static final String USER_ID_SEQUENCE_NAME = "user_id";
	
	public long getNextUserIdSequence() {
        return increaseCounter(USER_ID_SEQUENCE_NAME);
    }
	
	
	/**
	 * @author prabjot
	 * this method will update the counter in database and return counter value
	 * @param counterName // to define counter name in database
	 * @return
	 */
	private long increaseCounter(String counterName){
        Query query = new Query(Criteria.where("name").is(counterName));
        Update update = new Update().inc("sequence", 1);
        Counter counter = mongoTemplate.findAndModify(query, update, Counter.class); // return old Counter object
        return counter.getSequence();
    }
	
} 
 

Now one more step to complete

you have to setup one time counter document in database and initialized to 1 when you will start your application

 db.Counter.insert({ "name" : "user_id", sequence : 1})
 

Thank You !!!

 

 

 

 

 

 

 

About Author

Author Image
Prabjot Singh

Prabjot is a Java and Grails developer.He has a good hands on neo4J, AngularJS. He likes to work on new technologies

Request for Proposal

Name is required

Comment is required

Sending message..