Spring DI – Environment Setup

Spring DI – Environment Setup ”; Previous Next This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework − Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:jdk-11.0.11, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk-11.0.11;%PATH% set JAVA_HOME=C:jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Set Maven In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven – Environment Setup to install maven. Print Page Previous Next Advertisements ”;

Spring Boot JPA – Named Query

Spring Boot JPA – Named Queries ”; Previous Next Some time case arises, where we need a custom query to fulfil one test case. We can use @NamedQuery annotation to specify a named query within an entity class and then declare that method in repository. Following is an example. We”ve added custom methods in Repository in JPA Custom Methods chapter. Now let”s add another method using @NamedQuery and test it. Entity – Entity.java Following is the default code of Employee. It represents a Employee table with id, name, age and email columns. package com.tutorialspoint.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table @NamedQuery(name = “Employee.findByEmail”, query = “select e from Employee e where e.email = ?1″) public class Employee { @Id @Column private int id; @Column private String name; @Column private int age; @Column private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Repository – EmployeeRepository.java Add a method to find an employee by its name and age. package com.tutorialspoint.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.tutorialspoint.entity.Employee; @Repository public interface EmployeeRepository extends CrudRepository<Employee, Integer> { public List<Employee> findByName(String name); public List<Employee> findByAge(int age); public Employee findByEmail(String email); } Now Spring JPA will create the implementation of above methods automatically using the query provided in named query. Let”s test the methods added by adding their test cases in test file. Last two methods of below file tests the named query method added. Following is the complete code of EmployeeRepositoryTest. package com.tutorialspoint.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.tutorialspoint.entity.Employee; import com.tutorialspoint.sprintbooth2.SprintBootH2Application; @ExtendWith(SpringExtension.class) @Transactional @SpringBootTest(classes = SprintBootH2Application.class) public class EmployeeRepositoryTest { @Autowired private EmployeeRepository employeeRepository; @Test public void testFindById() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee result = employeeRepository.findById(employee.getId()).get(); assertEquals(employee.getId(), result.getId()); } @Test public void testFindAll() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findAll().forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testSave() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee found = employeeRepository.findById(employee.getId()).get(); assertEquals(employee.getId(), found.getId()); } @Test public void testDeleteById() { Employee employee = getEmployee(); employeeRepository.save(employee); employeeRepository.deleteById(employee.getId()); List<Employee> result = new ArrayList<>(); employeeRepository.findAll().forEach(e -> result.add(e)); assertEquals(result.size(), 0); } private Employee getEmployee() { Employee employee = new Employee(); employee.setId(1); employee.setName(“Mahesh”); employee.setAge(30); employee.setEmail(“[email protected]”); return employee; } @Test public void testFindByName() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findByName(employee.getName()).forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testFindByAge() { Employee employee = getEmployee(); employeeRepository.save(employee); List<Employee> result = new ArrayList<>(); employeeRepository.findByAge(employee.getAge()).forEach(e -> result.add(e)); assertEquals(result.size(), 1); } @Test public void testFindByEmail() { Employee employee = getEmployee(); employeeRepository.save(employee); Employee result = employeeRepository.findByEmail(employee.getEmail()); assertNotNull(result); } } Run the test cases Right Click on the file in eclipse and select Run a JUnit Test and verify the result. Print Page Previous Next Advertisements ”;

Spring DI – Create Project

Spring Dependency Injection – Create Project ”; Previous Next Using eclipse, select File → New → Maven Project. Tick the Create a simple project(skip archetype selection) and click Next. Enter the details, as shown below − groupId − com.tutorialspoint artifactId − springdi version − 0.0.1-SNAPSHOT name − springdi description − Spring Dependency Injection Project Click on Finish button and an new project will be created. pom.xml Update the pom.xml with Spring Core dependency. Following is the full content of pom.xml <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 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>springdi</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springdi</name> <description>Spring Dependency Injection Project</description> <properties> <org.springframework.version>5.3.9</org.springframework.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project> applicationcontext.xml Create applicationcontext.xml in src → main → resources with the following content. applicationcontext.xml <?xml version=”1.0″ encoding=”UTF-8″?> <beans xmlns=”http://www.springframework.org/schema/beans” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> </beans> Print Page Previous Next Advertisements ”;

Spring Boot JPA – Discussion

Discuss Spring Boot JPA ”; Previous Next JPA is a specification which specifies how to access, manage and persist information/data between java objects and relational databases. It provides a standard approach for ORM, Object Relational Mapping. Spring Boot provides a seemless integration with JPA. Print Page Previous Next Advertisements ”;

Spring Boot CLI – Creating Project

Spring Boot CLI – Creating Project ”; Previous Next Spring Boot CLI can be used to create a new project with maven as default build tool using init command. Maven will use https://start.spring.io service. In the following example, we will create a web application using thymeleaf. Go to E:Test folder and type the following command − E:/Test> spring init –dependencies = web,thymeleaf MavenApplication.zip The above command will generate the following output − Using service at https://start.spring.io Content saved to MavenApplication.zip Create Gradle project We can create a Gradle based project as well by setting –build as gradle. To understand this in a better way, consider the example given below. Go to E:Test folder and type the following command − E:/Test> spring init –build = gradle –java-version = 1.8 –dependencies = web,thymeleaf –packaging = war GradleApplication.zip The above command will generate the following output − Using service at https://start.spring.io Content saved to GradleApplication.zip Print Page Previous Next Advertisements ”;

Spring SpEL – Functions

Spring SpEL – Functions ”; Previous Next SpEL expression allows to create and use functions specific to expression using #function-name syntax. A function is set using registerFunction on EvaluationContext. Syntax context.registerFunction(“reverse”, MainApp.class.getDeclaredMethod(“reverse”, new Class[] { String.class })); Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − MainApp.java − Main application to run and test. Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException, NoSuchMethodException, SecurityException { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); context.registerFunction(“reverse”, MainApp.class.getDeclaredMethod(“reverse”, new Class[] { String.class })); String reverseString=parser.parseExpression(“#reverse(”main”)”).getValue(context, String.class); System.out.println(reverseString); } public static String reverse(String input) { StringBuilder backwards = new StringBuilder(); for (int i = 0; i < input.length(); i++) { backwards.append(input.charAt(input.length() – 1 – i)); } return backwards.toString(); } } Output niam Print Page Previous Next Advertisements ”;

Spring ORM – Maven Hibernate

Spring ORM – Maven Hibernate ”; Previous Next Let”s add following dependencies in pom.xml. Spring Framework Hibernate MySQL Connector Other related dependencies. Update the pom.xml as per below content. pom.xml <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 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>springorm</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Spring ORM</name> <description>Spring ORM Test Project</description> <properties> <org.springframework.version>4.3.7.RELEASE</org.springframework.version> <org.hibernate.version>5.2.9.Final</org.hibernate.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.13</version> </dependency> <dependency> <groupId>com.sun.activation</groupId> <artifactId>javax.activation</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.1</version> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project> Now right click on the project name. Select Maven → Update Project to download the required dependencies. Print Page Previous Next Advertisements ”;

Spring ORM – Quick Guide

Spring ORM – Quick Guide ”; Previous Next Spring ORM – Overview The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. Spring allows to configure ORM library features through dependency management. Spring maintains a uniform DAO Exception hiearchies and a generic transaction management for all the ORM libraries it supports. Spring IoC container facilitates ORM configurations and easy deployment. Following are the key benefits of using Spring framework to create ORM DAO. Easy to Test − Using spring IoC, an ORM implementation can be easily configured. Each piece of persistence unit can be tested in isolation. Common Data Access Exception − Spring wraps ORM Tools exceptions to a common runtime exception as DataAccessException. This approach helps to handle most persistence exception (non-recoverable) in appropriate layers. No need to handle ORM specific boilerplate catch/throws/exception declarations. General Resource Management − Spring application contexts manages persistence objects, their configurations easily. For example, Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, iBatis SQL Maps configuration objects and other related objects. Spring handles the local as well JTA transaction management by itself. Integrated transaction management − Spring AOP can be used to wrap an ORM code with a declarative AOP styled interceptor either using @Transaction annotation or by specifying transaction AOP advice in XML configuration file. Spring handles transaction semantics, exception handling, rollback and so on. Spring allows to swap transaction managers without affecting the ORM code. Spring ORM – Environment Setup This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework − Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:jdk-11.0.11, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk-11.0.11;%PATH% set JAVA_HOME=C:jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Install MySQL Database The most important thing you will need, of course is an actual running database with a table that you can query and modify. MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:Program FilesMySQLmysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:Program FilesMySQLmysql-connector-java-5.1.8mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. Set Database Credential When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. Create Database To create the TUTORIALSPOINT database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Step 2 Start the database

Spring ORM – Home

Spring ORM Tutorial PDF Version Quick Guide Resources Job Search Discussion The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. In this tutorial, we”ll cover all the important ORM frameworks which are supported by Spring ORM framework which helps in solving the common problems developers/users face in spring framework based applications. Audience This tutorial is designed for Java programmers with a need to understand the Spring framework in detail along with its architecture and actual usage. This tutorial will bring you at an intermediate level of expertise, from where you can take yourself to higher levels of expertise. Prerequisites Before proceeding with this tutorial, you should have a good understanding of Java programming language. Print Page Previous Next Advertisements ”;

Spring SpEL – Overview

Spring SpEL – Overview ”; Previous Next The Spring Expression Language, SpEL is a very powerful expression language and it supports querying and manipulating an object graph at runtime. It offers many advanced features like method invocation and basic string templating functionality. Spring Expression Language was originally created for the Spring community to have a single well supported expression language to be used across all the products in the Spring portfolio. While SpEL serves as the foundation for expression evaluation within the Spring portfolio, it is not directly tied to Spring and can be used independently. Following is the list of functionalities that Spring Expression Language, SpEL supports: Literal expressions Boolean and relational operators Regular expressions Class expressions Accessing properties, arrays, lists, maps Method invocation Relational operators Assignment Calling constructors Bean references Array construction Inline lists Ternary operator Variables User defined functions Collection projection Collection selection Templated expressions We”ll cover each and every topic in next chapters. Print Page Previous Next Advertisements ”;