Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


Advertisements

Setup React JS with NodeJS and Visual Studio Code

Posted on Updated on

Before getting started with first React JS example, download Visual Studio Code Editor that help you configure and better guidance of developing a React JS application.

Download & Install Visual Studio Code from here.
Download and install Node.Js from here.

Once the installation is done then create a root folder where do you want to set up a React JS Project.

>>cd d:
>>mkdir React
>>cd React
>>npm install –g create-react-app
>>create-react-app my-first-app
>>cd my-first-app
>>npm start

Once all step’s done successfully then the my-first-app folder will be created in your root folder React, go inside this folder and you will see all dependencies JS and related configuration files will be placed here.

Next, Open Visual Studio Code and Open project from File-> Open Folder

 

Then open http://localhost:3000/ to see your app.

Sort Array of String by their counts in Java 8

Posted on

Here, we will see how to sort an array base on elements occurrences in Java 8.

Suppose we got a city list containing duplicate city as well like below.

"Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";

First, we have to do aggregation on city name by applying groupBy function, count their occurrence and return a Map.

 String cities = "Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";
        
 TreeMap<String, Long> groupByCitiesMap = Stream.of(cities.split(","))
                .collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
 System.out.println(groupByCitiesMap);

This will return a TreeMap of sorted by City (natural sorting) that containing unique city name as key and their counts as in value.

{Agra=3, Bihar=3, Delhi=5, Uttar Pradesh=2}

OR

We can do it old fashion without using Stream.

TreeMap<String, CityReport> treeMap = new TreeMap();
for (String city : cities.split(",")) {
    CityReport cityReport = new CityReport(city);
    if (treeMap.containsKey(city)) {
        treeMap.computeIfPresent(city, (key, val) -> {val.counter+=1;return val;});
    } else {
        treeMap.put(city, cityReport);
    }
}

This will return a Map that containing unique city name as key and CityReport as value containing city name and count.

{Agra=CityReport{city=’Agra’, counter=3}, Bihar=CityReport{city=’Bihar’, counter=3}, Delhi=CityReport{city=’Delhi’, counter=5}, UP=CityReport{city=’UP’, counter=2}}

and Finally, need to be sorted out by City count and City name. so here we do so…

List<CityReport> sortedCityReport = treeMap.values().stream().sorted(new ComparatorFilter(new ComparatorByNumber(),new ComparatorByName())).collect(Collectors.toList());

System.out.println("Sort By Count first then City Name "+ sortedCityReport);

Output:

Sort By Count first then City Name [CityReport{city=’UP’, counter=2}, CityReport{city=’Agra’, counter=3}, CityReport{city=’Bihar’, counter=3}, CityReport{city=’Delhi’, counter=5}]

Rest of code is below:-

ComparatorFilter.Java :- Sorting by chain of comparator ( by count and name )  over the Collection.

static class ComparatorFilter implements Comparator<CityReport> {

    private final List<Comparator<CityReport>> comparators;

    ComparatorFilter(Comparator<CityReport>... comparators) {
        this.comparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(CityReport o1, CityReport o2) {
        for (Comparator c : this.comparators) {
            int val = c.compare(o1, o2);
            if (val != 0) {
                return val;
            }
        }
        return 0;
    }
}

ComparatorByName.Java – Sorting by City Name

static class ComparatorByName implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return o1.city.compareTo(o2.city);
    }
}

ComparatorByNumber.Java – sorting by count number.

static class ComparatorByNumber implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return (int) (o1.counter - o2.counter);
    }
}

CityReport Model Class –


class CityReport {
String city;
Long counter;

public CityReport(String city) {
    this.city = city;
    this.counter = 1L;
}


@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CityReport that = (CityReport) o;
    return Objects.equals(city, that.city);
}

@Override
public int hashCode() {

    return Objects.hash(city);
}

@Override
public String toString() {
    return "CityReport{" +
            "city='" + city + '\'' +
            ", counter=" + counter +
            '}';
}
}

Angular Filter

Posted on Updated on

 

 

 

 

What is Filter in AngularJS?

Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters as given below, but it is easy to define your own as well.

The general syntax in templates is as follows:

{{ expression [| filter_name[:parameter_value] ... ] }}

Build-in AngularJS filter

Name Description
filter Selects a subset of items from array and returns it as a new array.
currency Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number Formats a number as text.
date Formats date to a string based on the requested format.
json Allows you to convert a JavaScript object into JSON string.
lowercase Converts string to lowercase.
uppercase Converts string to uppercase.
limitTo Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, it is converted to a string.
orderBy Returns an array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.

Currency Filter Example :-

In HTML Template Binding
{{ currency_expression | currency : symbol : fractionSize}}
In JavaScript
$filter('currency')(amount, symbol, fractionSize)
Snippet example here:-



Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{1234.1324 | currency : "USD$" :4}}

Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
<hr/>		


Date filter example :

In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
Snippet example here:-


 Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
 
 Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
 
 Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
 <hr/> 


Number filter example :

In HTML Template Binding
{{ number_expression | number : fractionSize}}
In JavaScript
$filter('number')(number, fractionSize)
Snippet example here:-
Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}

Json filter example :

In HTML Template Binding
{{ json_expression | json : spacing}}
In JavaScript
$filter('json')(object, spacing)
Snippet example here:-


 JSON : {{JSONValue}} Filter : {{JSONValue | json}}
 
 JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
 <hr/> 


Uppercase and Lowercase filter example :

In HTML Template Binding
{{ lowercase_expression | lowercase}}
{{ uppercase_expression | uppercase}}
In JavaScript
$filter('lowercase')()
$filter('uppercase')()
Snippet example here:-


 Name Value is {{name}}
 
 Upper Case : {{name | uppercase}}
 
 Lower Case : {{name | lowercase}}
 <hr/> 


 filter example :

In HTML Template Binding
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
In JavaScript
$filter('filter')(array, expression, comparator, anyPropertyKey)
Snippet example here:-
<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>

How to Create custom filter?

Writing your own filter is very easy: just register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.

angular.module("myApp",[]).filter('reverse', function() {
 return function(input, uppercase) {
 input = input || '';
 var out = '';
 for (var i = 0; i < input.length; i++) {
 out = input.charAt(i) + out;
 }
 // conditional based on optional argument
 if (uppercase) {
 out = out.toUpperCase();
 }
 return out;
 };
})</pre>

HTML binding here



<pre>

<div>
 <input ng-model="greeting" type="text">
 No filter: {{greeting}}
 Reverse: {{greeting|reverse}}
 Reverse + uppercase: {{greeting|reverse:true}}
 Reverse, filtered in controller: {{filteredGreeting}}
</div>


Complete Example here :-

<html ng-app="myApp">
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-controller="filterController">
	<h1> Angular Build-in Filter Example </h1>
	<hr/>
	<p>
		Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{currencyValue | currency : "USD$" :4}}
		<br/>
		Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
		<hr/>	
	</p>	

<p>
	Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
	<br/>
	Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
	<br/>
	Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
	<hr/>	
</p>

<p>
	Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}
	<hr/>	
</p>

<p>
	JSON : {{JSONValue}} Filter  : {{JSONValue | json}}
	<br/>
	JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
	<hr/>	
</p>

<p>
	Name Value is {{name}}
	<br/>
	Upper Case   : {{name | uppercase}}
	<br/>
	Lower Case   : {{name | lowercase}}
	<hr/>	
</p>

<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>
<p>
<input ng-model="greeting" type="text"><br>
  No filter: {{greeting}}<br>
  Reverse: {{greeting|reverse}}<br>
  Reverse + uppercase: {{greeting|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredGreeting}}<br>
</p>
</body>
<script type="text/javascript">
angular.module("myApp",[])
.controller("filterController",function($scope){
	$scope.todayDate = new Date();
	$scope.dateInTimestamp = $scope.todayDate.getTime();
	$scope.currencyValue = 1234.33;
	$scope.numberValue = 123.456789;
	$scope.JSONValue = "[{'key':'value'}]";
	$scope.name="Sample Angular Filter Example";
	$scope.listOfItem = [
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
})
.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = '';
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
</script>

</html>




What is Directive in AngularJS?

Posted on Updated on

What is Directive in AngularJS?

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope in Directive in AngularJS?

Unlike the other MVC frameworks, AngularJS doesn’t have specific classes or functions to create model objects. Instead, AngularJS extended the raw JavaScript objects with custom methods and properties. These objects, also known as scope in AngularJS terms, work as a glue between the view and other parts ( directives, controllers and services ) inside the AngularJS application.

Whenever the AngularJS application is bootstrapped, a rootScope object is created. Each scope created by controllers, directives and services are prototypically inherited from rootScope. AngularJS documentation is one of the best resources to learn how scope inheritance works: see Scopes in AngularJS. Understanding how scope inheritance works will be useful in following sections.

Directive Types:

You can implement the following types of directives:

The restrict option is typically set to:

  • 'A' – only matches attribute name
  • 'E' – only matches element name ( by Default )
  • 'C' – only matches class name
  • 'M' – only matches comment

These restrictions can all be combined as needed:

  • 'AEC' – matches either attribute or element or class name

 

Link – Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile – Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

Scope inside a directive

All directives have a scope associated with them. They use this scope for accessing data/methods inside the template and link function. By default, unless explicitly set, directives don’t create their own scope. Therefore, directives use their parent scope ( usually a controller ) as their own.

However, AngularJS allows us to change the default scope of directives by passing a configuration object known as directive definition object. A directive definition object –– let’s call it as DDO –– is a simple JavaScript object used for configuring the directive’s behaviour,template..etc. Check out AngularJS docs about DDO.

scope values can be either “false”“true” or “{}” in AngularJS directive.

Different types of directive scopes

Scope : False ( Directive uses its parent scope )

There will be no scope created in DDO therefore Directive use it parent scope. Any change made on the directive scope will be reflected in parent scope and vice versa. Both Controller and Directive scope will be in sync.

Scope : true ( Directive get new  scope )

it gets its own scope by setting up scope equals to true and assigned to directive.  This newly created scope object is prototypically inherited from its parent scope ( the controller scope where it’s been used ).

Let’s see difference between setting two  scope:false and scope:true

  • When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrtroller ( the parent scope ) will be reflected in the directive scope.
  • When scope is set to “false”, the controller Controller and directive are using the same scope object. This means any changes to the controller or directive will be in sync.

Scope : { } ( Directive gets a new isolated scope )

Till now, we saw two situations for directive scope creation. In the third type, we are going to set scope property in DDO to an Object literal. When an object literal is passed to the scope property, things are bit different. This time, there will be a new scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.

  • It’ll make sure that our directive is generic, and placed anywhere inside the application. Parent scope is not going to interfere with the directive scope.

Though it’s called as an Isolated scope, AngularJS allows to communicate with the parent scope using some special symbols knows as prefixes. Because of course there are still situations where the directive needs to be able to exchange data with parent scope. The next section is dedicated to Isolated scope and its properties.

There’re 3 types of prefixes AngularJS provides.

  1.  “@” ( Text binding / one-way binding )
  2.  “=” ( Direct model binding / two-way binding )
  3.  “&” ( Behaviour binding / Method binding )
  1. The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.
  2. Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.
  3. Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a method binding. This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.

 

AngularJS + RequireJS Example

Posted on Updated on

Prerequisite Dependency Javascripts Path –

You can download dependencies script files from below path.

Project Structure:-

 

 

 

 

 

 

 

 

index.html

HTML page for the arithmetic operation.

 

app.js

This is requireJS configuration file, so we defined all dependencies and javascript path.


requirejs.config({
	baseUrl: './scripts',
    shim : {
        angular: {
            exports : 'angular'
           },
        app:{
            deps:['angular','jquery']
        }

    },
    paths: {
        "angular" : "./../lib/angular.min",
        "bootstrap" :  "/../lib/bootstrap.min",
        "jquery":"./../lib/jquery-3.2.1.min",
        "main":"./../main"  
    }
});

requirejs(['main']);

main.js

In this file, we can add all components of AngularJS like Services, Controllers, Directive and Utility files. Since we are only using Controller file in this example so only Controller file is getting added into angular.module(…).


define(['RegisterControllers','angular'],function (RegisterControllers,angular) {

  angular.module('myApp', ['ui.controllers']);
  angular.bootstrap(document, ['myApp']);

});

Controllers/PrimaryController.js

In this Controller file, methods are defined which handle action on button clicked.


define(['angular'],
	function (angular) {

		var myCtrl = null;
		PrimaryController = function($scope){
			this.$scope = $scope;
			this.$scope.myCtrl = this;		
			this.init();
		}
		PrimaryController.$inject=["$scope"];

		PrimaryController.prototype ={
			init : function(){
        	this.$scope.message = "Hellow How are you";
        },
           doAction : function(){
           	var num1 = this.$scope.number1;
			var num2 = this.$scope.number2;

			this.$scope.result = parseInt(num1) + parseInt(num2);
           }
        
        };

		return PrimaryController;

	});

RegisterController.js –

Here, we register a Controller into angular.module(“ui.controllers”,[]). Also you can pass multiple controllers file path seperated by comma and assign into variables in function body then add all of them one by one in angular.module(…).controller(…).controller(..).

 


define(['./controllers/PrimaryController','angular'],
	function (PrimaryController,angular) {

    return angular.module("ui.controllers",[])
    	.controller("PrimaryController",PrimaryController);
});

Finally open index.html page in your browser, we will see the below output.

Download complete code here.

Thanks!!

What is requireJS

Posted on Updated on

What is RequireJS?

Modular Programming is used to break a large application into smaller blocks of manageable code which are always easy to maintain, readable and reusable, But it’s high cost of managing the dependencies between modules are always a major concern of developers face throughout the application development process.

So RequireJS is one of the most popular Javascript API to manage dependencies between modules and it supports AMD ( Asynchronous Module Definition  ) approach to load the modules and resolved their dependencies.

Benefits of RequireJS.

  • Easy to use and maintain than traditional ways of developing a web application.
  • Minimize the code repetition, Block of code can be easy to reused between the modules.
  • Hassle free of maintaining and keeping the scripts file in correct order.
  • Lazy loading ( Only load what you need, on demand and asynchronously )

Let’s check, how to use RequireJs

Project Hierarchy

 

 

 

 

 

 

Define an Entry point of RequireJS

First, download the latest requirejs library from here and keep it inside lib folder. Now we need to define a html file and could named index.html where RequireJS is loading as shown below.

Here, data-main is a meta attribute for requireJs that defines the initialization point of the application. it’s defined a relative path for the file where to load the RequireJS configuration.

RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing “.js” suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path.

 

Configure RequireJS

In the file app.js we defined the RequireJS config options and all files are locate under baseUrl, Since baseUrl is a current directory in this demo example but You can define the baseUrl in your application where all scripts files are placed.

How to create modules

Three modules are defined here;

message.js

print.js

aboutus.js

Execute code RequireJS

Once, modules are defined then need to inject the dependencies and call the function.

main.js

Result

We can see the output in the web console.

 

 

 

 

See next example of Angular+RequireJS

Hope you like it. Thanks

Configure an H2 in memory Database in Spring Boot.

Posted on

Spring Boot has great build in support for H2 database so here we will see how to configured in-memory database H2 using Spring Boot.

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed an h2 database into your application. H2 Database has a built in the web based console that you can use to interact with the database. You can use H2 database as an in-memory database, embedded database or network database. You can file more details from here.

It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.

First of all here are the maven dependencies for spring boot to use H2 Database. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.boot.example</groupId>
    <artifactId>Spring_H2_Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring_boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.194</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    </dependencies>

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


</project>

Here, we created a SQL Schema file and dummy file under resource folder ( main/java/resources ), When our application gets started then it creates table and inserts into it.

sql/schema.sql file

DROP TABLE IF EXISTS User_Details;
create table User_Details (id integer not null auto_increment,
 email varchar(255),
 first_Name varchar(255),
 last_Name varchar(255),
 password varchar(255), primary key (id)
);

sql/data.sql file

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('rahul@gmail.com','Rahul','sharma','rahul@ku123123!');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('shyam_babul@yahoo.com','Sham','babul','shyam#babul!2123');

Since Spring boot can auto configure in-memory database ( h2 ) so you don’t need to provide configuration details unless the application has been configured in other ways. If you see in below application.properties file where it has been configured from where Schema and SQL file should be picked up from resources folder.

application.properties file contains all the required configurations to connect h2 database and run Spring Boot.

# Spring Boot can auto-configured H2 database.

spring.jpa.database=H2
spring.datasource.url=jdbc:h2:mem:test;MODE=Oracle
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.max-active=1
spring.jpa.hibernate.ddl-auto=false
spring.h2.console.enabled=true
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true
spring.h2.console.path=/h2
spring.datasource.schema=classpath*:sql/schema.sql
spring.datasource.data=classpath*:sql/data.sql


# Here, We create a new "local" Datasource for our application using it we can perform 'ddl' and 'dml' operations.
# Hence, it's redundant but we enabled spring data source.

local.datasource.url=jdbc:h2:mem:test;MODE=Oracle
local.datasource.username=sa
local.datasource.password=
local.datasource.driver-class-name=org.h2.Driver
local.datasource.max-active=1

Model Class

package com.spring.boot.example.domain;

public class UserDetails {

    private long id;
    private String email;
    private String first_name;
    private String last_name;
    private String password;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UserDetails{");
        sb.append("id=").append(id);
        sb.append(", email='").append(email).append('\'');
        sb.append(", first_name='").append(first_name).append('\'');
        sb.append(", last_name='").append(last_name).append('\'');
        sb.append(", password='").append(password).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

Repository Class


package com.spring.boot.example.repo;

import com.spring.boot.example.domain.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDetailsRepository {

@Autowired
private JdbcTemplate jdbcTemplate;

public List printUserDetailsData(){
return jdbcTemplate.query("SELECT * FROM USER_DETAILS",new UserDetailsRowMapper());
}

class UserDetailsRowMapper implements RowMapper{

@Override
public UserDetails mapRow(ResultSet resultSet, int i) throws SQLException {
UserDetails userDetails = new UserDetails();
userDetails.setId(resultSet.getInt("id"));
userDetails.setEmail(resultSet.getString("email"));
userDetails.setFirst_name(resultSet.getString("first_Name"));
userDetails.setLast_name(resultSet.getString("last_Name"));
userDetails.setPassword(resultSet.getString("password"));
return userDetails;
}
}
}

Main Class

package com.spring.boot.example;

import com.spring.boot.example.domain.UserDetails;
import com.spring.boot.example.repo.UserDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

@SpringBootApplication(exclude = JmsAutoConfiguration.class)
public class H2MainApp {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =  SpringApplication.run(H2MainApp.class, args);
        List<UserDetails> userDetailsList = context.getBean(UserDetailsRepository.class).printUserDetailsData();
        for(UserDetails userDetails : userDetailsList){
            System.out.println(userDetails);
        }
    }

    @Bean
    @ConfigurationProperties(prefix = "local.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}

Output:-

2017-08-12 15:11:57.899 INFO 4956 — [ main] com.spring.boot.example.H2MainApp : Started H2MainApp in 7.839 seconds (JVM running for 8.638)
UserDetails{id=1, email=’admin@admin.com’, first_name=’admin’, last_name=’admin’, password=’admin’}
UserDetails{id=2, email=’rahul@gmail.com’, first_name=’Rahul’, last_name=’sharma’, password=’rahul@ku123123!’}
UserDetails{id=3, email=’shyam_babul@yahoo.com’, first_name=’Sham’, last_name=’babul’, password=’shyam#babul!2123′}

Also, H2 Web Console can be enabled by enabling these properties in application.properties. It is a convenient way to view the tables created and run queries against the in memory database.  Here is an example of the H2 database console.

Keep these properties in your application.properties to enable H2 Web Console.

spring.h2.console.enabled=true

spring.h2.console.settings.web-allow-others=true

spring.h2.console.path=/h2