Monthly Archives: August 2018

Spring Data MongoDB – Save Or Update

In this tutorial you will learn how to save or update data into database using spring data mongoDB.

Spring Data MongoDB – Save Or Update

First declare “Mongo Template”, then do save or update :

@Autowired
private MongoTemplate mongoTemplate;

Spring Data MongoDB – Save Or UpdateMongo Template Save

User user = new User();
user.setName(“cimblo”);
user.setAge(99);
//save data with save() function
mongoTemplate.save(userTest1);

Mongo Template Update

No need to find the document. Just declare the Query with Criteria, then modify and update it with updateFirst() method.

String TABLE_USER = “table_user”;
Query query = new Query();
query.addCriteria(Criteria.where("name").is(“cimblo”);
Update update = new Update();
update.set(“age”, 25);
update.set(“updatedDate”, new Date());
mongoTemplate.updateFirst(query, update, TABLE_USER);

Update result:

{ 
	"_id" : ObjectId("id"), 
	"name" : “cimblo”, 
	"age" : 20, 
	"createdDate" : ISODate("2013-04-06T23:17:35.530Z"), 
	“updatedDate" : ISODate("2013-04-06T23:17:35.530Z") 
}

But using spring data mongoDB is very simple, you can just like this with mongo repository:

You can Save Or Update the whole object, if “_id” is present, perform an update, else insert it. If using mongo repository like below:

Using MongoRepository – Save OR Update

@Autowire
UserRepository userRepository;

//Find the document first by USER ID
User user = userRepository.findOne(id);

if (user == null) {
  User user = new User();
  user.setName(“Your Name”);
  user.setAge(20);
  //save new user object
  userRepository.save(user);
} else {
  user.setName(“Your Name”);
  user.setAge(20);
  //update
  userRepository.save(user);
}

That’s it 🙂

Need more reference? you can goto:

How To Handle Spring Data Pageable in Feign Client

If you don’t know about how to get content of Page in Spring Rest Client with Feign, hopefully this tutorial will help you to solve your problems. Let’s see how to handle spring data pageable in Feign Client below.

How To Handle Spring Data Pageable in Feign Client

When I’am building a MicroService with spring cloud, I think that feign is the good choice for the rest api client.
Unfortunately FeignClient interface is not support for Spring Data Pageable functionality. I am so sad 😭. But do not worry about that. If you still really want to retrieve response from Spring Data Pageable, you can make a custom ResponseBody like this example:

Sample response with JSON format:

{
  "code": "SUCCESS",
  "message": "SUCCESS",
  "errors": null,
  "data": {
    "content": [
      {
        "id": "5b82d48aae70060d69785736",
        "version": 0,
        "createdDate": 1535300746521,
        "createdBy": "system",
        "updatedDate": 1535300746521,
        "updatedBy": "system",
        "isDeleted": 0,
        "username": "guest",
        "password": "$2a$10$RPMVL3HIwG/CY/4rf0faVeQejDfC.C/v1IQmRT3tWIBKqbGK7QdXG",
        "fullName": "Guest",
        "email": "guest@guest.com",
        "enabled": true,
        "roles": [
          "ROLE_GUEST"
        ],
        "lastPasswordResetDate": null,
        "menuAccess": [
          {
            "id": null,
            "version": null,
            "createdDate": null,
            "createdBy": null,
            "updatedDate": null,
            "updatedBy": null,
            "isDeleted": 0,
            "accessCode": "DASHBOARD",
            "accessName": "Dashboard",
            "pathUrl": "/dashboard"
          }
        ]
      }
    ],
    "pageable": {
      "sort": {
        "sorted": true,
        "unsorted": false
      },
      "offset": 0,
      "pageSize": 20,
      "pageNumber": 0,
      "unpaged": false,
      "paged": true
    },
    "totalPages": 1,
    "totalElements": 1,
    "last": true,
    "size": 20,
    "number": 0,
    "numberOfElements": 1,
    "first": true,
    "sort": {
      "sorted": true,
      "unsorted": false
    }
  },
  "serverTime": 1535423509684
}

Custom class (for the response):

//to be continue 22:00 today

How To Handle Spring Data Pageable in Feign Client

That is how to get content of Page in Spring Rest Client with Spring Data Pageable in Feign Client.
Hopefully in the future this library (Feign Client) will adding support for spring data pageable functionality.

More tutorial

How To Undo, Reset, Revert Commits In Git

To undo git commit or reset or revert you can use this command below:

git reset HEAD~

Sometime people ask to me how to revert a Git repository? How to undo the last commit? or how to cancel a local git commit? Then how do I delete un-pushed git commits? that ‘blue‘ is the answer. But if you want to removing multiple commits from the top, you can run git reset HEAD~5 too.

How To Undo, Reset, Revert Commits In Git

How To Undo, Reset, Revert Commits In Git

When your situation is get accidentally committed wrong files to Git, but you haven’t pushed the commit to the server yet. My suggestion for undo changes in git is using a number after “~”, that’s mean to remove the last x commits. But if you have a nice trick for undoing or removing commits in Git, please comment down below guys.

notes:

  1. Do not use git reset –hard because this is a completely unrecoverable operation, any changes which are removed here cannot be restored later. This will not delete untracked or ignored files.
  2. Keep using best practice to reset changes in git if you don’t want to lose all the changes.
  3. That is the simple git tutorial about how to undo, reset, revert commits in Git.

This is more reference to learn how to undo a previous source in Git:

Spring RestTemplate With Cookie In Header

Spring rest template hit endpoint with cookie in header can be like this:

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL));
headers.add("Cookie", "ID=SPRING-JAVA");
HttpEntity entity = new HttpEntity<>(headers);

ResponseEntity response = restTemplate.exchange(
    "https://www.cimblo.com", HttpMethod.GET, entity, String.class);

Spring RestTemplate With Cookie In Header

Spring RestTemplate With Cookie In Header

In this example i’m using java 8 and spring boot version 1.5.8 with starter-web dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Open URL On Web Browser With JAVA (Linux, Mac, Windows)

If you need to open link on browser with java code, you can do with this code.

Runtime rt = Runtime.getRuntime();
String url =
    "https://www.cimblo.com“;
try {
  rt.exec("open " + url);
} catch (IOException e) {
  e.printStackTrace();
}

Open URL On Web Browser With JAVA (Linux, Mac, Windows)

Open URL On Web Browser With JAVA (Linux, Mac, Windows)

That code currently will work on Linux, Mac, Ubuntu and Windows in any default browser. See another java article here.

Spring Data MongoDB LIKE Query Insensitive Case ‘%%’

With spring data mongoDB you can do “LIKE QUERY” like example below.

Query query = new Query();
query.addCriteria(Criteria.where("name").regex("yourString", "i"));
mongoTemplate.find(query, CodingExample.class)

Spring Data MongoDB LIKE Query Insensitive Case

Spring Data MongoDB LIKE Query Insensitive Case

Spring Data MongoDB

The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

If you need more query regex example, please go to the official mongo regex documentation or spring data mongoDB.

AsyncRequestTimeoutException in Spring Boot

If you using asynchronous programming with observable streams in spring boot, i suggest you to setup async request timeout because default async request timeout in spring boot 2.0 is 10 second. You will got an exception (AsyncRequestTimeoutException) when request is more than 10 second.

AsyncRequestTimeout

AsyncRequestTimeoutException in Spring Boot

My suggestion is 60s or 120s (s mean second) :

spring.mvc.async.request-timeout=60s

That is how to handle “AsyncRequestTimeoutException in Spring Boot”.