Build your application using AngularJS and Spring data JPA?

AngularJS and Spring data JPA

Изградба на вашата апликација со користење на AngularJS и пролетта податоци JPA,,en,Може да се изгради ефикасна веб-базирана апликација со AngularJS и,,en,помагајќи да се изгради ефикасна и динамична,,en,со што се намалува оптоварувањето на серверите и нуди попаметни страница освежувања,,en,пролетните податоци JPA овозможува да се постави слој на база на податоци што му овозможува на клиентот брзо и прецизно да ги прима податоците што ги бара,,en,AngularJS е отворен код и,,en,базирана рамка за градење на динамички веб апликации,,en,AngularJS е обезбедена и одржувана од Google,,en,значително го намалува напорот потребен за развој на апликации за една страница,,en,Таа обезбедува рамка со која се намалуваат напорите на програмерите да пишуваат код,,en,Главните карактеристики на AngularJS се,,en,рамка ви овозможува да го поделите бизнис логичкиот слој,,en,слој на податоци,,en

Преглед

You can build an efficient web-based application with the AngularJS and the Spring Data JPA. Each component has a distinct role to play. While the AngularJS acts as the rich client, helping to build efficient and dynamic Single Page Applications (SPA) which reduces load on servers and offers smarter page refreshes, the Spring Data JPA allows to set up a smart database layer that allows the client to quickly and accurately receive the data it requested.








What is Angular JS?

The AngularJS is an open-source and Го вклучите Javascript--based framework for building dynamic web applications. AngularJS is provided and maintained by Google. AngularJS significantly reduces the effort needed in developing Single Page Applications (SPA). It provides a framework which reduces developer effort to write code. The main features of AngularJS are:

  • The Model-View-Controller (MVC) framework allows you to split the business logic layer, the data layer, и слој за презентација во одделни делови, така што ќе можете да работите на секој дел поединечно,,en,Слоевите се лабаво заедно со едни со други,,en,Не е потребен значаен напор за вршење податоци,,en,Вие не треба да напишете посебен код за да ги поврзете податоците со HTML,,en,AngularJS го прави тоа за вас,,en,Бидејќи AngularJS е рамка,,en,тоа обезбедува многу претходно конфигурирани ресурси кои можете да ги користите,,en,Да се ​​изврши,,en,манипулација,,en,претходно ќе треба да напишете многу JavaScript код,,en,Но, со AngularJS,,en,не треба да го сторите тоа затоа што ги обезбедува фрагменти,,en,Што е пролет податоци JPA,,en,Сите апликации на претпријатието треба да комуницираат со база на податоци за да зачувуваат податоци,,en,интеракција со база на податоци никогаш не била мазна, бидејќи,,en. The layers are loosely coupled with each other.
  • No significant data binding effort required. You do not need to write special code to bind the data to HTML, AngularJS does it for you.
  • Since the AngularJS is a framework, it provides a lot of pre-configured resources that you can use. To perform DOM manipulation, you would earlier need to write a lot of JavaScript code. But with AngularJS, you do not need to do so because it provides the snippets.

What is Spring Data JPA?

All enterprise applications need to interact with database to store and retrieve data. However, interacting with database has never been smooth because:

  • Потребно е да се напише премногу кодот за да се извршат едноставни прашања и да се изврши паганизација која е губење на ресурси,,en,Развивачите на софтвер користат неслободна рамка за да комуницираат со бази на податоци, што не е беспрекорна трансакција,,en,Релациони модели на објекти во врска со бази на податоци нудат предизвици за пристап до податоци до програмерите,,en,Пролетниот податок JPA може да го реши пристапот до базата на податоци и проблемот со пребарување на податоци преку обезбедување слој за пристап до податоци,,en,Од перспектива на инвеститорот,,en,сето тоа треба да се направи е да се напишат интерфејсите на складиштето,,en,вклучувајќи сопствени методи за пронаоѓање, а остатокот е направено од пролетта податоци JPA,,en,Главните карактеристики на пролетта податоци JPA се,,en,поддршка за градење на репозиториуми базирани на пролет и ЈПА,,en,транспарентна ревизија на класата на доменот,,en,поддршка за паганизација,,en.
  • Software developers use proprietary framework to interact with the data bases which is not a seamless transaction.
  • Relational object models with reference to databases offer data access challenges to developers.

The Spring Data JPA can solve the database access and data retrieval problem by providing a data access layer. From the developer’s perspective, all that needs to be done is to write the repository interfaces, including custom finder methods and the rest is done by Spring Data JPA. The main features of Spring Data JPA are: support for building Spring and JPA-based repositories; transparent auditing of domain class; support for pagination, динамично извршување на барањето и може да интегрира сопствен код за пристап до податоци,,en,Причини да се изгради апликација,,en,Главните причини треба да се претпочитаат комбинацијата на AngularJS и Spring Data JPA подолу,,en,Од гледна точка на корисничко искуство,,en,беспрекорен пред крајот или клиент и сервер е неопходно,,en,Серверот треба да биде способен за непречено пристап до базата на податоци,,en,испраќајте прашања и добијте ги посакуваните одговори во препознатлив формат,,en,Колку побрзо процесот е завршен,,en,толку подобро е за корисничкото искуство,,en,Пролетните податоци JPA им овозможува на серверот да има брза и мазна трансакција,,en,Бидејќи AngularJS е рамка во која,,en,сите логички единици можат да се одвојат,,en,тоа може да комуницира добро со база на слој поставен со помош на пролетта податоци JPOA,,en.








Must read – Interesting articles on Spring framework

Reasons to build application

The main reasons a combination of AngularJS and Spring Data JPA should be preferred are mentioned below.

  • From the perspective of user experience, a seamless front-end or client and a server is necessary. The server should be able to smoothly access the database, send queries and retrieve the desired responses in a recognizable format. The faster the process is completed, the better it is for the user experience. Spring Data JPA enables the server to have a quick and smooth transaction.
  • Since the AngularJS is a framework in which, all logical units can be separated, it can interact well with the database layer set up with the help of the Spring Data JPOA, на тој начин отворајќи го патот за непречено пребарување и систем за одговор,,en,следниот пристап треба да се преземат при градење на апликација со AngularJS и Spring Data JPA,,en,Прво дефинирајте ја структурата на проектот,,en,Во структурата,,en,мора да ги дефинирате сите папки,,en,подпапки,,en,зависности и ресурси,,en,што и да е применливо во контекст на проектот,,en,Дефинирајте ги параметрите за управување со зависност или конфигурацијата во POM.xml датотеката,,en,проектот за прибежиште POM обично ќе наследи од проектот пролет-подигање-стартер-родител,,en,Дефинирајте ја главната класа на пролетта,,en,Spring Boot нуди класа SpringApplication да подигне пролетна апликација која ќе се стартува од главната,,en,JPA конфигурација,,en,ќе ги поставите следните складишта,,en,Пролетни податоци @EnableJpaRepositories,,en,Прозорец за подигање на податоци,,en,и пролетта говорница DataSourceBuilder,,en.

Approach

Typically, the following approach should be taken when building an application with AngularJS and Spring Data JPA.

  • Define the project structure first. In the structure, you must define all the folders, subfolders, dependencies and resources, whichever applicable in the context of the project.
  • Define the dependency management parameters or configuration in the POM.xml file. In most of the cases, the maven project POM will usually inherit from the spring-boot-starter-parent project.
  • Define the Spring Boot main class. Spring Boot offers the SpringApplication class to bootstrap a Spring application that will be started from the main() метод.
  • JPA configuration. In this step, you will be setting up the following repositories: Spring Data @EnableJpaRepositories; Spring Boot DataSourceProperties; and Spring Boot DataSourceBuilder.



Стапици и ограничувања,,en,Комбинацијата на AngularJS и пролетните податоци JPA е одлична за интерактивност на серверот и базата, но само ако одредени предизвици се управуваат добро,,en,AngularJS е MVC рамка и сите негови логички единици,,en,слој на деловна логика,,en,и презентирачки слој - може да се одделат во различни логички делови,,en,Иако ова дава многу флексибилност,,en,исто така може да создаде проблеми со компатибилноста со слојот од базата на податоци создаден со пролетните податоци JPA,,en,слојот за презентација може да не работи,,en,ако е изменета или заменета со слојот на база на податоци,,en,тоа е императив дека секогаш кога има било какви промени во,,en,MVC рамка,,en,се има предвид компатибилноста со слојот на базата на податоци,,en,Научете подигање на пролет,,en,Видео упатства,,en,Градење на апликацијата,,en,ние ќе се обидеме да изградиме примерочна апликација со AngularJS,,en

The combination of AngularJS and Spring Data JPA is great for server and database interactivity but only if certain challenges are managed well. However, the AngularJS is an MVC framework and all its logical units — business logic layer, the data layer, and presentation layer – can be separated into distinct logical sections. Though this gives a lot of flexibility, it may also create compatibility issues with the database layer created with Spring Data JPA. For example, the presentation layer may not work, if changed or replaced with the database layer. So, it is imperative that whenever there are any changes in the AngularJS MVC framework, the compatibility with the database layer is kept in mind.

Learn Spring boot – Video tutorials

Building the application (Code)

In this section, we will try to build a sample application having AngularJS, Пролет и JPA интеграција,,en,Тоа ќе биде апликација за подигање пролет,,en,ние ќе ја провериме датотеката pom.xml,,en,Во оваа датотека,,en,ќе имаме зависности за пролетниот подигање,,en,мачор сервер,,en,Примерок pom.xml датотека,,en,пролет-boot-starter-data-jpa,,en,пролет-подигање-стартер-веб,,en,пролет-boot-стартер-мачор,,en,обезбедени,,en,mysql-конектор-java,,en,траење,,en,ние ќе ја провериме класата на податоци модел,,en,Ова е модел класа одбележан со табелата во базата на податоци,,en,Имињата на колоните во табелата ќе бидат мапирани со ентитетите на модели со користење на прибелешки,,en,Моделот класа треба да се имплементира Serializable интерфејс,,en,Класа на модел на вработени,,en,пакет com.techalpine.spring.examples,,en,увоз javax.persistence.Column,,en,јавна класа Вработениот имплементира Сериализира,,en,приватна статична конечна долга serialVersionUID = -3008976332242234306L,,en,приватен долг id,,en,@Column,,en,private firstName,,en,приватна низа lastName,,en,Прва низа на низа,,en,Стринг lastName,,en. It will be a Spring boot application.

First, we will check the pom.xml file. In this file, we will have dependencies for Spring boot, MySQL, tomcat server.

Listing 1: Sample pom.xml file

[код]

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-tomcat</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

[/код]

Now, we will check the data model class. This is the model class mapped with the table in the database. Table column names will be mapped with the model entities by using annotations. The model class should be implementing Serializable interface.








Listing 2: Employee model class

[код]

package com.techalpine.spring.examples

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

@Entity

@Table(name = “employee”)

public class Employee implements Serializable {

private static final long serialVersionUID = -3008976332242234306L;

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private long id;

@Column(name = “firstname”)

private String firstName;

@Column(name = “lastname”)

private String lastName;

public Employee(String firstName, String lastName) {

this.firstName = firstName,,en,this.lastName = lastName,,en,јавна долга забава,,en,врати id,,en,public void setId,,en,долг ид,,en,this.id = id,,en,јавен стринг getFirstName,,en,public void setFirstName,,en,јавен Стринг getLastName,,en,вратирај lastName,,en,public void setLastName,,en,врати String.format,,en,id =% d,,en,firstName = '% s',,en,lastName = '% s',,en,ние ќе направиме уште една моделска класа,,en,што е за одговор порака,,en,Целта на оваа класа на модели е да ги држат податоците од одговорот,,en,Класа на модел на податоци за одговарање,,en,јавна класа ResponseData,,en,приватна статус на стринг,,en,приватни податоци за објект,,en,јавен одговорДода,,en,Статус на низа,,en,Податоци за објекти,,en,this.status = статус,,en,this.data = податоци,,en,јавен Стринг getStatus,,en,вратен статус,,en,public void setStatus,,en,јавен објект getData,,en,врати податоци,,en,public void setData,,en,По креирањето на класи на модел,,en,ние ќе создадеме класа на складиште,,en,Примерна класа на складиште,,en;

this.lastName = lastName;

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName,,en,this.lastName = lastName,,en,јавна долга забава,,en,врати id,,en,public void setId,,en,долг ид,,en,this.id = id,,en,јавен стринг getFirstName,,en,public void setFirstName,,en,јавен Стринг getLastName,,en,вратирај lastName,,en,public void setLastName,,en,врати String.format,,en,id =% d,,en,firstName = '% s',,en,lastName = '% s',,en,ние ќе направиме уште една моделска класа,,en,што е за одговор порака,,en,Целта на оваа класа на модели е да ги држат податоците од одговорот,,en,Класа на модел на податоци за одговарање,,en,јавна класа ResponseData,,en,приватна статус на стринг,,en,приватни податоци за објект,,en,јавен одговорДода,,en,Статус на низа,,en,Податоци за објекти,,en,this.status = статус,,en,this.data = податоци,,en,јавен Стринг getStatus,,en,вратен статус,,en,public void setStatus,,en,јавен објект getData,,en,врати податоци,,en,public void setData,,en,По креирањето на класи на модел,,en,ние ќе создадеме класа на складиште,,en,Примерна класа на складиште,,en;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

@ Отфрли

public String toString() {

return String.format(“Employee[id=%d, firstName=’%s’, lastName=’%s’]”, id, firstName, lastName);

}

}

[/код]

Now, we will make one more model class, which is for response message. Purpose of this model class is to hold the response data.

Listing 3: Response data model class

[код]

package com.techalpine.spring.examples

public class ResponseData {

private String status;

private Object data;

public ResponseData() {

}

public ResponseData(String status, Object data) {

this.status = status;

this.data = data;

}

public String getStatus() {

return status;

}

public void setStatus(String status) {

this.status = status;

}

public Object getData() {

return data;

}

public void setData(Object data) {

this.data = data;

}

}

[/код]

After creating the model classes, we will be creating a repository class.








Listing 4: Sample repository class

[код]

package com.techalpine.spring.examples

import java.util.List;

увоз org.springframework.data.repository.CrudRepository,,en,увоз com.techalpine.spring.examples.Employee,,en,јавниот интерфејс EmployeeRepository ја проширува CrudRepository,,en,Клиент,,en,findAll,,en,ние ќе создадеме една класа на примерок контролер како што е прикажано подолу,,en,Овде ќе провериме зачувување и враќање на дел од податоците за вработените,,en,Пример контролер класа,,en,увоз org.springframework.web.bind.annotation.PathVariable,,mr,увоз org.springframework.web.bind.annotation.RequestBody,,en,увоз com.techalpine.spring.examples.ResponseData,,en,увоз com.techalpine.spring.examples.EmployeeRepository,,en,јавна класа EmployeeController,,en,EmployeeRepository складиштето,,en,postemployee,,pl,метод = RequestMethod.POST,,en,јавна празнина postEmployee,,en,@RequestBody Вработен работник,,en,repository.save,,en,employee.getFirstName,,en,employee.getLastName,,en,findall,,en,јавен одговор findAll,,en,вработени = repository.findAll,,en,врати нов одговор,,en,По креирањето на дел од контролорот,,en;

import com.techalpine.spring.examples.Employee;

public interface EmployeeRepository extends CrudRepository<Customer, Long> {

Iterable<Customer> findAll();

}

[/код]

Now, we will be creating one sample controller class as shown below. Here we will checking saving and retrieval part of Employee data.

Listing 5: Sample controller class

[код]

package com.techalpine.spring.examples

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

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

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import com.techalpine.spring.examples.ResponseData;

import com.techalpine.spring.examples.Employee;

import com.techalpine.spring.examples.EmployeeRepository;

@RestController

public class EmployeeController {

@Autowired

EmployeeRepository repository;

@RequestMapping(value = “/postemployee”, method = RequestMethod.POST)

public void postEmployee(@RequestBody Employee employee) {

repository.save(new Employee(employee.getFirstName(), employee.getLastName()));

}

@RequestMapping(“/findall”)

public Response findAll() {

Iterable<Employee> employees = repository.findAll();

return new Response(“Done”, employees);

}

}

[/код]

After creating the controller part, ние ќе го разгледаме корисничкиот дел од апликацијата,,en,Овде ќе создадеме една ЈСП-страница со Англарните ознаки за да зачуваме и да ги добиеме податоците за вработените,,en,Примерок JSP страница со аголни JS тагови,,en,Spring Boot и JPA Пример,,en,meta http-equiv =,,en,Тип на содржина,,en,почетна скала = 1,,en,src =,,en,ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js,,en,js / angular.js,,en,netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css,,en,div class =,,en,контејнер,,en,ng-app =,,tl,стан,,en,Пролет JPA,,en,ред,,en,постконтролер,,en,col-md-3,,en,employeeForm,,en,ng-submit =,,tl,submitForm,,en,Име,,en,контрола,,en,Презиме,,en,форма-контрола,,en,тип на копче =,,en,btn btn-основно,,sv,postResultMessage,,es,getallemployeesController,,af,h3,,ar,Сите вработени,,en,копче кликнете =,,tl,getAllEmployees,,af,Земи ги сите вработени,,en,div ng-show =,,tl,showAllEmployees,,en,ul класа =,,en,листа-група,,en,li ng-repeat =,,tl,вработени во allemployees.data,,en,h4 класа =,,en,листа-група-елемент,,en,Emp Id,,en,employee.id,,en,Emp Име,,en,employee.firstName,,en,Презиме Емп,,en,employee.lastName,,en,li,,ku,getResultMessage,,en. Here we will create one JSP page with AngularJS tags to save and get Employee data.

Listing 6: Sample JSP page with Angular JS tags

[код]

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″

pageEncoding=”ISO-8859-1″%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<title>Spring Boot and JPA Example</title>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>

<meta name=”viewport” content=”width=device-width, initial-scale=1″ />

<script

src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js”></script>

<script src=”/js/angular.js”></script>

<link rel=”stylesheet”

href=”http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css” />

</head>

<body>

<div class=”container” ng-app=”app”>

<h1>AngularJS – Spring JPA – DB</h1>

<div class=”row”>

<div ng-controller=”postController” class =”col-md-3″>

<form name=”employeeForm” ng-submit=”submitForm()”>

<label>FirstName</label>

<input type=”text” name=”firstname” class =”форма- control” ng-model=”firstname” />

<label>LastName</label>

<input type=”text” name=”lastname” class =”form-control” ng-model=”lastname” />

<button type=”submit” class =”btn btn-primary”>Достават</button>

</форма>

<p>{{postResultMessage}}</p>

</div>

</div>

<div class=”row”>

<div ng-controller=”getallemployeesController” class =”col-md-3″>

<h3>All Employees</h3>

<button ng-click=”getAllEmployees()”>Get All Employees</button>

<div ng-show=”showAllEmployees”>

<ul class=”list-group”>

<li ng-repeat=”employees in allemployees.data”><h4 class=”list-group-item”>

<strong>Employee {{$index}}</strong><br />

Emp Id: {{employee.id}}<br />

Emp First Name: {{employee.firstName}}<br />

Emp Last Name: {{employee.lastName}}

</h4></li>

</ul>

</div>

<p>{{getResultMessage}}</p>

</div>

</div>

</div>

</body>

</html>

[/код]

Ова е страницата на ЈСП за доставување податоци за вработените и добивање на податоци за сите вработени,,en,Англарните JS и пролетните податоци JPA нуди одлична можност за изградба на робусна и динамична веб апликација доколку компатибилноста помеѓу слоевите на клиентите и слојот на база на податоци се управува интелигентно,,en,Пролетните податоци JPA е лесно да се имплементираат и користат,,en,програмерите ќе можат лесно да ги користат и да ги истражат своите податоци во базата на податоци,,en,techalpine.com/build-your-application-using-angularjs-and-spring-data-jpa,,en.

Must watch – Spring video tutorials








Заклучок

The AngularJS and Spring Data JPA offers a great opportunity to build a robust and dynamic web application if the compatibility between the client layers and the database layer is managed intelligently. Spring data JPA is easy to implement and use. So, the developers will be able to use it easily and persist their data in the database.


============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share