CRUD using Spring Data Rest and AngularJS using Spring Boot

In my previous article , I explained how to make crud operations using plain spring restful web services and angularjs with a samp...




In my previous article, I explained how to make crud operations using plain spring restful web services and angularjs with a sample task manager application. That was very simple, yet it had several shortcomings that needed a fix in order to move towards reducing most of the boilerplate code, adhering to the latest methodologies suggested by Spring Framework and to follow better code practices. It is better late than never. Having mentioned that, the previous implementation will still work and to start with as a beginner, it is a good choice to have a read through it.

My sincere thanks to Greg L. Turnquist and Josh Long for helping me to understand the best approach and the way to go forward with Spring Framework. Special thanks to Greg, who also fine tuned task manager project to use Spring Data Rest and Spring Boot. In this article I am going to give you an overview of how to use Spring Boot to setup and build Spring project and how to use Spring Data REST to efficiently implement database operations in a RESTFul manner, with the same task manager application used in my previous article.

If you are not well versed in the latest releases of Spring and are used to the XML way of configuring things like me, it is time to learn "SPRING BOOT". Do not hesitate, as it is very simple and once you start using it you will never regret the decision of spending some time to learn it. Lets get started now.


Article Recognitions*

  • A mention about this article in official spring blog here.
  • Big Link in Dzone



Spring Boot can be used with build tools such as Maven or Gradle. These build tools help you share jars between various applications, build your application and generate reports. There are many articles on how to install and use Maven and I am going to explain how to install Maven plugin to Eclipse for our use in this project.

Install Maven in Eclipse IDE

Open Eclipse IDE
Click Help -> Install New Software...
Click Add button at top right corner
At pop up: fill up Name as "M2Eclipse" and Location as "http://download.eclipse.org/technology/m2e/releases"
Now click OK
After that installation would be started.

Another way to install Maven plug-in for Eclipse:

Open Eclipse
Go to Help -> Eclipse Marketplace
Search by Maven
Click "Install" button at "Maven Integration for Eclipse" section
Follow the instruction step by step

After successful installation do the followings in Eclipse:

1) Go to Window --> Preferences
2) Observe, Maven is enlisted at left panel

Set up project with Spring Boot

1. Go to New -> Maven Project in Eclipse,


2. Click Next -> Check Create a simple project -> Give workspace location


3. Click Next -> Enter configurations as seen in the screenshot below



Now as the application configuration is done, on clicking "Finish", you can see a project with below standard directory structure created in the workspace,


Before proceeding with Spring Data Rest let me give you some pointers on what all Spring Boot provides,
  • Production-ready services
  • Basic health-check and monitoring functions (not used in this application)
  • Pre-configured, embedded Tomcat server
  • Executable JAR packaging with all dependencies included
  • Very little overall configuration overhead (i.e. we just have to configure what we want to customize)
David Boross had written an excellent article out of his own experience with Spring Boot here. This contains information on what to expect from and how to use Spring Boot.

Usually, we use a servlet container such as Tomcat or Jetty to deploy and run our web application separately. While using Spring Boot it includes an embedded tomcat and all you have to do is, a Maven build that converts your whole application into an executable jar. Just run the jar file and access the application using default Tomcat's port (if you have not made an attempt to use a different port).

Let us go ahead and rewrite pom.xml file to include all dependencies,

<dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-rest</artifactId>
  </dependency>
  
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
  </dependency>
 </dependencies>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <start-class>com.programmingfree.springservice.Application</start-class>
  <java.version>1.7</java.version>
 </properties>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>


There are four dependencies we have included,

- thymeleaf (html templating)
- spring data jpa
- spring data rest
- mysql connector for java

Apart from the dependencies, the start class is also mentioned for the maven to identify where to start from. Finally spring boot maven plugin ensures packaging of your application into an executable jar.

As we have the structure and setup ready, let us proceed with building the CRUD application using Spring Data Rest and AngularJS in the front end. Before that, let us complete the MySql table setup required to bring up the Task Manager Application.

MySql Table - Task Manager Application

Use the following sql script to create task_list table against which we are gonna perform CRUD operations.

create database taskmanager;
use taskmanager;
create table task_list(task_id int not null auto_increment, task_name varchar(100) not null, task_description text,task_priority varchar(20),task_status varchar(20),task_start_time datetime not null default CURRENT_TIMESTAMP,task_end_time datetime not null default CURRENT_TIMESTAMP,task_archived bool default false,primary key(task_id));
insert into task_list values(1,'Gathering Requirement','Requirement Gathering','MEDIUM','ACTIVE',curtime(),curtime() + INTERVAL 3 HOUR,0);
insert into task_list values(2,'Application Designing','Application Designing','MEDIUM','ACTIVE',curtime(),curtime() + INTERVAL 2 HOUR,0);
insert into task_list values(3,'Implementation','Implementation','MEDIUM','ACTIVE',curtime(),curtime() + INTERVAL 3 HOUR,0);
insert into task_list values(4,'Unit Testing','Unit Testing','LOW','ACTIVE',curtime(),curtime() + INTERVAL 4 HOUR,0);
insert into task_list values(5,'Maintanence','Maintanence','LOW','ACTIVE',curtime(),curtime() + INTERVAL 5 HOUR,0);
select * from task_list;

Spring Data REST

The difference between simple Spring MVC RESTFul Web Services and Spring Data REST is that it combines the RESTFul architecture with Spring Data JPA (Java Persistence)/Gemfire/MongoDB/Neo4j to provide an easy way to implement database operations. If you are not familiar with Spring Data JPA or any other persistence library such as Hibernate, do not worry. You just have to understand the basic concept of it to get started. 

Java Persistence API (JPA) - Unlike writing a plain DAO that consists of plain JDBC code everywhere (my previous tutorial is an example of this scenario) full of PreparedStatements and SqlConnections etc, we just map the original fields in the database table to Java classes called Entities, provide SQL queries and let the persistence api handle the connections, query execution etc without writing much boilerplate code. 

Spring Data JPA & Spring Data REST takes a step forward and handles the DAO layer around data repositories with out of the box implementation for most commonly used queries. Though you can use @Query Annotation to write your own queries, you would not require that in most of the cases.

Hope that is enough of theory now. Even if you do not understand a single line of it, I am sure you will make it out in the course of implementation. So let us first write our Entity class.

Task.java

package com.programmingfree.springservice;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Id;

@Entity
@Table(name="task_list")
public class Task {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name="task_id")
 private int id;
 
 @Column(name="task_name")
 private String taskName;
 
 @Column(name="task_description")
 private String taskDescription;
 
 @Column(name="task_priority")
 private String taskPriority;
 
 @Column(name="task_status")
 private String taskStatus;
 
 @Column(name="task_archived")
 private int taskArchived = 0;

 public int getTaskId() {
  return id;
 }

 public void setTaskId(int taskId) {
  this.id = taskId;
 }

 public String getTaskName() {
  return taskName;
 }

 public void setTaskName(String taskName) {
  this.taskName = taskName;
 }

 public String getTaskDescription() {
  return taskDescription;
 }

 public void setTaskDescription(String taskDescription) {
  this.taskDescription = taskDescription;
 }

 public String getTaskPriority() {
  return taskPriority;
 }

 public void setTaskPriority(String taskPriority) {
  this.taskPriority = taskPriority;
 }

 public String getTaskStatus() {
  return taskStatus;
 }

 public void setTaskStatus(String taskStatus) {
  this.taskStatus = taskStatus;
 }

 public int isTaskArchived() {
  return taskArchived;
 }

 public void setTaskArchived(int taskArchived) {
  this.taskArchived = taskArchived;
 }

 @Override
 public String toString() {
  return "Task [id=" + id + ", taskName=" + taskName
    + ", taskDescription=" + taskDescription + ", taskPriority="
    + taskPriority + ",taskStatus=" + taskStatus + "]";
 }

}


The above class has @Entity annotation and @Table annotation with table name as an argument to it. You can clearly see each and every field in the table is mapped to java variables with @Column providing the actual name in the table. Rest of the code are getters and setters which will be present in any domain class usually.

As the entity is ready, next step is to create a repository class that serves as the data access layer in Spring Data Rest. Usually in any DAO, you will have methods to create, read, update and delete from database. But Spring makes it easy for you, that all these operations are covered out of the box and you just need an interface that extends CrudRepository class.

TaskRepository.java


package com.programmingfree.springservice;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface TaskRepository extends CrudRepository<Task, Integer> {

 List<Task> findByTaskArchived(@Param("archivedfalse") int taskArchivedFalse);
 List<Task> findByTaskStatus(@Param("status") String taskStatus);

}

TaskRepository extends CrudRepository. The type of entity and ID it works with, Task and Long are specified as generic parameters to CrudRepository. By extending CrudRepository, TaskRepository inherits several methods for working with Task persistence, including methods for saving, deleting, and finding Task entities.

Spring Data JPA also allows you to define other query methods by simply declaring their method signature. In the case of TaskRepository, this is shown with a findByTaskArchived() method which takes archivedTask as parameter. In a typical Java application, you’d expect to write a class that implements TaskRepository. But that’s what makes Spring Data JPA so powerful: You don’t have to write an implementation of the repository interface. Spring Data JPA creates an implementation on the fly when you run the application.

In the above code you can see @RepositoryRestResource annotation being used. This annotation is responsible for exposing this repository interface as a RESTFul resource. This is pretty much similar to @RestController which we used in plain Spring MVC REST to expose a controller as RESTFul resource.

Property File

By default Spring Boot will look for a property file in the package root directory called 'application.properties', this is a good place to customize your application. For example, as we have placed mysql connector jar in the pom.xml file, Spring Boot will look for mysql specific properties in this file. By Maven conventions, place this file into the src/main/resources directory so your build artefacts will be 
generated correctly. 

application.properties

# Replace with your connection string
spring.datasource.url=jdbc:mysql://localhost:3307/taskmanager

# Replace with your credentials
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.driverClassName=com.mysql.jdbc.Driver

Make the application Executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance. Remember we mentioned Application class as the start class in pom.xml file.

Application.java


package com.programmingfree.springservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;

@Configuration
@ComponentScan
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {

 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
  
 }

}

The @EnableJpaRepositories annotation activates Spring Data JPA. Spring Data JPA will create a concrete implementation of the TaskRepository and configure it to talk to a back end in-memory database using JPA.


Spring Data REST is a Spring MVC application. The @Import(RepositoryRestMvcConfiguration.class) annotation imports a collection of Spring MVC controllers, JSON converters, and other beans needed to provide a RESTful front end. These components link up to the Spring Data JPA backend.

The @EnableAutoConfiguration annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet is configured and registered for you — no web.xml necessary.

Templating

We have loaded thymeleaf as a dependency which is nothing but an html templating engine. Initially when the application class is run, all classes in the package in which the application class resides will be scanned. Hence let us write a controller that redirects the control to front end template.

HomeController.java


package com.programmingfree.springservice;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

 @RequestMapping("/home")
 public String home() {
  return "index";
 }

}

Next let us place the static resources and template files according to the standard directory structure expected by Spring Boot to process them.


I had copied all css and javascript files from my previous project into static folder. I had used index.jsp in my previous tutorial and here I am using index.html template file. 

index.html

<html ng-app="taskManagerApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>AngularJS Task Manager</title>
<link href='./css/style.css' rel="stylesheet" type="text/css" />
<link href='./css/css/font-awesome.css' rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
<script data-require="angular.js@*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular.js"></script>
  <script data-require="angular-animate@*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular-animate.js"></script>
<script type="text/javascript" src="./js/app.js"></script>
</head>
<body>

<div ng-controller="taskManagerController">
<h2 class="page-title">Task Manager using Spring Boot, Spring Data REST &amp; AngularJS</h2>
<h4 class="page-title">Demo &amp; Tutorial by <a href="">Priyadarshini</a></h4>
<a href="http://www.programming-free.com/2014/07/spring-data-rest-with-angularjs-crud.html" class="button-red" style="text-align:center;width:70px;margin-left:45%;margin-right:40%">Tutorial</a> 
 <div id="task-panel" class="fadein fadeout showpanel panel"  ng-show="toggle"> 
  <div class="panel-heading">
   <i class="panel-title-icon fa fa-tasks"></i>
   <span class="panel-title">Recent Tasks</span>
   <div class="panel-heading-controls">
    <button ng-click="toggle = !toggle" class="btn-panel">Add New Task</button>
    <button class="btn-panel" confirmed-click="archiveTasks()" ng-confirm-click="Would you like to archive completed tasks?">Clear completed tasks</button>
   </div>
  </div>
  <div class="panel-body">
   <div class="task" ng-repeat="task in tasks">
    <span ng-if="task.taskPriority=='HIGH'" class="priority priority-red">
     {{task.taskPriority}}
    </span>
    <span ng-if="task.taskPriority=='MEDIUM'" class="priority priority-yellow">
     {{task.taskPriority}}
    </span>
    <span ng-if="task.taskPriority=='LOW'" class="priority priority-green">
     {{task.taskPriority}}
    </span>
    <div class="action-checkbox">
                    <input id="{{task._links.self.href}}" type="checkbox" value="{{task._links.self.href}}" ng-checked="selection.indexOf(task._links.self.href) > -1" ng-click="toggleSelection(task._links.self.href)" />
                    <label for="{{task._links.self.href}}" ></label>
                </div>
    <div ng-if="task.taskStatus=='COMPLETED'">
     <a href="#" class="checkedClass">
      {{task.taskName}}
     <span class="action-status">{{task.taskStatus}}</span>
     </a>
    </div>
    <div ng-if="task.taskStatus=='ACTIVE'">    
     <a href="#" class="uncheckedClass">
      {{task.taskName}}
      <span class="action-status">{{task.taskStatus}}</span>
     </a>
    </div>
   </div>
  </div>
 </div>
 <div id="add-task-panel" class="fadein fadeout addpanel panel" ng-hide="toggle">
  <div class="panel-heading">
   <i class="panel-title-icon fa fa-plus"></i>
   <span class="panel-title">Add Task</span>
   <div class="panel-heading-controls">
    <button ng-click="toggle = !toggle" class="btn-panel">Show All Tasks</button>
   </div>
  </div>
  <div class="panel-body">
   <div class="task" >
    <table class="add-task">
     <tr>
      <td>Task Name:</td>
      <td><input type="text" ng-model="taskName"/></td>
     </tr>
     <tr>
      <td>Task Description:</td>
      <td><input type="text" ng-model="taskDesc"/></td>
     </tr>
     <tr>
      <td>Task Status:</td>
      <td>
       <select ng-model="taskStatus" ng-options="status as status for status in statuses">
        <option value="">-- Select --</option>      
            </select>
      </td>
     </tr>
     <tr>
      <td>Task Priority:</td>
      <td>
       <select ng-model="taskPriority" ng-options="priority as priority for priority in priorities">
        <option value="">-- Select --</option>
       </select>
      </td>
     </tr>
     <tr>
      <td><br/><button ng-click="addTask()" class="btn-panel-big">Add New Task</button></td>
     </tr>
    </table>        
   </div>
  </div>
 </div>
</div>
</body>
</html>


app.js

var taskManagerModule = angular.module('taskManagerApp', ['ngAnimate']);

taskManagerModule.controller('taskManagerController', function ($scope,$http) {
 
 var urlBase="";
 $scope.toggle=true;
 $scope.selection = [];
 $scope.statuses=['ACTIVE','COMPLETED'];
 $scope.priorities=['HIGH','LOW','MEDIUM'];
 $http.defaults.headers.post["Content-Type"] = "application/json";

    function findAllTasks() {
        //get all tasks and display initially
        $http.get(urlBase + '/tasks/search/findByTaskArchived?archivedfalse=0').
            success(function (data) {
                if (data._embedded != undefined) {
                    $scope.tasks = data._embedded.tasks;
                } else {
                    $scope.tasks = [];
                }
                for (var i = 0; i < $scope.tasks.length; i++) {
                    if ($scope.tasks[i].taskStatus == 'COMPLETED') {
                        $scope.selection.push($scope.tasks[i].taskId);
                    }
                }
                $scope.taskName="";
                $scope.taskDesc="";
                $scope.taskPriority="";
                $scope.taskStatus="";
                $scope.toggle='!toggle';
            });
    }

    findAllTasks();

 //add a new task
 $scope.addTask = function addTask() {
  if($scope.taskName=="" || $scope.taskDesc=="" || $scope.taskPriority == "" || $scope.taskStatus == ""){
   alert("Insufficient Data! Please provide values for task name, description, priortiy and status");
  }
  else{
   $http.post(urlBase + '/tasks', {
             taskName: $scope.taskName,
             taskDescription: $scope.taskDesc,
             taskPriority: $scope.taskPriority,
             taskStatus: $scope.taskStatus
         }).
    success(function(data, status, headers) {
    alert("Task added");
             var newTaskUri = headers()["location"];
             console.log("Might be good to GET " + newTaskUri + " and append the task.");
             // Refetching EVERYTHING every time can get expensive over time
             // Better solution would be to $http.get(headers()["location"]) and add it to the list
             findAllTasks();
      });
  }
 };
  
 // toggle selection for a given task by task id
   $scope.toggleSelection = function toggleSelection(taskUri) {
     var idx = $scope.selection.indexOf(taskUri);

     // is currently selected
        // HTTP PATCH to ACTIVE state
     if (idx > -1) {
       $http.patch(taskUri, { taskStatus: 'ACTIVE' }).
    success(function(data) {
        alert("Task unmarked");
              findAllTasks();
      });
       $scope.selection.splice(idx, 1);
     }

     // is newly selected
        // HTTP PATCH to COMPLETED state
     else {
       $http.patch(taskUri, { taskStatus: 'COMPLETED' }).
    success(function(data) {
     alert("Task marked completed");
              findAllTasks();
      });
       $scope.selection.push(taskUri);
     }
   };
   
 
 // Archive Completed Tasks
   $scope.archiveTasks = function archiveTasks() {
          $scope.selection.forEach(function(taskUri) {
              if (taskUri != undefined) {
                  $http.patch(taskUri, { taskArchived: 1});
              }
          });
          alert("Successfully Archived");
          console.log("It's risky to run this without confirming all the patches are done. when.js is great for that");
          findAllTasks();
   };
 
});

//Angularjs Directive for confirm dialog box
taskManagerModule.directive('ngConfirmClick', [
 function(){
         return {
             link: function (scope, element, attr) {
                 var msg = attr.ngConfirmClick || "Are you sure?";
                 var clickAction = attr.confirmedClick;
                 element.bind('click',function (event) {
                     if ( window.confirm(msg) ) {
                         scope.$eval(clickAction);
                     }
                 });
             }
         };
 }]);

Note that the URI to query the exposed RESTFul repositories had changed in the app.js file. If you are doubtful about how angularjs works in index.html file and communicates with the backend, please refer to my previous article which will give you an idea of how AngularJS can be made to work with Spring MVC. If you are new to AngularJS, then you might want to have a look at the basics once to get started.

We are done with the coding. To build the project,

Right click on pom.xml file -> Run as -> Run Configurations -> Select Maven Build -> New Launch Configuration -> Select your project locations -> Mentions Goals as clean install package -> Run



After successfully running the project, refresh workspace once and you can see the executable jar file under target folder here,


Open command prompt to execute jar file and hit http://localhost:8080/home to see the task manager application working.

 java - jar target/spring-data-rest-angular-0.0.1-SNAPSHOT.jar



Keep yourself subscribed for getting programmingfree articles delivered directly to your inbox once in a month. Thanks for reading!

Subscribe to GET LATEST ARTICLES!


Related

Trending 1607721071847268222

Post a Comment

  1. Thanks

    Your project on my computer is working perfectly, the problem comes when I change the project to to the web. In this article shows how to do this: http://spring.io/guides/gs/convert-jar-to-war-maven/.

    The problem I am having is as follows: not get access to the resources folder files.

    Could you please tell me how to access the same files converted for web project (war)?

    ReplyDelete
  2. hi

    spring data rest will not require service layer? As per this example it seems to indicate that we dont need service layer.

    ReplyDelete
  3. as additional information
    you can use ng-class for make decision which one required.
    ng-class="task.taskPriority=='HIGH'?priority priority-red:(task.taskPriority=='MEDIUM'?priority priority-yellow:priority priority-green)"

    ReplyDelete
  4. hi, thanks for the tutorial, but when I download the code and starting to run as Spring Boot App, I am getting this exception all over and its not starting:
    Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

    Any idea?

    ReplyDelete
    Replies
    1. Hi I also face the same issue and fixed by setting the dialect property in the application.prerties file as below. Please note use dialect property of your database.

      spring.jpa.database-platform= org.hibernate.dialect.MySQL5Dialect

      Delete
  5. First of all, thank you for a great tutorial! It provided just enough of information for me to go learn what I was missing. I learned some interesting things about AngularJS, Spring Data, and Spring Boot. I changed out the IDE to Intellij and the database to Postgres. I also added the start and end time fields as they are required for adding a task. Thank you again.

    ReplyDelete
  6. Great article Priya and nice to see such enthusiasm in the writing. This worked a treat and was a perfect follow-up to the previous tutorial and was faster to build. I like that you covered topics that speed up development in Spring Boot too. I tested this with MariaDB and MySQL and worked great. Thanks again!

    ReplyDelete
  7. Hello..
    I didnt understand where you are mapping the $http Url to find the rest service.

    $http.get(urlBase + '/tasks/search/findByTaskArchived?archivedfalse=0')

    Your project works fine but when I created my own project with similar concepts uanble to plugin the REST service url correctly.
    Please help.

    ReplyDelete
    Replies
    1. We have exposed all query methods in the TaskRepository class using @RepositoryRestResource. If you dont have this annotation, you wont be able to access it as a search resource with '/search/querymethodname' like how we have in this example.

      Read this for better understanding - http://docs.spring.io/spring-data/rest/docs/current/reference/html/#repository-resources.search-resource

      Delete
    2. You need a plural s in the url, you see the object in the repository is "Task", that maps to /tasks
      Our object is "Customer", maps to /customers
      etc

      Delete
    3. Spring Data REST exposes a collection resource named after the uncapitalized, pluralized version of the domain class the exported repository is handling. Both the name of the resource and the path can be customized using the @RepositoryRestResource on the repository interface...


      @Priya Darshini thanks for the post .. Post is really awesome ,but even I stuck in this to find where is tasks/search/... located ..I read your previous post where you had written separate controller for these api,when I failed to find these url ,i almost lost ,googled ,then thought to ask you in comment ,fortunately I found my answer in comment sections . Kindly mention about this in your post itself.
      Thank you for the wonderful explanation

      Delete
    4. Hi....I understand that object is "Customer", maps to /customers but what is the use of "search" here ?
      I am also facing this issue. Kindly help.

      Delete
  8. hi Priya...very nice article...thanks a lot.
    I think there is a tight coupling between Repository name and Model class name in Spring data. I tried to connect with my Oracle DB and my table name is 'CLMS_AUTO_INV_CONTROL' (@Entity
    @Table(name="CLMS_AUTO_INV_CONTROL")
    public class ClmsAuto {), and my repository as : @RepositoryRestResource
    public interface ClmsAutoRepository extends CrudRepository {, rest all are same...and after hitting the URL (localhost:8080/home), when I click 'Add New Task' button, I get the error in console : "o.s.web.servlet.PageNotFound : Request method 'POST' not supported". Kinldy help me.

    ReplyDelete
  9. hello i'm having the same problem of Ikshvak Iks and is the following:
    hi, thanks for the tutorial, but when I download the code and starting to run as Spring Boot App, I am getting this exception all over and its not starting:
    Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

    ReplyDelete
  10. i would like to know wha t to do to avoid hibernate dialect error and why is not starting the project it also says something about the embebed tomcat that is not loading
    thanks in advance

    ReplyDelete
  11. [@Scorpionloco]
    Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set:

    I think for this issue you need to set the datasource.platform in your properties file.

    #Sample is given below:-
    spring.datasource.platform=postgres

    example:-
    spring.jpa.database=POSTGRESQL
    spring.datasource.platform=postgres
    spring.jpa.show-sql=true
    spring.jpa.hibernate.ddl-auto=create-drop
    spring.database.driverClassName=org.postgresql.Driver
    spring.datasource.url=jdbc:postgresql://localhost:5432/NGP_DB
    spring.datasource.username=test
    spring.datasource.password=test

    ReplyDelete
  12. [@Priya]
    Can u explain why we need to use the url "/tasks/search/..." on server call?

    ReplyDelete
  13. Can you please let me know how insert command is working here. I got that as the entity is mapped with table so for /task the select statement is executing.So how a new task is added..as i am not able to see any save method.

    ReplyDelete
  14. Very good article, this helped me to start my spring boot+rest+angular2 learning more practical

    ReplyDelete
  15. Hi,

    I am having problem with my project and can't figure a way forward without rewriting using http versus resource. Would you mind looking at my source to see my problem? https://github.com/jasonscott5471/TestChqApp
    Basically, I can't figure out how to get the checkbox control which is firing to then call the factory service method which is tied to a put command. Can't find any examples. Thanks in advance.

    ReplyDelete
  16. Source project not available

    ReplyDelete
  17. this one is a better example on spring data, H2 with angular frontend on github https://github.com/mrin9/Angular-SpringBoot-REST-JWT

    ReplyDelete
    Replies
    1. Hi, your git project looks great! i am facing some problem running it, could you share your email-id at vishwanath12520@gmail.com.

      Thanks
      Vishwa
      682-557-7372

      Delete
  18. HI Priya,
    Thanks for the nice article.
    I had a question regarding JSON data. Is there a way we can build our own custom JSON data in controller Applcation class before sending it to front end. Is there a way to reach out to you via email.

    ReplyDelete
  19. Gostaria de deixar a recomendação para o pessoal que está começando também fazerem o download gratuito do e-book API RESTful com Spring Boot.
    Baixem GRÁTIS no link → https://www.javaavancado.com/ebook-spring-boot/index.html

    ReplyDelete
  20. Thanks for the Information, Get the best java training in chennai at affordable fees from hope tutors.

    ReplyDelete
  21. Above article is valuable to read .the article says how to upgrade all.the concept is good.
    Angularjs Training in Chennai

    ReplyDelete
  22. I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.
    Click here |Norton Customer Service
    Click here |Mcafee Customer Service
    Click here |Phone number for Malwarebytes
    Click here |Hp printer support number
    Click here |Canon printer support online

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. I would definitely thank the admin of this blog for sharing this information with us. Waiting for more updates from this blog admin.
    salesforce Training in Bangalore
    uipath Training in Bangalore
    blueprism Training in Bangalore

    ReplyDelete
  26. Wow...What an excellent informative blog, really helpful. Thank you so much for sharing such a wonderful article with us.keep updating..
    aws Training in Bangalore
    python Training in Bangalore
    hadoop Training in Bangalore
    angular js Training in Bangalore
    bigdata analytics Training in Bangalore

    ReplyDelete
  27. BEST EMAIL SUPPORT SERVISES
    Happytosupport is a 100% US based provider of Online solution. Our skilled, experienced and professional technicians support both home users and small businesses as well.




    Email Support


    Roadrunner Customer Care Number

    Verizon Customer Care Number

    Yahoo
    Email Support


    Gmail Customer Care Number


    AOL Email Customer Care Number

    ReplyDelete
  28. This is a wonderful article...Railways in India will generate employment of around 14 crore man-days in the upcoming year. Every year, RRB Recruitment 2020 Notification is released for filling Lakhs of Vacancies

    ReplyDelete
  29. I have an issue as follows

    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    ReplyDelete
  30. Computer education is a necessity these days as tasks in all professions has become digitized. artificial intelligence course in hyderabad

    ReplyDelete
  31. actually, the science of data creates a connection between the two innovations. With the combination of these parts, scientists can get a deeper insight into the data. best course to learn artificial intelligence

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. A well-developed data science course helps you gain expertise in data science and gain an advantage over your peers. data science course syllabus

    ReplyDelete
  34. Capitalinfosolutions is the perfect place to survive. Salesforce training in Chennai

    ReplyDelete
  35. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.

    data science course in India

    ReplyDelete
  36. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!
    Artificial Intelligence Course

    ReplyDelete
  37. This is such a great resource that you are providing and you give it away for free! good presentation skills | Virtual team building | Piano Lessons Singapore

    ReplyDelete
  38. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Data Science Training in Hyderabad

    ReplyDelete
  39. More impressive Blog!!! Its more useful for us...Thanks for sharing with us...
    Wonderful Blog.... Thanks for sharing with us...
    Hadoop Training in Chennai
    Hadoop Training in Bangalore
    Big Data Onlie Course
    Big Data Training in Coimbatore

    ReplyDelete
  40. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    data science training in noida

    ReplyDelete
  41. Really Nice Information It's Very Helpful All courses Checkout Here.
    data scientist certification malaysia

    ReplyDelete
  42. I must appreciate you for providing such valuable content for us. To make our dreams a reality, everyone has to put up a hard struggle in their life. Here I am making my small effort to arrange up the list of highest paying Jobs in India. We provide one of the best courses for you.
    1) Data Science course in Delhi
    2) Artificial Intelligence Course in Delhi
    3) Machine Learning course in Delhi
    4) Business Analytics courses in Delhi
    5) Digital marketing course in Delhi
    6) Full Stack Software Developer course in Delhi.

    ReplyDelete
  43. Baccarat is money-making and it is exceptional availability. Optimal For you it is being sold that there are pretty interesting choices. And that is considered to be a thing that's quite diverse And it is rather something that's quite prepared to hit with Pretty much the most great, too, is a very good option. Moreover, it is an extremely interesting solution. It is a better way which can earn money. Superbly ready The number of best-earning baccarat will be the accessibility of making one of the most cash. Pretty much as possible is very well suited for you A substitute that can be sure. To a wide range of efficiency and accessibility And see excellent benefits as well.
    บาคาร่า
    ufa
    ufabet
    แทงบอล
    แทงบอล
    แทงบอล

    ReplyDelete
  44. ได้โดยที่จะทำให้คุณนั้นสามารถสร้างกำไรจากการเล่นเกมส์เดิมพันออนไลน์ได้เราแนะนำเกมส์ชนิดนี้ให้คุณได้รู้จักก็เพราะว่าเชื่อว่าทุกคนนั้นจะต้องรู้วิธีการเล่นและวิธีการเอาชนะเกมม สล็อต าแทบทุกคนเพราะเราเคยเล่นกันมาตั้งแต่เด็กเด็กหาคุณได้เล่นเกมส์คาสิโนออนไลน์ที่คุณนั้นคุ้นเคยหรือจะเป็นสิ่งที่จะทำให้คุณสามารถที่จะได้กำไรจากการเล่นเกมได้มากกว่าที่คุณไปเล่นเกมส์คาสิโนออนไลน์ที่คุณนั้นไม่เคยเล่นมาก่อนและไม่คุ้นเคย เราจึงคิดว่าเกมส์ชนิดนี้เป็นเกมส์ที่น่าสนใจมากๆที่เราอยากจะมาแนะนำให้ทุกคนได้รู้จักและได้ใช้บริการ

    ReplyDelete
  45. You totally coordinate our desire and the assortment of our data.
    ai course in pune

    ReplyDelete

  46. This is extremely beneficial information!! Exceptional work. All this is important to learn to understand. Thank you for giving this helpful information. Keep publishing articles like this in the future.

    digital marketing course in hyderabad
    digital marketing training in hyderabad

    ReplyDelete

  47. PC Crack
    You've created a very useful website.
    I really like your blog as it is not only extremely useful but also creative at the same time.
    License Cracked

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. Thanks for sharing informative post. Are looking for best Tamil typing tool online, make use of our Tamil typing software to make translation faster. Thirumana Porutham in Tamil | Samacheer Kalvi Books PDF

    ReplyDelete
  50. Every photographer has their own style when it comes to photography. Therefore you may want to decide on the type of photography you want to get done. For example, if you want them to shoot realistic photos, make sure you ask them about it. Destination wedding videography

    ReplyDelete
  51. What are you most looking forward to in the next 10 years?ThingsyoudoforbeautyWhat chore do you absolutely hate doing?INDIA'S BEST OFF SITE SEO PROVIDER CHEAPEST AND FASTEST OFF SITE SEO SERVICE IN INDIA

    ReplyDelete
  52. The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought you have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.data science course in surat

    ReplyDelete
  53. At Standout Music Studio, we offer professional Singing Lessons in sydney, Australia for all levels, from beginner to advanced. Our experienced singing teachers will help you develop your vocal technique, improve your range and projection, and build confidence.

    ReplyDelete
  54. Asset Plus is a Real Estate Buyers Agent in Brisbane, Australia. We help buyers find and purchase property in Brisbane and the surrounding areas. We offer our clients a wide range of services, including property search, property management, and investment advice. Contact us today to learn more about how we can help you find the perfect property.

    ReplyDelete
  55. Looking for a great Hotel in Mathura Near Railway Station? We offer clean, comfortable rooms at great prices. We're just 5 minutes from the Mathura Railway Station, making us the perfect choice for travelers. Book your room today!

    ReplyDelete
  56. Are you looking for a great way to keep your home cool in the summer and warm in the winter? Outdoor Roller Blinds in Melbourne, Australia are a great solution! Divine Interiors offers a wide selection of high-quality roller blinds that are perfect for any home in Melbourne

    ReplyDelete
  57. Thanks for sharing this useful article. Get to know about the best website design company kottayam.

    ReplyDelete
  58. Thanks for your sharing such a useful information. This is really helpful to me. Looking for exceptional online tuition for CBSE board students? Ziyyara’s CBSE Online Tuition is designed to provide personalized learning experiences from the comfort of your own home.
    For more info contact +91-9654271931 or visit Online tuition for cbse board

    ReplyDelete
  59. Thanks for sharing this information, If you want you enhance your skills in software testing. Read the blog:"Online vs In-Person Software Testing Courses: Which is Right for You?".

    ReplyDelete
  60. CRUD operations are the backbone of many applications, and this tutorial on using Spring Data Rest and Angular with Spring Boot is a gem. It brilliantly combines backend and frontend technologies, making it easier for developers to create powerful and interactive applications. A must-read for anyone looking to master CRUD operations!

    Read More...

    ReplyDelete
  61. I hope the next blog I read does not disappoint me as much as this one did. I mean, I understand it was my choice to read, but I thought you have something interesting to say. All I hear is a lot of whining about something that you could change if you weren't so busy asking for attention. I particularly appreciate the topic about how government expenditure can be used to create jobs and increase consumer spending.
    semi truck accident

    ReplyDelete
  62. Couples nowadays often face the challenge of infertility, which can be caused by different factors like a sedentary lifestyle and the natural process of aging that affects both men and women. Thankfully, advancements in medical technology have introduced IVF treatment as a solution to this problem. If you are contemplating IVF, the next crucial step is to find the most suitable IVF specialist in Delhi. Selecting the right IVF doctor in Delhi is a vital decision that will greatly impact your journey towards becoming parents.

    Driven by a passion for helping couples achieve their dream of parenthood, this IVF specialist in Delhi continues to make significant contributions to reproductive healthcare, earning trust and recognition in the field.

    ReplyDelete

emo-but-icon

SUBSCRIBE


item