Commonly Used Terms in Java Spring Frameworks

  • By
  • January 18, 2020
  • JAVAJAVA Programming
Commonly Used Terms in Java Spring Frameworks

Commonly Used Terms in Java Spring Frameworks

Java Spring Framework

Java Server Faces (JSF): JSF stands for Java server faces is a web application framework based on java to simplify application development integration of web user interfaces.

It is a server-side process to allow embed server-side code into a web page. This makes code simpler and short after rendering into web page. JSF has two major components:

Java Facets: This JF is a file resides on a server to acts as a controller and it redirects the client request to the concern JSF web page. 

JSF tags: JDF tags allow server-side scripting to be embedded into a web page and it also provides custom tags to perform some basic operations and iterations.

All above stuff makes it MVC form. I.e. Model View Controller.

Managed Bean in JSF is a regular Java Bean classes registered with JSF. That is Managed Beans is a Java bean class managed by the JSF framework effectively. Managed bean class is like POJO class contains the setter and getter methods to set attributes, business logic with functions, o HTML form bean to backup. Managed beans work as UI component model. These Managed Beans can be accessed from the JSF web page. In JSF a managed beans have to be registered from JSF configuration file facesconfig.xml. Even now it can be managed with java annotations. Understand all terms within Java Course In Pune

For Example 1:

package com.sevenmentor;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.ManagedProperty;

import javax.faces.bean.RequestScoped;

@ManagedBean(name = “welcomeJava”, eager = true)

@RequestScoped

public class WelcomeJava {

   @ManagedProperty(value = “#{message}”)

   private Message messageBean;

   private String message;

      public WelcomeJava() {

      System.out.println(“WelcomeJava started!”);   

   }

      public String getMessage() {      

      if(messageBean != null) {

         message = messageBean.getMessage();

      }       

      return message;

   }   

   public void setMessageBean(Message message) {

      this.messageBean = message;

   }

}

——————————————————————————————————

package com.sevenmentor;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.RequestScoped;

@ManagedBean(name = “message”, eager = true)

@RequestScoped

public class Message {

   private String message = “WelcomeJava”;

   public String getMessage() {

      return message;

   }

   public void setMessage(String message) {

      this.message = message;

   }

}

——————————————————————————————————

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 2.0 Transitional//EN”

   “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns = “http://www.w3.org/2004/xhtml”>

   <head>

      <title>JSF Demo</title>

   </head>

      <body>

      #{welcomeJava.message}

   </body></html>

——————————————————————————————————-

Example 2: 

package com.sevenmentor;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.ManagedProperty;

import javax.faces.bean.RequestScoped;

@ManagedBean(name = “meesage1”, eager = true)

@RequestScoped

public class Message1 {

   @ManagedProperty(value = “#{message}”)

   private Message messageBean;

   private String message;

      public Message1() {

      System.out.println(“Message1 started!”);   

   }

      public String getMessage() {

            if(messageBean != null) {

         message = messageBean.getMessage();

      }       

      return message;

   }

   public void setMessageBean(Message message) {

      this.messageBean = message;

   }

}

——————————————————————————————————–

package com.sevenmentor;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.RequestScoped;

@ManagedBean(name = “message”, eager = true)

@RequestScoped

public class Message {

   private String message = “Message1”;

   public String getMessage() {

      return message;

   }

   public void setMessage(String message) {

      this.message = message;

   }

}

——————————————————————————————————-

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 2.0 Transitional//EN”

   “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns = “http://www.w3.org/2004/xhtml”>

   <head>

      <title>JSF Demo</title>

   </head>

   <body>

      #{meesage1.message}

   </body></html>

——————————————————————————————————–

Maven: You must have heard about the Maven repository. It is an application build automation tool used mainly for Java projects and also it can manage other programming language projects. Maven mainly works on how software has been built and its required dependencies. Its easier to maintain project dependencies using maven XML configurations. It also easily builds the project without the overhead of external jar files.

For example 1:

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.techprimers.jpa</groupId>

<artifactId>spring-jpa-hibernate-example</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

<name>spring-jpa-hibernate-example</name>

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

<parent>

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

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

<version>1.5.3.RELEASE</version>

<relativePath/> <!– lookup parent from repository –>

</parent>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

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

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

</dependency>

<dependency>

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

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

</dependency>

<dependency>

<groupId>mysql</groupId>

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

<scope>runtime</scope>

</dependency>

<dependency>

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

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

<scope>test</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

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

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

——————————————————————————————————

Example2:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd”>

<modelVersion>4.0.0</modelVersion>

<parent>

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

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

<version>2.2.2.RELEASE</version>

<relativePath/> <!– lookup parent from repository –>

</parent>

<groupId>com.springbootsecurity</groupId>

<artifactId>spring-bootjpa-security</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>spring-bootjpa-security</name>

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

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

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

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

</dependency>

<dependency>

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

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

</dependency>

<dependency>

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

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

</dependency>

<dependency>

<groupId>mysql</groupId>

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

<scope>runtime</scope>

</dependency>

<dependency>

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

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

<scope>test</scope>

<exclusions>

<exclusion>

<groupId>org.junit.vintage</groupId>

<artifactId>junit-vintage-engine</artifactId>

</exclusion>

</exclusions>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

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

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

——————————————————————————————————

Play: Play is an open-sourced web application framework that follows concrete MVC i.e. Model View and Controller model. This framework is developed using scala language so it works with common java JVM. This framework gives higher productivity in work-flows with high scalability. It provides the RAD feature as rapid application development. Here compilation and loading happen in the background which makes it more faster. 

For Example1:

package com.sevenmentor

 import com.google.inject.Inject

import play.api.mvc.InjectedController

 class SevenMessage @Inject() extends InjectedController {

   def sevenMessage = Action {

    Ok(com.jcg.examples.playscala.views.html.sevenMessage(“Dear candidates, Welcome to Play Java framework!!”))

  }

 }

——————————————————————————————————

build.sbt includes following:

name := “PlayFrameworkScalaSevenMessage”

 version := “1.0.0”

 lazy val root = (project in file(“.”)).enablePlugins(PlayScala)

 scalaVersion := “2.12.6”

 libraryDependencies ++= Seq(guice)

——————————————————————————————————

Example2: 

package com.sevenmentor

 import com.google.inject.Inject

import play.api.mvc.InjectedController

 class MyMessage @Inject() extends InjectedController {

   def myMessage = Action {

    Ok(com.jcg.examples.playscala.views.html.myMessage(“message1”))

  }

 }

——————————————————————————————————

build.sbt inclues following:

name := “PlayFrameworkScalaMyMessage “

 version := “1.0.0”

 lazy val root = (project in file(“.”)).enablePlugins(PlayScala)

 scalaVersion := “2.12.6”

 libraryDependencies ++= Seq(guice)

——————————————————————————————————

Apache Struts: Its a web framework to work Java EE projects. It also provides MVC i.e. Model View Controller based architecture to enhance the product in a better way. Apache Struts helps fix the problems with existing Java Enterprise Edition web application by separating the model (logic for a database) from the view (Web pages shown to a client) and from the controller (information transfer between model and view). Struts provide the controller template for the presentation layer or view for the client. The programmer just needs to write the model code through the configuration file to bind MVC together.

For example1:

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 http://maven.apache.org/xsd/maven-5.0.0.xsd”>

<modelVersion>5.0.0</modelVersion>

<groupId>SevenStrutsDemo</groupId>

<artifactId>SevenStrutsDemo</artifactId>

<version>0.0.2-SNAPSHOT</version>

<packaging>war</packaging>

<dependencies>

<dependency>

<groupId>org.apache.struts</groupId>

<artifactId>struts2-core</artifactId>

<version>2.3.15.1</version>

</dependency>

</dependencies>

<build>

<sourceDirectory>src</sourceDirectory>

<plugins>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.1</version>

<configuration>

<source>1.6</source>

<target>1.6</target>

</configuration>

</plugin>

<plugin>

<artifactId>maven-war-plugin</artifactId>

<version>2.3</version>

<configuration>

<warSourceDirectory>WebContent</warSourceDirectory>

<failOnMissingWebXml>false</failOnMissingWebXml>

</configuration>

</plugin>

</plugins>

<finalName>${project.artifactId}</finalName>

</build>

</project>

——————————————————————————————————

web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xmlns=”http://java.sun.com/xml/ns/javaee”

xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd”

version=”4.0″>

<display-name>SevenStrutsDemo</display-name>

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>

——————————————————————————————————

first.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

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

<%– Using struts Tags in JSP –%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>First Log Page</title>

</head>

<body>

<h3>Welcome User, please login below</h3>

<s:form action=”log”>

<s:textfield name=”name” label=”User Name”></s:textfield>

<s:textfield name=”pwd” label=”Password” type=”password”></s:textfield>

<s:submit value=”Login”></s:submit>

</s:form>

</body>

</html>

——————————————————————————————————

Second.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

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

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>Second Page</title>

</head>

<body>

<h3>Hi <s:property value=”name”></s:property></h3>

</body>

</html>

——————————————————————————————————-

MyError.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

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

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>My Error Page</title>

</head>

<body>

<h4>User Name or Password is invalid</h4>

<s:include value=”first.jsp”></s:include>

</body>

</html>

——————————————————————————————————-

FirstAction.java

package com.SevenStrutsDemo;

import com.opensymphony.xwork2.Action;

public class FirstAction implements Action {

@Override

public String execute() throws Exception {

if(“Seven”.equals(getName()) && “admin”.equals(getPwd()))

return “SUCCESS”;

else return “ERROR”;

}

//Java Bean to hold the form parameters

private String name;

private String pwd;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

}

——————————————————————————————————-

struts.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.6//EN”

“http://struts.apache.org/dtds/struts-2.6.dtd”>

<struts>

<package name=”user” namespace=”/User” extends=”struts-default”>

<action name=”home”>

<result>/first.jsp</result>

</action>

<action name=”first” class=”com.sevenmentor.LoginAction”>

<result name=”SUCCESS”>/second.jsp</result>

<result name=”ERROR”>/MyError.jsp</result>

</action>

</package>

——————————————————————————————————

Example2:

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 http://maven.apache.org/xsd/maven-5.0.0.xsd”>

<modelVersion>5.0.0</modelVersion>

<groupId>MyExampleDemo</groupId>

<artifactId>MyExampleDemo</artifactId>

<version>0.0.3-SNAPSHOT</version>

<packaging>war</packaging>

<dependencies>

<dependency>

<groupId>org.apache.struts</groupId>

<artifactId>struts2-core</artifactId>

<version>2.3.16.1</version>

</dependency>

</dependencies>

<build>

<sourceDirectory>src</sourceDirectory>

<plugins>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.2</version>

<configuration>

<source>1.7</source>

<target>1.7</target>

</configuration>

</plugin>

<plugin>

<artifactId>maven-war-plugin</artifactId>

<version>2.4</version>

<configuration>

<warSourceDirectory>WebContent</warSourceDirectory>

<failOnMissingWebXml>false</failOnMissingWebXml>

</configuration>

</plugin>

</plugins>

<finalName>${project.artifactId}</finalName>

</build>

</project>

——————————————————————————————————

web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xmlns=”http://java.sun.com/xml/ns/javaee”

xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd”

version=”4.0″>

<display-name>MyExampleDemo</display-name>

<filter>

<filter-name>struts</filter-name>

<filter-class>org.apache.struts.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>struts</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>

——————————————————————————————————

MyExample1.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

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

<%– Using struts Tags in JSP –%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>MyExample1</title>

</head>

<body>

<h3>Welcome, please check below</h3>

<s:form action=”check”>

<s:textfield name=”name” label=”User Name”></s:textfield>

<s:textfield name=”contact” label=”Contact”></s:textfield>

<s:submit value=”Submit”></s:submit>

</s:form>

</body>

</html>

——————————————————————————————————

check.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

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

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>MyExample2</title>

</head>

<body>

<h3>Hi <s:property value=”name”></s:property></h3>

</body>

</html>

——————————————————————————————————

MyError.jsp

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

<%@ taglib uri=”/struts-tags” prefix=”s”%>

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

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>My Error Page</title>

</head>

<body>

<h4>User Name is invalid</h4>

<s:include value=”MyExample1.jsp”></s:include>

</body>

</html>

——————————————————————————————————

FirstAction.java

package com.MyExampleDemo;

import com.opensymphony.xwork2.Action;

public class FirstAction implements Action {

@Override

public String execute() throws Exception {

if(“Seven”.equals(getName()) && “admin”.equals(getPwd()))

return “SUCCESS”;

else return “ERROR”;

}

//Java Bean to hold the form parameters

private String name;

private String contact;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getcontact() {

return contact;

}

public void setContact(String contact) {

this.contact = contact;

}

}

——————————————————————————————————-

struts.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.6//EN”

“http://struts.apache.org/dtds/struts-2.6.dtd”>

<struts>

<package name=”user” namespace=”/User” extends=”struts-default”>

<action name=”home”>

<result>/MyExample1.jsp</result>

</action>

<action name=”MyExample1″ class=”com.sevenmentor.MyExample1Action”>

<result name=”SUCCESS”>/second.jsp</result>

<result name=”ERROR”>/MyError.jsp</result>

</action>

</package>

——————————————————————————————————

ORM: Object Relational Mappers. Its a technique for converting data between incompatible type systems in RDBMS and Java language. It is good for abstracting the SQL or flat file to provide an interface in your code.  

For exampl1:

Employee.hbm.xml

<?xml version = “1.0” encoding = “utf-8”?>

<!DOCTYPE hibernate-mapping PUBLIC 

“-//Hibernate/Hibernate Mapping DTD//EN”

“http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”> 

<hibernate-mapping>

   <class name = “Employee” table = “EMPLOYEE”>

            <meta attribute = “class-description”>

         This class contains the employee detail. 

      </meta>

            <id name = “id” type = “int” column = “id”>

         <generator class=”native”/>

      </id>

            <property name = “firstName” column = “first_name” type = “string”/>

      <property name = “lastName” column = “last_name” type = “string”/>

      <property name = “salary” column = “salary” type = “int”/>

         </class>

</hibernate-mapping>

——————————————————————————————————

Hibernate.cfg.xml

<?xml version = “1.0” encoding = “utf-8”?>

<!DOCTYPE hibernate-configuration SYSTEM 

“http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>

   <session-factory>

      <property name = “hibernate.dialect”>

         org.hibernate.dialect.MySQLDialect

      </property>

      <property name = “hibernate.connection.driver_class”>

         com.mysql.jdbc.Driver

      </property>

      <!– Assume students is the database name –>

         <property name = “hibernate.connection.url”>

         jdbc:mysql://localhost/mydb

      </property>

         <property name = “hibernate.connection.username”>

         test

      </property>

         <property name = “hibernate.connection.password”>

         test123

      </property> 

      <!– List of XML mapping files –>

      <mapping resource = “Employee.hbm.xml”/>

     </session-factory>

</hibernate-configuration>

—————————————————————————————————–

Employee.java

public class Employee {

   private int id;

   private String firstName; 

   private String lastName;   

   private int salary;  

   public Employee() {}

      public Employee(String fname, String lname, int salary) {

      this.firstName = fname;

      this.lastName = lname;

      this.salary = salary;

   }

      public int getId() {

      return id;

   }

      public void setId( int id ) {

      this.id = id;

   }

      public String getFirstName() {

      return firstName;

   }

      public void setFirstName( String first_name ) {

      this.firstName = first_name;

   }

      public String getLastName() {

      return lastName;

   }

      public void setLastName( String last_name ) {

      this.lastName = last_name;

   }

      public int getSalary() {

      return salary;

   }

      public void setSalary( int salary ) {

      this.salary = salary;

   }

}

——————————————————————————————————-

ManageEmployee.java

import java.util.List; 

import java.util.Date;

import java.util.Iterator; 

import org.hibernate.HibernateException; 

import org.hibernate.Session; 

import org.hibernate.Transaction;

import org.hibernate.SessionFactory;

import org.hibernate.Criteria;

import org.hibernate.criterion.Restrictions;

import org.hibernate.criterion.Projection;

import org.hibernate.criterion.Projections;

import org.hibernate.cfg.Configuration;

public class ManageEmployee {

     public static void main(String[] args) {

  Configuration cfg = new Configuration();

       cfg.configure(“hibernate.cfg.xml”);

       SessionFactory factory = cfg.buildSessionFactory();

       Session session = factory.openSession();

       Transaction tx = session.beginTransaction();  

  Criteria cr = session.createCriteria(Employee.class); 

  cr.setProjection(Projections.avg(“salary”));

  List restrictionsRowCount = cr.list();

  System.out.println(restrictionsRowCount);

      tx.commit();

       session.close();

       factory.close();

   }

}

——————————————————————————————————-

Certificate.java

public class Certificate {

   private int id;

   private String name; 

   public Certificate() {}

      public Certificate(String name) {

      this.name = name;

   }

      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 boolean equals(Object obj) {

      if (obj == null) return false;

      if (!this.getClass().equals(obj.getClass())) return false;

      Certificate obj2 = (Certificate)obj;

      if((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {

         return true;

      }

      return false;

   }

      public int hashCode() {

      int tmp = 0;

      tmp = ( id + name ).hashCode();

      return tmp;

   }

}

——————————————————————————————————-

OXM: It is a Spring Object XML Mappers and it is a module available in Spring to do a mapping between Java objects and XML documents like bean.xml etc. JAXB stands for Java Architecture for XML Binding and learn more about it through Java Training In Pune.  

For example:

pom.xml

<properties>

<spring.version>3.0.10.RELEASE</spring.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>${spring.version}</version>

</dependency>

<!– spring oxm –>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-oxm</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.codehaus.castor</groupId>

<artifactId>castor</artifactId>

<version>1.2</version>

</dependency>

<dependency>

<groupId>xerces</groupId>

<artifactId>xercesImpl</artifactId>

<version>2.8.10</version>

</dependency>

</dependencies>

——————————————————————————————————-

SimpleObject 

package com.sevenmentor;

public class Student {

String name;

int age;

boolean flag;

String address;

}

——————————————————————————————————-

Marshaller and Unmarhshaller class

package com.sevenmentor;

import java.io.*;

import javax.xml.transform.stream.*;

import org.springframework.oxm.*;

public class MyXMLConverter {

private Marshaller myMarsh;

private UnmyMarsh unmyMarsh;

public Marshaller getMarshaller() {

return myMarsh;

}

public void setMarshaller(Marshaller myMarsh) {

this.myMarsh = myMarsh;

}

public UnmyMarsh getUnmyMarsh() {

return unmyMarsh;

}

public void setUnmyMarsh(UnmyMarsh unmyMarsh) {

this.unmyMarsh = unmyMarsh;

}

public void convertFromObjectToXML(Object object, String filepath)

throws IOException {

FileOutputStream os = null;

try {

os = new FileOutputStream(filepath);

getMarshaller().marshal(object, new StreamResult(os));

} finally {

if (os != null) {

os.close();

}

}

}

public Object convertFromXMLToObject(String xmlfile) throws IOException {

FileInputStream is = null;

try {

is = new FileInputStream(xmlfile);

return getUnmyMarsh().unmarshal(new StreamSource(is));

} finally {

if (is != null) {

is.close();

}

}

}

}

——————————————————————————————————

Spring configuration class

<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-4.0.xsd”>

<bean id=”MyXMLConverter” class=”com.sevenmentor.MyXMLConverter”>

<property name=”marsh” ref=”castorMarshaller” />

<property name=”unmar” ref=”castorMarshaller” />

</bean>

<bean id=”castorMarshaller” class=”org.springframework.oxm.castor.CastorMarshaller” />

</beans>

——————————————————————————————————-

Test class

package com.sevenmentor;

import java.io.IOException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sevenmentor.model.Student;

public class App {

private static final String XML_FILE_NAME = “student.xml”;

public static void main(String[] args) throws IOException {

ApplicationContext appContext = new ClassPathXmlApplicationContext(“App.xml”);

XMLConverter converter = (XMLConverter) appContext.getBean(“XMLConverter”);

Student student = new Student();

student.setName(“seven”);

student.setAge(35);

student.setFlag(true);

student.setAddress(“Pune”);

System.out.println(“Convert Object to XML!”);

//from object to XML file

converter.convertFromObjectToXML(student, XML_FILE_NAME);

System.out.println(“Done \n”);

System.out.println(“Convert XML back to Object!”);

//from XML to object

Student student2 = (Student)converter.convertFromXMLToObject(XML_FILE_NAME);

System.out.println(student2);

System.out.println(“Done”);

}

}

——————————————————————————————————–

student.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<student flag=”true” age=”35″>

<address>Pune</address>

<name>seven</name>

</student>

——————————————————————————————————-

mapping.xml

<mapping>

<class name=”com.sevenmentor.Student”>

<map-to xml=”student” />

<field name=”age” type=”integer”>

<bind-xml name=”age” node=”attribute” />

</field>

<field name=”flag” type=”boolean”>

<bind-xml name=”flag” node=”element” />

</field>

<field name=”name” type=”string”>

<bind-xml name=”name” node=”element” />

</field>

<field name=”address” type=”string”>

<bind-xml name=”address” node=”element” />

</field>

</class>

</mapping>

——————————————————————————————————-

JMS: JMS stands for Java Message Service API is a Java message-oriented API for sending messages between clients and its middleware. Java Message Service (JMS) is an application programming interface (API) by an oracle to work as middleware. It is designed for an exchange of asynchronous, reliable messages between different clients can be software applications, are based on the J2EE. JMS is a messaging standard for creating, sending, receiving and reading messages as requests by clients. This also allows having communication between different programs written in different programming languages.

For Example:

Sender class

    import java.io.*;  

    import javax.naming.*;  

    import javax.jms.*;  

          public class MessageSender {  

        public static void main(String[] args) {  

            try  

            {   //Create and start connection  

                InitialContext ctx=new InitialContext();  

                QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup(“QueueConnectionFactory”);  

                QueueConnection con=f.createQueueConnection();  

                con.start();  

                QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  

                                 Queue t=(Queue)ctx.lookup(“Queue”);  

                                      QueueSender sender=ses.createSender(t);  

                TextMessage msg=ses.createTextMessage();  

                                  BufferedReader b=new BufferedReader(new InputStreamReader(System.in));  

                while(true)  

                {  

                    System.out.println(“Msg enter else terminate”);  

                    String s=b.readLine();  

                    if (s.equals(“end”))  

                        break;  

                    msg.setText(s);  

                                         sender.send(msg);  

                    System.out.println(“Message sent.”);  

                }  

                                con.close();  

            }catch(Exception e){e.printStackTrace();}  

        }  

}  

——————————————————————————————————-

Receiver Class:

    import javax.jms.*;  

    import javax.naming.InitialContext;  

          public class MessageReceiver {  

        public static void main(String[] args) {  

            try{  

                                InitialContext ctx=new InitialContext();  

                QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup(“QueueConnectionFactory”);  

                QueueConnection con=f.createQueueConnection();  

                con.start();  

                                QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);  

                                Queue t=(Queue)ctx.lookup(“Queue”);  

                                QueueReceiver receiver=ses.createReceiver(t);                  

                                ThisListener listener=new ThisListener();                        

               receiver.setMessageListener(listener);  

                                  System.out.println(“waiting for messages…”);  

                                while(true){                  

                    Thread.sleep(1200);  

                }  

            }catch(Exception e){System.out.println(e);}  

        }  

          }

    import javax.jms.*;  

    public class ThisListener implements MessageListener {  

              public void onMessage(Message m) {  

            try{  

            TextMessage message=(TextMessage)m;  

                      System.out.println(“Received:”+message.getText());  

            }catch(JMSException e){System.out.println(e);}  

        }  

    }    

——————————————————————————————————

Transaction: A database transaction is a set of actions in a sequence that are treated as a single unit of work. These actions will commit if successfully completed else no effect.

An important part of transaction management is defining the right transaction with a way to start, end and boundaries. It also has to be rolled back if it fails.

For Example:

package com.seven.dao;

import com.seven.model.Student;

public interface StudentDAO {

public void create(Student student);

}

——————————————————————————————————-

package com.sevenmentor.dao;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.sevenmentor.model.Student;

public class StudentDAOImpl implements StudentDAO {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

}

@Override

public void create(Student student) {

String querySt= “insert into St(id, name) values (?,?)”;

String queryAdrs = “insert into Adrs(id, adrs,country) values (?,?,?)”;

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

jdbcTemplate.update(queryStudent, new Object[] { student.getId(),

student.getName() });

System.out.println(“Inserted into Student “);

jdbcTemplate.update(queryAddress, new Object[] { student.getId(),

student.getAdrs().getAdrs(),

student.getAddress().getCountry() });

System.out.println(“Inserted into Address “);

}

}

——————————————————————————————————-

AOP: Aspect-Oriented Programming breaks down all program logic into distinct different parts called concerns which are basically functions. In AOP, aspects enable the secularization of functions so-called as concerns such as transaction or security that divides multiple types and objects. AOP provides a way to dynamically add concern before, after or around the actual programmatic logic using simple feasible configurations. It makes easy to maintain and reuse code in the present and future use. Java Classes In Pune can add concerns without compiling concerns and can manage from the configuration file.

Spring: Spring is one of the most popular java frameworks for Java EE application development used by professionals. It is an open-source Java framework available on

https://repo.spring.io web portal. Spring framework promotes POJO i.e. Plain Old Java Object-based programming model and practices which makes it more user and maintenance-friendly application development.

Spring can do easy Integration with existing java frameworks which makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz, and JDK timer, etc. Testing an application written with Spring is simple because environment-dependent code and its dependencies are moved into this framework. Spring’s web framework also provides well designed and defined MVC framework from web applications to provide alternatives for existing old frameworks such as Struts, Play, etc. Spring provides a convenient to handle checked exceptions like Hibernate and JDBC into unchecked exceptions. Lightweight Inversion of Control containers is lightweight compared to J2EE EJB components.

Author:

Mr. Sachin Patil | Sr. Technical Trainer
SevenMentor Pvt. Ltd.

 

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*