- In this kind of association, a foreign key column is created in owner entity. For example, if we make EmployeeEntity owner, then a extra column "ACCOUNT_ID" will be created in Employee table. This column will store the foreign key for Account table.

- To make such association, refer the Account entity in EmployeeEntity class as follow:
@OneToOne @JoinColumn(name="ACCOUNT_ID") private AccountEntity account;- @JoinColumn
- The join column is declared with the @JoinColumn annotation which looks like the @Column annotation, It is used in column owner column and mapped by used in other table. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
- mappedBy
- mappedBy is used. ‘mappedBy’ refers to the property name of the association on the owner side.AccountEntity.java
-
@OneToOne(mappedBy="account") private EmployeeEntity employee;
Wednesday, 5 December 2018
Hibernate one to one mapping
Hibernate Many-To-One Bidirectional
- One table has a foreign key column that references the primary key of associated table.In Bidirectional relationship, both side navigation is possible.

- We are discussing an example of Student and University relationship. Many student can enroll at one University. And one University can have many students.
@Entity @Table(name = "STUDENT") public class Student { @Id @GeneratedValue @Column(name = "STUDENT_ID") private long id; @Column(name = "FIRST_NAME") private String firstName; @ManyToOne(optional = false) @JoinColumn(name = "UNIVERSITY_ID") private University university; ------------------------ ------------------------ } @Entity @Table(name = "UNIVERSITY") public class University { @Id @GeneratedValue @Column(name = "UNIVERSITY_ID") private long id; @Column(name = "NAME") private String name; @Column(name = "COUNTRY") private String country; @OneToMany(mappedBy = "university", cascade = CascadeType.ALL) private Liststudents; } - @JoinColumn says that Student table will contain a separate column UNIVERSITY_ID which will eventually act as a foreign key reference to primary key of University table
Many to Many Annotation
- In this scenario, any given employee can be assigned to multiple projects and a project may have multiple employees working for it, leading to a many-to-many association between the two.

- We have an employee table with employee_id as its primary key and a project table with project_id as its primary key. A join table employee_project is required here to connect both sides.
- The model classes Employee and Project need to be created with JPA annotations:
@Entity @Table(name = "Employee") public class Employee { // ... @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "Employee_Project", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "project_id") } ) Setprojects = new HashSet<>(); // standard constructor/getters/setters } @Entity @Table(name = "Project") public class Project { // ... @ManyToMany(mappedBy = "projects") private Set employees = new HashSet<>(); // standard constructors/getters/setters } - Both the Employee class and Project classes refer to one another, which means that the association between them is bidirectional.
- In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations.
- @ManyToMany
- The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
- @JoinTable
- In our example, the owning side is Employee so the join table is specified on the owning side by using the @JoinTable annotation in Employee class
- @JoinColumn
- The @JoinColumn annotation is used to specify the join/linking column with the main table. Here, the join column is employee_id and project_id is the inverse join column since Project is on the inverse side of the relationship
- mappedBy
- In the Project class, the mappedBy attribute is used in the @ManyToMany annotation to indicate that the employees collection is mapped by the projects collection of the owner side
Thursday, 29 November 2018
LinkedList and Index
- They have a logical index, yes - effectively the number of times you need to iterate, starting from the head, before getting to that node.
- it can't directly search using index of the object
- Typically O(1) access by index is performed by using an array lookup, and in the case of a linked list there isn't an array - there's just a chain of nodes. To access a node with index N, you need to start at the head and walk along the chain N times... which is an O(N) operation.
import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LnkedListNthh { public static void main(String[] args) { LnkedListNthh app = new LnkedListNthh(); LinkedListlist = app.createList(); app.nthElement(list, 2); app.SecondLastElement(list); } private void nthElement(LinkedList list, Integer n) { list.get(n); System.out.println(n + "th Element is " + list.get(n)); } private void SecondLastElement(LinkedList list) { System.out.println("SecondLastElement = " + list.get(list.size() - 1)); } private LinkedList createList() { LinkedList list = new LinkedList (); Supplier - > supplier = () -> new LinkedList
(); return (LinkedList ) IntStream.range(2, 102).boxed().collect(Collectors.toCollection(supplier)); } }
Java 8 New
- Function Interface
- Java.util.function has special interface like bleow, it contains generic methods used as type for lambda expression with same type and signature.
- An interface with exactly one abstract method is called Functional Interface.
- @FunctionalInterface annotation is added so that we can mark an interface as functional interface.
- If we try to have more than one abstract method, it throws compiler error.
- The major benefit of java 8 functional interfaces is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class implementation.
- Java 8 has defined a lot of functional interfaces in java.util.function package. Some of the useful java 8 functional interfaces are Runnable, Consumer, Supplier, Function and Predicate
- Custom
@FunctionalInterface public interface Square { public int calculate(int number); } // Custom Square sq = (i) -> (i * i); int result = sq.calculate(2); System.out.println(result);- Runnable
Thread t = new Thread(() -> { System.out.println("Thread Running"); }); t.start();- Predecate Interface
- The Functional Interface PREDICATE is defined in the java.util.Function package.It improves manageability of code, helps in unit-testing them separately, and contain some methods like:
- isEqual(Object targetRef) : Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
- and(Predicate other) : Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
- negate() : Returns a predicate that represents the logical negation of this predicate.
- or(Predicate other) : Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
- test(T t) : Evaluates this predicate on the given argument.boolean test(T t)
// Simple Predicate PredicatelesserThan = (i) -> (i > 10); System.out.println(lesserThan.test(11)); // Predicate Chaining Predicate lessThan = (i) -> (i < 10); Predicate greaterThan = (i) -> (i > 5); boolean result = lesserThan.and(greaterThan).test(6); System.out.println(result); // negation boolean result2 = lesserThan.and(greaterThan).negate().test(6); System.out.println(result2); Predicate equals = (i) -> (i == 2); boolean result3 = equals.test(2); System.out.println(result3); - Static methods and Default methods
- Default methods
- Java 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.
- For creating a default method in java interface, we need to use “default” keyword with the method signature. For example,
public interface Interface2 { void method2(); default void log(String str){ System.out.println("I2 logging::"+str); } }- Static methods
- Java interface static method is similar to default method except that we can’t override them in the implementation classes.
public interface MyData { default void print(String str) { if (!isNull(str)) System.out.println("MyData Print::" + str); } static boolean isNull(String str) { System.out.println("Interface Null Check"); return str == null ? true : "".equals(str) ? true : false; } }- Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
- Abstract Class Needs
- Abstract class can define constructor. They are more structured and can have a state associated with them.
- The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.
Wednesday, 28 November 2018
Angular 6 CRUD Application
- Angular CLI Useful Commands
- ng g component my-new-component
- ng g directive my-new-directive
- ng g pipe my-new-pipe
- ng g service my-new-service
- ng g class my-new-class
- ng g guard my-new-guard
- ng g interface my-new-interface
- ng g enum my-new-enum
- ng g module my-module
- Create components. Template, component and js file will be generated with this and Module will be added to @ngModule decorations decalarion part of app.module.ts.
ng g component login ng g component add-user ng g component edit-user ng g component list-user- app.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from "./login/login.component"; import { AddUserComponent } from "./add-user/add-user.component"; import { EditUserComponent } from "./edit-user/edit-user.component"; import { ListUserComponent } from "./list-user/list-user.component"; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'add-user', component: AddUserComponent }, { path: 'edit-user', component: EditUserComponent }, { path: 'list-user', component: ListUserComponent }, { path: '', component: LoginComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }- Following is our routing configurtion.We have configured to use LoginComponent as a default component.Also, do not forget to include it in the main module - app.module.ts
- app.routing.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from "./login/login.component"; import { AddUserComponent } from "./add-user/add-user.component"; import { EditUserComponent } from "./edit-user/edit-user.component"; import { ListUserComponent } from "./list-user/list-user.component"; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'add-user', component: AddUserComponent }, { path: 'edit-user', component: EditUserComponent }, { path: 'list-user', component: ListUserComponent }, { path: '', component: LoginComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }- Create model user.model.ts
ng g class model/User- user.model.ts
export class User { id: number; firstName: string; lastName: string; email: string; }- Create Service service/user.service.ts
ng g service service/UserService- We can make web api call using HttpClent package in service class by the use of model User
- user.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { User } from '../model/user'; @Injectable({ providedIn: 'root' }) export class UserServiceService { constructor(private http: HttpClient) { } baseUrl: string = 'http://localhost:8080/user-portal/users'; getUsers() { return this.http.get(this.baseUrl); } getUserById(id: number) { return this.http.get (this.baseUrl + '/' + id); } createUser(user: User) { return this.http.post(this.baseUrl, user); } updateUser(user: User) { return this.http.put(this.baseUrl + '/' + user.id, user); } deleteUser(id: number) { return this.http.delete(this.baseUrl + '/' + id); } } - Edit Html and component class to make the application
- add-user.component.html
2. add-user.component.tsimport { Component, OnInit } from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {UserService} from "../service/user.service"; import {first} from "rxjs/operators"; import {Router} from "@angular/router"; @Component({ selector: 'app-add-user', templateUrl: './add-user.component.html', styleUrls: ['./add-user.component.css'] }) export class AddUserComponent implements OnInit { constructor(private formBuilder: FormBuilder,private router: Router, private userService: UserService) { } addForm: FormGroup; ngOnInit() { this.addForm = this.formBuilder.group({ id: [], email: ['', Validators.required], firstName: ['', Validators.required], lastName: ['', Validators.required] }); } onSubmit() { this.userService.createUser(this.addForm.value) .subscribe( data => { this.router.navigate(['list-user']); }); } }- Adding Materials
- With the release of Angular 6, we can directly run ng add @angular/material command to add material design capabilities to an existing Angular application. By executing below command we will be installing Angular Material and the corresponding theming into the project.
Angular6 Routing
- To generate new component employee. Go to app root in CLI and run below command
ng g c employee/create-employee --spec=false --flat=true ng g c employee/list-employees --spec=false --flat=true- component.ts, html and css files will be genarated in employee folder in app and it will add List Employee and Create Employee components in app.module.ts as below
- app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CreateEmployeeComponent } from './employee/create-employee.component'; import { ListEmployeesComponent } from './employee/list-employees.component'; @NgModule({ declarations: [ AppComponent, CreateEmployeeComponent, ListEmployeesComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }- Generate routing module to app. It will create app-routing.module.ts file and add Routing to app.module.ts
ng g m app-routing --flat=true --module=app- Inside app-routing.module.ts, add RouterModule object and call forRoot Method as below.
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ListEmployeesComponent } from './employee/list-employees.component'; import { CreateEmployeeComponent } from './employee/create-employee.component'; const routes: Routes = [ {path: 'list', component: ListEmployeesComponent}, {path: 'create', component: CreateEmployeeComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }- Go to app.component.html and add new routes using routerLink tag
