Monday, December 28, 2020

Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

In Spring framework, by default all the singleton beans are eagerly created and configured by ApplicationContext as part of the initialization process. Though this behavior of pre-instantiation is desirable most of the time as you can detect errors in the configuration immediately. But sometimes you may have a large object graph and loading all those beans in the beginning itself may be expensive. In that kind of scenario you can prevent pre-instantiation of a singleton bean by configuring the Spring bean to be initialized lazily.

If you mark a bean as lazy-initialized in Spring that means IoC container will create a bean instance when it is first requested, rather than at startup.

Here note that when a lazy-initialized bean is a dependency of a singleton bean that is not lazy initialized, the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the singleton’s dependencies.

Saturday, December 26, 2020

Injecting Inner Beans in Spring

This post shows how to inject inner beans in Spring and what are the scenarios when you would need to inject a bean as an inner bean.

Let’s say you have a Java class which refers to another class object and the access type for that object is private. In that case what do you think is the best way to provide bean definition in Spring. Let me provide class (Employee.java) here so you can understand what I am saying.

Friday, December 25, 2020

ServiceLocatorFactoryBean in Spring Framework

ServiceLocatorFactoryBean in Spring framework as the name suggests is an implementation of service locator design pattern and helps with locating the service at run time.

ServiceLocatorFactoryBean helps if you have more than one implementation of the same type and want to use the appropriate implementation at the run time i.e. you have an interface and more than one class implementing that interface and you want to have a factory that will return an appropriate object at run time.

registerShutdownHook() Method in Spring Framework

In the post Spring Bean Life Cycle we have already seen that you can provide destroy methods for your beans to do clean up. One problem is that these destroy callback methods are not executed automatically you do have to call AbstractApplicationContext.destroy or AbstractApplicationContext.close before shutting down the IOC container. There is another option to ensure graceful shutdown, you can register a shutdown hook with the JVM using registerShutdownHook() method in Spring.

Note that this problem is only with non-web applications. Spring’s web-based ApplicationContext implementations already have code in place to shut down the Spring IoC container gracefully when the relevant web application is shut down.

Thursday, December 24, 2020

Batch Processing in Java JDBC - Insert, Update Queries as a Batch

If you have a large number of similar queries it is better to process them in a batch rather than as individual queries. Processing them as a batch provides better performance as you send a group of queries in a single network communication rather than sending individual queries one by one.

Batch support in JDBC

JDBC provides batch support in the form of addBatch() and executeBatch() methods.

If you are using Statement interface then use addBatch(String Sql) method to add queries to the batch.

For PreparedStatement and CallableStatement use addBatch() method as parameters for the query are provided later.

Once you have added queries to a batch you can call executeBatch() method to execute the whole batch of queries.

DB you are using may not support batch updates. You should use the supportsBatchUpdates() method of the DatabaseMetaData interface to check whether the target database supports batch updates or not.

The method returns true if this database supports batch updates; false otherwise.

Wednesday, December 23, 2020

Transaction Management in Java-JDBC

This post provides detail about JDBC transaction management with examples for starting a transaction in JDBC, committing and rolling back a transaction, setting savepoint for transaction rollback.


DataSource in Java-JDBC

In the examples given in the previous post Java JDBC Steps to Connect to DB we have seen how to get a connection using DriverManager class. That’s ok for sample code where you just need to test using a connection and close it. But in a real life application creating connection object every time DB interaction is needed will be very time consuming. What you need is a connection pool where a given number of connection objects are created in the beginning itself and are reused.

In this post we’ll see another way of connecting to DB from your Java application using a DataSource object which provides the connection pooling. There are other advantages of using DataSource in JDBC too.

Tuesday, December 22, 2020

Java Lambda Expression as Method Parameter

As we have already seen in the post about functional interface that lambda expression provides implementation for the abstract method present in the functional interface and the target type for the lambda expression is the functional interface. In the simple terms we can say that lambda expression is an object that can be used where ever the reference of functional interface is required. One of these uses is passing lambda expression as an argument. To pass a lambda expression as a method parameter in Java, the type of the method argument, which receives the lambda expression as a parameter, must be of functional interface type.

Java Lambda Expressions Interview Questions And Answers

In this post some of the Java Lambda Expressions interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews especially when asked interview questions about Java 8.

  1. What is lambda expression?

    Lambda expression in itself is an anonymous method i.e. a method with no name which is used to provide implementation of the method defined by a functional interface.

    A new syntax and operator has been introduced in Java for Lambda expressions.

    General form of lambda expression

    (optional) (Arguments) -> body
    

Monday, December 21, 2020

Connection Pooling Using Apache DBCP in Java

In this post we’ll see how to configure connection pooling in your Java application using Apache DBCP datasource. The DB we are connecting to is MySQL.

Jars needed

If you are using Maven then you can add the following dependency.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.8.0</version>
</dependency>

Connection Pooling Using C3P0 in Java

In this post we’ll see how to configure connection pooling using C3P0 datasource in your Java application. The DB we are connecting to is MySQL.

Jars needed for C3P0

You need the following jars in your project’s classpath, check the versions as per your Java and DB versions.

lib/c3p0-0.9.5.5.jar
lib/mchange-commons-java-0.2.19.jar

If you are using Maven then you can add the following dependency.

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.5</version>
</dependency>

Sunday, December 20, 2020

Spring WebFlux Example Using Functional Programming - Spring Web Reactive

In this post we’ll see a Spring web reactive example using Spring WebFlux functional programming model. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and run on the default Netty server.

Saturday, December 19, 2020

Spring Web Reactive Framework - Spring WebFlux Tutorial

This Spring WebFlux tutorial gives an overview of the new reactive web framework- Spring WebFlux added in Spring version 5.0. It is fully non-blocking, helps you to write event driven, asynchronous logic and supports Reactive Streams back pressure.


Friday, December 18, 2020

Spring WebFlux Example Using Annotation-Based Programming - Spring Web Reactive

The post Spring Web Reactive Framework - Spring WebFlux Tutorial gives an overview of Spring web reactive. Building on that knowledge in this post we’ll see a Spring web reactive example using Spring WebFlux annotation-based programming model where @Controller and @RestController components use annotations to express request mappings, request input, exception handling, and more. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and runs on the default Netty server.

Class And Object in Python

Python being an object oriented programming language works on the concept of creating classes and using objects of the class to access the properties and methods defined by the class.

What is a class

In object oriented programming class defines a new type. Class encapsulates data (variables) and functionality (methods) together. Once a class is defined it can be instantiated to create objects of that class. Each class instance (object) gets its own copy of attributes for maintaining its state and methods for modifying its state.

You can create multiple class instances, they all will be of the same type (as defined by the class) but they will have their own state i.e. different values for attributes.

Thursday, December 17, 2020

Constructor in Python - __init__() function

Constructor is a special method provided to initialize objects (assign values to its data members) when they are created. In Python __init__() special method is the constructor and this method is always called when an object is created.

Syntax of init() in Python

First argument in __init__() method is always self. Constructor may or may not have other input parameters i.e. other input parameters are optional.

def __init__(self, input_parameters):
 #initialization code
 ....
 ....

Wednesday, December 16, 2020

Connection Pooling Using C3P0 Spring Example

This post shows how to provide JDBC connection pooling using C3P0 data source in Spring framework. DB used in this example is MySQL.

Maven dependency for C3P0

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>
Alternatively you can download the following jars and put them in the application’s classpath.
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.11.jar

Tuesday, December 15, 2020

Spring JdbcTemplate With ResultSetExtractor Example

In the post Select Query Using JDBCTemplate in Spring Framework we have already seen an example of extracting data from ResultSet using RowMapper. A RowMapper is usually a simpler choice for ResultSet processing, mapping one result object per row but there is another option in Spring framework known as ResultSetExtractor which gives one result object for the entire ResultSet. In this post we’ll see an example of Spring JdbcTemplate with ResultSetExtractor.

Since ResultSetExtractor is a callback interface used by JdbcTemplate's query methods so you can use an instance of ResultSetExtractor with JdbcTemplate’s query method.

Monday, December 14, 2020

Spring JdbcTemplate Insert, Update And Delete Example

In the post Data access in Spring framework we have already seen how Spring provides templates for various persistence methods and how templates divide the data access code into fixed part and variable part. Where Spring framework manages the fixed part and custom code which is provided by the user is handled through callbacks. In this post we’ll see how to use Spring JdbcTemplate to insert, update and delete data from the database.

Note that JdbcTemplate needs a DataSource in order to perform its management of fixed part like getting a DB connection, cleaning up resources.
In this post Apache DBCP is used for providing pooled datasource and MYSQL is used as the back end.

Async Pipe in Angular With Examples

Of all the built-in pipes in Angular, Async pipe is a little different as it subscribes to an Observable or Promise and returns the latest value it has emitted. When the component gets destroyed, the async pipe unsubscribes automatically to avoid any memory leaks.


Friday, December 11, 2020

Connection Pooling With Apache DBCP Spring Example

This post shows how to provide JDBC connection pooling using Apache DBCP data source in Spring framework. DB used in this example is MySQL.

Maven dependency for DBCP

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1</version>
</dependency>

Alternatively you can download the following jars and put them in the classpath.

commons-dbcp2-2.1.1.jar
commons-pool2-2.5.0.jar
commons-logging-1.2.jar

Thursday, December 10, 2020

Pure and Impure Pipes in Angular

When you create a custom pipe in Angular there is one more attribute of @Pipe decorator which you can assign a value as true or false, that attribute is pure. In this tutorial we’ll see what are pure and impure pipes in Angular and what are the differences between pure and impure pipes.

@Pipe({
  name: 'myCustomPipe', 
  pure: false/true
})
export class MyCustomPipe {

}

By default, pipes are defined as pure so you don't explicitly need to assign value of pure as true.

Wednesday, December 9, 2020

Custom Pipe in Angular With Example

Though there are many Angular built-in pipes for data transformation but Angular framework also gives you an option to create a custom pipe to cater to custom data transformation. In this tutorial we’ll see how to create a custom pipe in Angular.

Creating custom pipe in Angular

To mark a class as a pipe apply the @Pipe decorator to the class. In the name attribute of the of @Pipe provide the name of the pipe. Use name in template expressions as you would for a built-in pipe.

Your custom pipe class should also implement the PipeTransform interface.

Sunday, December 6, 2020

CopyOnWriteArraySet in Java With Examples

In Java 5 many concurrent collection classes are added as a thread safe alternative for their normal collection counterparts which are not thread safe. Like ConcurrentHashMap as a thread safe alternative for HashMap, CopyOnWriteArrayList as a thread safe alternative for ArrayList. Same way CopyOnWriteArraySet in Java is added as a thread safe alternative for HashSet in Java.

CopyOnWriteArraySet class in Java

CopyOnWriteArraySet implements the Set interface (Actually it extends the AbstractSet class which in turn implements the set interface). Since CopyOnWriteArraySet implements the Set interface so basic functionality of the Set that only unique elements can be added applies to CopyOnWriteArraySet too.

Tuesday, December 1, 2020

Using Angular Pipes in Component or Service Classes

In this tutorial we’ll see how to use Angular pipe in Component classes and Service classes in Angular.

Steps to use angular pipes in component classes (or Service)

If you want to use the pipe in more than one component class then configure it in app.module.ts class-

  1. Import the required Angular pipe and add it to the providers array.
  2. In the Component class inject the pipe and use it.

You can do these steps in Component class itself if specific Angular pipe is used in that class only.

Using Angular pipes in component class example

We’ll create a simple reactive form with fields to enter date and amount. Date has to be transformed using the DatePipe and amount using the CurrencyPipe in Component. For DatePipe configuration is done in App module where as for CurrencyPipe it is done in the Component class itself.

Tuesday, November 24, 2020

Custom Async Validator in Angular Template-Driven Form

In this tutorial we’ll see how to create a custom asynchronous validator to be used with Angular Template-Driven form.

For custom async validator in Reactive form refer this post - Custom Async Validator in Angular Reactive Form

Custom Asynchronous validator for Template-Driven form

If you want to write a custom async validator for a template-driven form that has to be written as an Angular directive which should implement the AsyncValidator interface.

interface AsyncValidator extends Validator {
  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>

  // inherited from forms/Validator
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}

Your Async validator class has to implement the validate() function which must return a Promise or an Observable.

Monday, November 23, 2020

Custom Async Validator in Angular Reactive Form

In this tutorial we’ll see how to create a custom asynchronous validator to be used with Angular Reactive form.

For custom async validator in Template-Driven form refer this post- Custom Async Validator in Angular Template-Driven Form


Types of Validator functions

Validator functions can be either synchronous or asynchronous.

  • Sync validators: Synchronous validator functions are passed a FormControl instance as argument and immediately return either a set of validation errors or null. You can pass these in as the second argument when you instantiate a FormControl.
  • Async validators: Asynchronous validator functions are passed a FormControl instance as argument and return a Promise or Observable that later emits a set of validation errors or null. You can pass these in as the third argument when you instantiate a FormControl.

Sunday, November 22, 2020

CallableStatement Interface in Java-JDBC

In the post Statement Interface in Java-JDBC and PreparedStatement Interface in Java-JDBC we have already seen how you can use Statement to execute static SQL statements and PreparedStatement to execute precompiled parameterized SQL statements. On the same lines the JDBC API provides CallableStatement interface that extends PreparedStatement and used to execute SQL stored procedures.

Stored Procedure

Stored procedure is a subroutine which resides with in the database and may have DB specific way of writing it. If you have a huge SQL statement or a group of SQL statements involving more than one table, checking for conditions, looping it is better to write it as a stored procedure. That way you will need to make just one call to the DB server and your pre-compiled procedure would be executed in the same space as your DB server.

That brings you the advantages like efficiency as it is already compiled, reduced network traffic as its full execution happens in the DB server.

Obtaining JDBC CallableStatement object

CallableStatement object can be created using the prepareCall() method of the Connection interface.

CallableStatement callableStatement = connection.prepareCall(“{call PROCEDURE_NAME(?, ?, ?)}”); 
Here ‘?’ is a place holder used to register IN, OUT and INOUT parameters.

You can also also call functions using Callable statement, in that case general form would be like -

CallableStatement callableStatement = connection.prepareCall(“? = {call PROCEDURE_NAME(?, ?, ?)}”);

How to use CallableStatement in JDBC

In order to pass values to the IN and INOUT parameters of the stored procedure you need to use the appropriate setter method. CallableStatement inherits setter methods from PreparedStatement and there are different setter methods for different data types i.e. setInt(), setString(), setDate() etc.

You also need to register OUT parameters of the stored procedure. For that you need to use registerOutParameter method which takes column index or column name and type as parameters. It has other overloaded methods too.

There are also various getter methods (like getString(), getLong(), getTime()) for getting the values from the OUT parameters.

In order to execute the CallableStatement you can use execute() methods -

  • execute()- Any SQL statement. Returns a boolean which is true if the first result is a ResultSet object; false if it is an update count or there are no results.
  • executeUpdate()- For DML statements like Insert, Update or DDL statements like Create.
  • ExecuteQuery()- For SQL statement that returns ResultSet.

Java CallableStatement examples

Let’s see some examples using CallableStatement in JDBC. Database used is MySql, schema is netjs and table employee with columns id, age and name, where id is auto-generated.

1. CallableStatement example-Executing stored procedure having IN params

In this example let’s execute a stored procedure that has only IN params using CallableStatement. The stored procedure inserts a new row into the table.

insert_employee_proc.sql

CREATE PROCEDURE `insert_employee_proc`(IN param_name VARCHAR(35), IN param_age int)
BEGIN
  INSERT into EMPLOYEE (name, age) values 
  (param_name, param_age);
END

You can see in the stored procedure that there are two IN parameters in the stored procedure.

Java Code

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCCallableStmt {

  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                          "root", "admin");
      
      // Getting CallableStatement object
      CallableStatement cStatement = connection.prepareCall(
         "{call insert_employee_proc(?, ?)}");
      // Setting params
      cStatement.setString(1, "Jackie");
      cStatement.setInt(2, 45);
      
      int count = cStatement.executeUpdate();
      System.out.println("Count of rows inserted " + count);
   
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

2. CallableStatement example-Executing stored procedure having IN and OUT params

In this Java CallableStatement example let’s execute a stored procedure that has both IN and OUT params using CallableStatement. The stored procedure has a select query to which id is passed as an IN parameter and age and name for that id are send in OUT parameters.

select_employee_proc.sql

CREATE PROCEDURE `select_employee_proc`(IN param_id int, 
    OUT param_name varchar(35), OUT param_age int)
BEGIN
 SELECT name, age INTO param_name, param_age
 from EMPLOYEE where id = param_id;
END

Java Code

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.JDBCType;
import java.sql.SQLException;

public class JDBCCallableStmt {

  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                          "root", "admin");
      
      // Getting CallableStatement object
      CallableStatement cStatement = connection.prepareCall(
        "{call select_employee_proc(?, ?, ?)}");
      // Setting params
      cStatement.setInt(1, 26);
      // Registering OUT parameters Using 
      // JDBCType enum which is added in Java 8
      cStatement.registerOutParameter(2, JDBCType.VARCHAR);

      cStatement.registerOutParameter(3, JDBCType.INTEGER);

      cStatement.executeQuery();

      // Reading the OUT paramter here 
      System.out.println("Fetched Result " + "Name: " + cStatement.getString(2) + 
        " Age: " + cStatement.getInt(3));
   
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

3. CallableStatement example-Executing stored procedure returning multiple rows

Let’s see an example where stored procedure returns multiple rows as result. In that case you can use execute or executeQuery to execute the procedure using CallableStatement and that will return the resultset. In this example execute method is used in order to show how it uses other methods like getResultSet and getMoreResults.

all_employee_proc.sql

CREATE PROCEDURE `all_employee_proc`(IN param_age int)
BEGIN
  SELECT * from employee where age > param_age;
END

The stored procedure returns all employees whose age is greater than the passed age integer parameter.

Java code

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCCallableStmt {

  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                          "root", "admin");
      
      // Getting CallableStatement object
      CallableStatement cStatement = connection.prepareCall("{call all_employee_proc(?)}");
      // Setting params
      cStatement.setInt(1, 30);
    
      boolean hasResults = cStatement.execute();
      while(hasResults){
        ResultSet rs = cStatement.getResultSet();
        while(rs.next()){
          System.out.println("id : " + rs.getInt("id") + " Name : " 
            + rs.getString("name") + " Age : " + rs.getInt("age")); 
        }
        hasResults = cStatement.getMoreResults();
      }   
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

Output

id : 6 Name : Tim Age : 40
id : 8 Name : Johnny Age : 35
id : 17 Name : Johnny Age : 35
id : 18 Name : Bob Age : 45
id : 25 Name : Jacky Age : 50
id : 26 Name : Jackie Age : 45

That's all for this topic CallableStatement Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. JDBC Tutorial - Java JDBC Overview
  2. Java JDBC Steps to Connect to DB
  3. ResultSet Interface in Java-JDBC
  4. DataSource in Java-JDBC
  5. Transaction Management in Java-JDBC

You may also like-

  1. How ArrayList Works Internally in Java
  2. Java Stream flatMap() Method
  3. Serialization Proxy Pattern in Java
  4. Just In Time Compiler (JIT) in Java
  5. Lambda Expressions in Java 8
  6. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  7. Invoking Getters And Setters Using Reflection in Java
  8. finalize Method in Java

Saturday, November 21, 2020

PreparedStatement Interface in Java-JDBC

In the post Statement interface in Java we have already seen how you can create a Statement using connection object and execute SQL statements. One problem though is that Statement interface is used to execute static SQL statements with no option to send parameters. Though you can always use a StringBuilder to append parameters to the SQL and use it with Statement but there is a better option provided by JDBC itself in the form of PreparedStatement which is a sub-interface of Statement. In this post we'll see how to use PreparedStatement in Java with examples.

Obtaining JDBC PreparedStatement object

You can get the PreparedStatement object by calling the prepareStatement method of the Connection class.

PreparedStatement preparedStatement = connection.prepareStatement(sql);

Advantages of using PreparedStatement in JDBC

As stated above one advantage of PreparedStatement is that you can use PreparedStatement object for SQL statement with or without parameters. The advantage of using SQL statement with parameters is that you can use the same statement and supply it with different parameter values each time you execute it.

That brings us to the second advantage of PreparedStatement, it is more efficient. Unlike Statement object, PreparedStatement is given the SQL statement when it is created. So the SQL is sent to the DB right away where it is already compiled. When you come to execute() method to actually execute the SQL that SQL is pre-compiled making it more efficient for repeated executions.

Java PreparedStatement example

Let’s see an example using PreparedStatement in JDBC. DB used here is MySql, schema is netjs and table is employee with columns id, age and name, where id is auto-generated.

In the code there are methods for insert, update, delete and select from the table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCPrepStmt {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
    
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/netjs", 
                         "root", "admin");
      JDBCPrepStmt prep = new JDBCPrepStmt();
      prep.insertEmployee(connection, "Kate", 24);
      prep.updateEmployee(connection, 22, 30);
      prep.displayEmployee(connection, 22);
    
      //prep.deleteEmployee(connection, 24);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
 
  // Method to insert
  private void insertEmployee(Connection connection, String name, int age) 
        throws SQLException{
    String insertSQL = "Insert into employee (name, age) values (?, ?)";
    PreparedStatement prepStmt = null;
    try {
      prepStmt = connection.prepareStatement(insertSQL);
      prepStmt.setString(1, name);
      prepStmt.setInt(2, age);
      int count = prepStmt.executeUpdate();
      System.out.println("Count of rows inserted " + count);
    }finally{
      if(prepStmt != null){
        prepStmt.close();
      }
    }
  }
 
 // Method to update
 private void updateEmployee(Connection connection, int id, int age) throws SQLException{
  String updateSQL = "Update employee set age = ? where id = ?";
  PreparedStatement prepStmt = null;
  try {
   prepStmt = connection.prepareStatement(updateSQL);
   prepStmt.setInt(1, age);
   prepStmt.setInt(2, id);
   int count = prepStmt.executeUpdate();
   System.out.println("Count of rows updated " + count);
  }finally{
    if(prepStmt != null){
     prepStmt.close();
    }
  }
 }
 
 // Method to delete
 private void deleteEmployee(Connection connection, int id) throws SQLException {
  String deleteSQL = "Delete from employee where id = ?";
  PreparedStatement prepStmt = null;
  try {
   prepStmt = connection.prepareStatement(deleteSQL);
   prepStmt.setInt(1, id);
   int count = prepStmt.executeUpdate();
   System.out.println("Count of rows deleted " + count);
  }finally{
    if(prepStmt != null){
     prepStmt.close();
    }
  }
 }
 

 // Method to retrieve
 private void displayEmployee(Connection connection, int id) throws SQLException{
  String selectSQL = "Select * from employee where id = ?";
  PreparedStatement prepStmt = null;
  try {
   prepStmt = connection.prepareStatement(selectSQL);
   prepStmt.setInt(1, id);
   ResultSet rs = prepStmt.executeQuery();
   while(rs.next()){
     System.out.println("id : " + rs.getInt("id") + " Name : " 
                   + rs.getString("name") + " Age : " + rs.getInt("age")); 
   }
  }finally{
    if(prepStmt != null){
     prepStmt.close();
    }
  }
 }
 
}

Points to note here

Taking this example as reference let’s go through some of the points you will have to keep in mind when using PreparedStatement in JDBC.

  • Parameterized statement– In the example you can see that all the SQL statements are parameterized and ‘?’ is used as a placeholder in parameterized statements.

    As example-

    String insertSQL = "Insert into employee (name, age) values (?, ?)";
    
  • Setter methods– Values for these placeholders are provided through setter methods. PreparedStatement has various setter methods for different data types i.e. setInt(), setString(), setDate() etc.

    General form of the setter method is setXXX(int parameterIndex, value)

    Here parameterIndex is the index of the parameter in the statement, index starts from 1.

    As example-

    String insertSQL = "Insert into employee (name, age) values (?, ?)";
    

    For this sql where the first parameter is String (name) and second parameter is of type int (age), you need to set the parameters on the PreparedStatement object as follows -

    prepStmt.setString(1, name);
    prepStmt.setInt(2, age);
    
  • Executing PreparedStatement objects– You can use execute methods for executing the queries.
    1. boolean execute()- Executes the SQL statement in this PreparedStatement object, (it can be any kind of SQL query), which may return multiple results.
      Returns a boolean which is true if the first result is a ResultSet object; false if it is an update count or there are no results.
    2. ResultSet executeQuery(String sql)- Executes the SQL statement in this PreparedStatement object, which returns a single ResultSet object. If you want to execute a Select SQL query which returns results you should use this method.
    3. int executeUpdate()- Executes the SQL statement in this PreparedStatement object, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
      Returns an int denoting either the row count for the rows that are inserted, deleted, updated or returns 0 if nothing is returned.

That's all for this topic PreparedStatement Interface in Java-JDBC. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. JDBC Tutorial - Java JDBC Overview
  2. ResultSet Interface in Java-JDBC
  3. Transaction Management in Java-JDBC
  4. Connection Pooling Using C3P0 in Java
  5. Data Access in Spring Framework

You may also like-

  1. Ternary Operator in Java With Examples
  2. Volatile Keyword in Java With Examples
  3. Race Condition in Java Multi-Threading
  4. Transient Keyword in Java With Examples
  5. Spliterator in Java
  6. Lambda Expressions in Java 8
  7. Type erasure in Java Generics
  8. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example

Name Mangling in Python

In Python there are no explicit access modifiers so you can’t mark a class member as public/private. Then the question is how to restrict access to a variable or method outside the class, if required. Class member can be made private (Close to private actually) using a process called name mangling in Python.


Name mangling (Making member private)

In Python name mangling process any identifier with at least two leading underscores, at most one trailing underscore is textually replaced with _classname__identifier where classname is the current class name. For example if there is a variable __var it is rewritten by the Python interpreter in the form _classname__var.

Since the name of any such class member (with at least two leading underscores, at most one trailing underscore) changes internally thus it can’t be accessed using the given name. That is the closest Python goes for making a class member private.

Python Name mangling example

Let’s try to clarify name mangling process with examples.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
#accessing using class method
print('Displaying values using class method')
person.display()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print(person.name)
print(person.__age)

Output

Displaying values using class method
John
40
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 21, in <module>
Trying to access variables from outside the class 
John
    print(person.__age)
AttributeError: 'Person' object has no attribute '__age'

As you can see variable __age (having two leading underscores) is not accessible from outside the class. Using a method with in the class it can still be accessed.

Same way for a method with two leading underscores.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def __displayAge(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
person.__displayAge()

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Person.py", line 15, in <module>
    person.__displayAge()
AttributeError: 'Person' object has no attribute '__displayAge'

As you can see method is not accessible from outside the class.

How does name change in Name mangling

If you want to verify the rewriting of name in Python name mangling process you can do so using the dir() function.

When a class object is passed as an argument to dir() function, it returns a list of valid attributes for that object.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

person = Person('John', 40)
print(dir(person))

Output

['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', 
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', '__weakref__', 'name']

From the output of dir() function for Person object you can see that the __age is rewritten as _Person__age.

Name mangling and method overriding

As per Python docs stated objective of name mangling is to avoid name clashes of names with names defined by subclasses. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

For example consider the following scenario where Parent class is subclassed and there is an overridden method test is the Child class too. From the constructor of Parent class there is a call to test method- self.test()

class Parent:
  def __init__(self):
    print('in init')
    self.test()
  def test(self):
    print('In Parent test method')

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Child test method
In Child test method

As you can see Child test method is getting called both of the times. To avoid that name clash you can create a private copy of the original method.

class Parent:
  def __init__(self):
    print('in init')
    self.__test()
  def test(self):
    print('In Parent test method')

  # private copy
  __test = test

class Child(Parent):
  def test(self):
    print('In Child test method')

obj = Child()
obj.test()

Output

in init
In Parent test method
In Child test method

Accessing name mangled class members

As already stated Python name mangling process rewrites the member name by adding _classname to the member. Thus it is still possible to access the class member from outside the class by using the rewritten name. That is why it is said that Name mangling is the closest to private not exactly private.

class Person:
  def __init__(self, name, age=0):
    self.name = name
    self.__age = age

  def display(self):
    print(self.name)
    print(self.__age)

person = Person('John', 40)
print('Trying to access variables from outside the class ')
print(person.name)
print(person._Person__age)

Output

Trying to access variables from outside the class 
John
40

As you can see private class member is accessed from outside the class by using the name mangled form _ClassName__var.

That's all for this topic Name Mangling in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Installation on Windows
  2. Encapsulation in Python
  3. Method Overriding in Python
  4. Multiple Inheritance in Python
  5. Python for Loop With Examples

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Local, Nonlocal And Global Variables in Python
  3. Python count() method - Counting Substrings
  4. Python Functions : Returning Multiple Values
  5. Marker Interface in Java
  6. Functional Interfaces in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Race Condition in Java Multi-Threading

Thursday, November 19, 2020

Custom Validator in Angular Template-Driven Form

Angular framework provides many built-in validators that can be used with forms but sometimes you may need a validation in your application that can’t be catered by a built-in validators. For such scenario Angular also gives the option to create a custom validator. In this tutorial we’ll see how to create a custom validator to be used with Angular template-driven form.

Custom validator for Template-Driven form

If you want to write a custom validator for a template-driven form that has to be written as an Angular directive which should implement the Validator interface. This Validator interface is implemented by classes that perform synchronous validation.

interface Validator {
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}

Wednesday, November 18, 2020

Custom Validator in Angular Reactive Form

Angular framework provides many built-in validators that can be used with forms but sometimes these built-in validators may not match the requirement of your use case. For such scenario Angular also gives the option to create a custom validator. In this tutorial we’ll see how to create a custom validator and how to use it with Angular reactive form.

Creating custom validator

Custom validators are also like any other function that you can write in a component class. A custom validator takes FormControl as an argument and returns a key, value pair where key is string and value is boolean. Following pseudo code shows how custom validator can be written to validate a control in Angular form.

Thursday, September 17, 2020

What is Client Side Routing in Angular

While working with any modern JS frameworks like Angular, React, Vue you would have definitely come across two terms Single Page Application (SPA) and client side routing. In this post we’ll see what is client side routing using Angular as example framework.

Client side routing

In a traditional web application every request for displaying a page goes to the server and results in a full page load. Whereas in a Single page application each request doesn’t go to the server. Web server gives a single page, any further rendering is done locally by the Java script. So, in a SPA you will get a single page and part of the page is updated dynamically for further requests.

Tuesday, September 15, 2020

Location Strategies in Angular Routing

In Angular routing we have two location strategies that we can use to implement client side routing.

  1. PathLocationStrategy
  2. HashLocationStrategy

In this post we’ll see what is location strategy, which routing strategy to chose for your SPA and what are the differences between the HashLocationStrategy and PathLocationStrategy.

Friday, September 11, 2020

How to Create a Custom Observable in Angular

In this post we’ll see how to create a custom Observable in Angular. Observables are based on Observer design pattern in which an object, called the subject, maintains a list of observers and notifies them automatically of state changes. Some thing like this-

public interface Subject {
  public void register(Observer obj);
  public void unregister(Observer obj);

  public void notifyObservers();
}

Tuesday, September 8, 2020

Angular Route Resolver - Passing Data Dynamically

In the posts route parameters and Angular query parameters we have seen examples of passing data in the route and using it in the component as it is or to retrieve more data. This process happens once you have navigated to a route but you can also get data before you have navigated to a route. That is done using Angular Resolve interface that classes can implement to be a data provider. A data provider class can be used with the router to act as a resolver and it can resolve data during navigation. Using Resolve interface in Angular gives you one way to get data dynamically before navigating to a route.

Angular Resolve interface

Resolve interface has a single method resolve() that is invoked when the navigation starts. The router waits for the data to be resolved before the route is finally activated.

Monday, September 7, 2020

Angular Route - Passing Static Data

We have already seen how to pass data to a route using route parameters and using Angular query parameters. In this post we’ll see how to pass static data to an Angular route. Static data is configured at the time of defining a route using data property.

For example, here is a route definition with data property-

{path: 'wrongpath', component: PageNotFoundComponent, data :{ message:'Page not found'}},

As you can see with data property you can pass an object having key, value pairs.

Monday, August 31, 2020

CanDeactivate Guard in Angular With Example

In this post we’ll see an example of CanDeactivate guard in Angular which helps in handling unsaved changes.

CanDeactivate interface in Angular

Any class implementing CanDeactivate interface can act as a guard which decides if a route can be deactivated. If you configure this class to be a canDeactivate guard for any route then if you try to navigate away from that route you can show a dialog box to confirm whether user really want to move away.

CanDeactivate interface has a single method canDectivate and the interface is defined as given below-

interface CanDeactivate<T> {
  canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}

Tuesday, August 25, 2020

Angular CanActivateChild Guard to protect Child Routes

In the post Angular Access Control CanActivate Route Guard Example we saw an example of canActivate guard and how it protects a route including its child routes. You can also protect child routes with the CanActivateChild guard in Angular. If you want to guard only the child component then you can use the CanActivateChild guard which is similar to the CanActivate guard with the difference that it runs before any child route is activated.

CanActivateChild interface in Angular

A class implementing CanActivateChild interface can act as a guard deciding if a child route can be activated. If all guards return true, navigation continues. If any guard returns false, navigation is cancelled.

There is one method canActivateChild in the interface.

interface CanActivateChild {
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
}

Tuesday, August 18, 2020

Nested Route (Child Route) in Angular

All the Angular routing examples we have seen so far have routes that are relative to the root component. But in a big application you would want to contain the route with in another route that is creating routes that are relative to component other than root component. These types of routes with in a route are called nested route or child route in Angular routing.


How to create a child route in Angular routing

You place child routes in a children array within the parent route. For example if you want to create two nested routes relative to ParentComponent then it can be done as follows-

Monday, August 17, 2020

Setting Wild Card Route in Angular

In the post Angular Routing Concepts With Example we saw an example of setting up routes for navigation. One question though is what if user navigates to a path that does not exist. Ideally you should also handle such scenario and show a page not found or navigate to home page when user tries to navigate to a non-existent path. In this post we’ll see how to set up wild card route in Angular to handle any case when the requested URL doesn’t match any router path.

In this example wild card route is set up to show page not found message.

Wild card route in Angular

For setting up a wild card route in Angular you use ‘**’ (double asterisk). This wild card route catches all routes that are not configured with in the route definition.

{ path: '**', component: COMPONENT_NAME}

Do ensure that the wildcard route is the last one in the route definition ordering as wild card route matches every URL.

This order of routes is important because the Router uses a first-match wins strategy. When matching routes if wildcard route, which matches every URL, is at the top then the component paired with wildroute will be the one always called. Follow the order of-

  • List routes with a static path first.
  • Empty path route (with a possible redirection).
  • The wildcard route comes last.

Wild card route Angular Example

Routing module with route definitions including wild card route (app-routing.module.ts).

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';

const routes: Routes = [
                      {path: 'home', component: HomeComponent},                  
                      {path: 'account', component: AccountsComponent},
                      {path: 'account/:acctno', component: AccountComponent},
                      {path: 'service', component: ServiceComponent},
                      {path: '', redirectTo:'/home', pathMatch: 'full'}, 
                      {path: '**', component: PageNotFoundComponent}                
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Do notice the route order, static paths first, then the default route redirect using empty path and then the wild card route.

PageNotFoundComponent (pagenotfound.component.ts)

@Component({
  selector: 'app-pagenotfound',
  templateUrl: './pagenotfound.component.html'
})
export class PageNotFoundComponent{

}

pagenotfound.component.html

<h3>404 Page Not Found!!</h3>

For other component’s code please refer this post- Angular Routing Concepts With Example

Now if you try to navigate any URL that doesn’t match any of the configured routes you will be sent to PageNotFoundComponent.

wild card route in Angular


That's all for this topic Setting Wild Card Route in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  3. Nested Route (Child Route) in Angular
  4. Angular Route Parameters - Setting and Fetching
  5. Passing Query Parameters in Angular Routing

You may also like-

  1. Angular ngFor Directive With Examples
  2. Angular One-Way Data Binding Using String Interpolation
  3. Angular Two-Way Data Binding With Examples
  4. Angular - Call One Service From Another
  5. ConcurrentHashMap in Java With Examples
  6. Var type in Java - Local Variable Type Inference
  7. What Are JVM, JRE And JDK in Java
  8. How to Write a Map Only Job in Hadoop MapReduce

Friday, August 14, 2020

Passing Query Parameters in Angular Routing

In this post we’ll how to pass query parameters in Angular routing and how to retrieve the passed query parameters.


Query parameters in Angular

Using query parameters you can pass optional parameters across the routes in your application. Query parameters are separated by a question mark from the URL and any route parameters. You can have more than one query parameter in the URL which are separated by &.

For example- localhost:4200/services?accttype=s&allowaccess=1

Here accttype and allowaccess are query parameters.

Passing query parameters in Angular routing

1. You can pass query parameters with RouterLink directive. RouterLink directive has a property queryParams that is used to pass query parameters.

<a [routerLink]="['/account', accountnumber]"  
            [queryParams]="{accttype: 's'}"           
             class="list-group-item"   
            *ngFor="let accountnumber of accountnumbers">
            {{ accountnumber }}
</a>

Which results in a URL like- http://localhost:4200/account/A1001?accttype=s

2. You can also pass query parameters programmatically using Router.navigate() method. In navigate method you can pass query parameters as a Javascript object.

this.router.navigate(['/account', accountno], {queryParams:{accttype: 's'}});

You can of course pass more than one query parameter in both of these ways as comma separated values.

this.router.navigate(['/account', accountno], {queryParams:{accttype: 's', allowaccess: 1}});

Accessing query parameters in Angular

For retrieving query parameters in Angular you can use the queryParams property of the ActivatedRoute class.

this.route.queryParams
          .subscribe((queryParams: Params)=> {
            this.acctType = queryParams['accttype']
          });
or you can use the current snapshot of the route to get query parameters from that.
this.acctType = this.route.snapshot.queryParams['accttype'];

Query parameters in Angular routing example

Let’s see a full Angular example to understand passing and retrieving of query parameters. In the example there is-

AccountsComponent to display account numbers.

AccountComponent to display details of the clicked account.

In the AccountComponent there is a button to navigate to ServiceComponent which displays the offered services only if account type is saving. Account type is passed as a query parameter.

1. Routing module (app-routing.module.ts)

import { Routes, RouterModule } from '@angular/router';
import { AccountsComponent } from './accounts/accounts.component';
import { AccountComponent } from './accounts/account/account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';

const routes: Routes = [
                    {path: 'home', component: HomeComponent},                  
                    {path: 'account', component: AccountsComponent},
                    {path: 'account/:acctno', component: AccountComponent},
                    {path: 'service', component: ServiceComponent},
                    {path: '', redirectTo:'/home', pathMatch: 'full'}             
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. Adding routing module to AppModule.

import { AppRoutingModule } from './app-routing.module';

imports: [
  BrowserModule,
  AppRoutingModule
],

3. Route links (app.component.html)

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/home">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" [routerLink]="['/service']">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

4. Creating components.

AccountsComponent (accounts.component.ts)

In this component there are some hardcoded account numbers.

import { Component } from '@angular/core';

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent {
  accountnumbers = ['A1001', 'A1002'];
}

accounts.component.html

This template displays the account numbers and also creates route link for account numbers.

<div class= "row">
  <div class="col-xs-4 col-md-6">
    <h2>Account Numbers</h2>
    <div class="list-group">
      <a [routerLink]="['/account', accountnumber]"           
        class="list-group-item"   
        *ngFor="let accountnumber of accountnumbers">
        {{ accountnumber }}
      </a>
    </div>
  </div>
</div>

AccountComponent (account.component.ts)

In this component we display details for the account number which is sent as route parameter. To extract the parameter route.params observable is used and we subscribe to it so that when ever there is a change the parameter is extracted into a acctNo variable. This is done in ngOnInit().

Using the fetched account number we find the related object in the array using the find() method.

There is also a onSelectedAccount(acct) method where the query parameter is attached to the URL in the router.navigate() method.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent implements OnInit{
  acctNo: string;
  account: {accountnumber: string, type: string, balance: number};
  constructor(private router: Router, private route: ActivatedRoute){ }
  accountDetails = [
    {
      accountnumber: 'A1001',
      type: 'Saving', 
      balance: 22000
    },
    {
      accountnumber: 'A1002',
      type: 'Checking',
      balance: 1000
    }
  ];

  ngOnInit() {
    this.route.params.subscribe((params: Params)=> this.acctNo = params['acctno']);
    this.account = this.accountDetails.find(e=>e.accountnumber === this.acctNo);
  }

  onSelectedAccount(acct){
    this.router.navigate(['/service'], {queryParams:{accttype: acct.type === 'Saving'? 's':'c'}})
  }
}

account.component.html

This template displays the account details for the selected account number. There is also a button to navigate to the offered services for the selected account number.

<h2>Account Details</h2>
<div class="row">
  <div class="col-xs-6">
    <label>Account Number: </label> {{ account.accountnumber }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Account Type: </label> {{ account.type }}
  </div>
</div>
<div class="row">
  <div class="col-xs-6">
    <label>Balance: </label> {{account.balance}}
  </div>
</div>
<button class="btn btn-primary" (click)="onSelectedAccount(account)">Offered Services</button>

ServiceComponent (service.component.ts)

In this component we have the offered services stored in an array. In the ngOnInit() method passed query parameter (accttype) is retrieved using route.queryParams observable.

Boolean variable showServices is assigned the value true or false based on whether the passed query parameter is ‘s’ or ‘c’.

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: 'app-service',
    templateUrl:'./service.component.html'
})
export class ServiceComponent implements OnInit{
  showServices = false;
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ];
  constructor(private route : ActivatedRoute){ }
  ngOnInit() {
    this.route.queryParams
              .subscribe((queryParams: Params) => {
                  this.showServices = queryParams['accttype'] === 's'? true:false
               });
  }
}

service.component.html

Using ngIf directive value of showServices is checked and if it is false then the messsage ‘No services for checking account’ is displayed otherwise offered services are displayed.

<h2>Services Offered</h2>
<h4 *ngIf="!showServices">No services for checking account</h4>
<div *ngIf="showServices">
  <div class="row">
    <div class="col-xs-12 col-sm-6">
      <div class="list-group">
        <a
          href="#"
          class="list-group-item"
          *ngFor="let service of services">
          {{ service }}
        </a>
      </div>
    </div>
  </div>
</div>

Showing account numbers-

Display account details-

Offered services-

When URL is- http://localhost:4200/service?accttype=s

When URL is- http://localhost:4200/service?accttype=c

Preserving or Merging Query Parameters with queryParamsHandling

If you navigate away from the route with query parameters to any other route, by default the query parameters are lost. If you want to retain them set queryParamsHandling to-

  • preserve- If you want to preserve the original query parameters.
  • merge- If you want to merge the original query parameters with the new one.

For example if you want to move from service to other-page and still want to keep the query parameters-

onClickOtherPage(){
  this.router.navigate(['/other-page'], {queryParamsHandling:'preserve'});
}

Resulting in a URL- http://localhost:4200/other-page?accttype=s

If you want to add more query parameters and want to retain the previous one too-

onClickOtherPage(){
  this.router.navigate(['/other-page'], {queryParams: {param1: 'value', queryParamsHandling:'merge'});
}

Resulting in a URL- http://localhost:4200/other-page?param1=value&accttype=s

That's all for this topic Passing Query Parameters in Angular Routing. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Navigate to a Route Programmatically in Angular
  3. Angular Route - Passing Static Data
  4. Location Strategies in Angular Routing
  5. Angular Custom Property Binding Using @Input Decorator

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular ngSwitch Directive With Examples
  3. Angular Cross Component Communication Using Subject Observable
  4. FormBuilder in Angular Example
  5. PriorityBlockingQueue in Java Concurrency
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Predefined Mapper And Reducer Classes in Hadoop
  8. Passing Arguments to getBean() Method in Spring

Friday, August 7, 2020

Using RouterLinkActiveOptions to Fix Link Highlighted Problem

In the post Highlight Currently Selected Menu Item Angular Routing Example we saw how you can highlight the selected menu option but there may be one problem with that, menu option configured with root path route always remain highlighted. In this post we’ll see how to fix the problem of root path route always remaining highlighted in Angular using routerLinkActiveOptions.

Link remaining highlighted problem

If you have configured your routes arrays something like as given below-

const routes: Routes = [
                        {path: '', component: HomeComponent},                  
                        {path: 'account', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

And the routeLink as given here-

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/">Home</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/account">Accounts</a>
        </li>
        <li class="nav-item" routerLinkActive="active">
          <a class="nav-link" routerLink="/service">Services</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
    <div class="row">
      <div class="col-md-12">
        <router-outlet></router-outlet>
      </div>
    </div>
</div> 

Then you will see the problem of link associated with the root ("/") always remain highlighted.

Using routerLinkActiveOptions in Angular

You can see in the image even if Services menu link is clicked, ‘Home’ remains highlighted.

This problem occurs because Angular considers root path segment to be the part of all the paths. Even if path is either http://localhost:4200/service or http://localhost:4200/account, root path segment “/” is always there. That is the reason the Link associated with empty path (“/”) is always highlighted.

Using routerLinkActiveOptions

In order to solve this problem using routerLinkActiveOptions. With routerLinkActiveOptions you can pass a javascript object {exact:true} to direct Angular to make link active only when exact path matches.

<li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  <a class="nav-link" routerLink="/">Home</a>
</li>

With this configuration change ‘Home’ menu will only be highlighted when it is selected, as soon as you move away from this option it won’t remain highlighted anymore.

That's all for this topic Using RouterLinkActiveOptions to Fix Link Highlighted Problem. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Routing Concepts With Example
  2. Path Redirection in Angular Routing
  3. Navigate to a Route Programmatically in Angular
  4. Setting and Fetching Route Parameters in Angular
  5. Angular Two-Way Data Binding With Examples

You may also like-

  1. Angular ngClass Directive With Examples
  2. Angular Custom Event Binding Using @Output Decorator
  3. How to Add Bootstrap to Angular Application
  4. Angular - Call One Service From Another
  5. What is In-place Algorithm
  6. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  7. Switch Expressions in Java 12
  8. Python Exception Handling Tutorial