EasyMock Simple Example

In this example we will see how to write java test cases using EasyMock. This api provides an easy way to create Mock Objects for interfaces and classes generating them on the fly. See more about EasyMock

Software Used

Java 1.7

EasyMock 3.2

Maven

Eclipse Juno

Create a Maven Project and below dependencies

      <dependency>
	<groupId>org.easymock</groupId>
	<artifactId>easymock</artifactId>
	<version>3.2</version>

Create a Simple Java POJO class (Employee.java)

package com.pretech;
public class Employee {
	private String name;
	private String address;
	private String age;
//Generate getters and setters

Create a class to use Employee object

package com.pretech;
public class EmployeeDetails {
	public Employee createNewEmp(Employee emp) {
		System.out.println("Inside create method" + emp.getName());
		return emp;
	}
		
}

Now we are going to test createNewStudent method using EasyMock

package com.pretech;
import static org.junit.Assert.assertEquals;
import org.easymock.EasyMock;
import org.junit.Test;
public class EmployeeDetailsTest {
	
	@Test
	public void testEmployee(){
		//Creating Employee mock object
		Employee employeeMock = EasyMock.createMock(Employee.class);
		//Setting up mock values in this example we are using getName 2 times so it is added .times(2) otherwise second time getName wont work
		EasyMock.expect(employeeMock.getName()).andReturn("Vinod").times(2);
	       //Activating mock
		EasyMock.replay(employeeMock);
	
		//Testing
		EmployeeDetails empetails=new EmployeeDetails();
		Employee emp=new Employee();
		emp=empetails.createNewEmp(employeeMock);
		System.out.println(emp);
		assertEquals("Vinod",emp.getName());
	}
}

Output

Run program as Junit and see below output

image


Struts 2 HelloWorld Simple Example

In this example we will see how to create a simple helloworld application using Struts 2 framework

Environment Used

Java 1.7

Eclipse Juno

Apache Tomcat 7

Struts 2 Jars

1. Create a dynamic web project in Eclipse

Create a Dynamic web project in Eclipse and configure apache tomcat as Server. Once it is created download Struts 2 jars and place in to WEB-INF/lib folder. Here is the final structure of the project. (Click here to download this example with jars)

image

2. Update Web.xml file

Add Struts servlet details in to 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>Struts2HelloWorldExample</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3. Create an Action class (HelloWorldAction.java)

package com.vinod.test;
import com.opensymphony.xwork2.ActionSupport;
 
public class HelloWorldAction extends ActionSupport {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String execute() {
        setName("Hello "+name+" Welcome to Struts 2");
            return SUCCESS;
    }
}

4. Create a JSP page (index.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:form action="helloaction">
    <s:textfield name="name" label="Enter Your Name" /><br>    
    <s:submit value="Submit" align="center" />
</s:form>
</body>
</html>

5. Create Success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head></head>
<body>
    <h4>
    <s:property value="name" />
    </h4>
 </body>
</html>

6. Create Struts.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml"/>
    <package name="com" extends="struts-default">
        <action name="helloaction" class="com.pretech.HelloWorldAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

7. Deploy application in tomcat server

Run the application and give your name for input

image

image

Download Application

Struts 2 Helloworld Example

Hibernate Native SQL

Hibernate supports native SQL queries as well, in the below code snippet we will see how to use Native SQL in hibernate. Since Hibernate 3.x offers you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Session objects createSQLQuery(“Query”) method is using to get SQLQuery object. We can make use of this either as Scalar query or entity query. 

SQLQuery query = session.createSQLQuery("select * from student")
                .addEntity(Student.class);
        List list = query.list();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Student stud = (Student) it.next();
            System.out.println(stud.getName());
            System.out.println(stud.getStandard());
        }
 
        System.out.println("Executing Select Scalar Query");
 
        SQLQuery query1 = session.createSQLQuery("select name,standard from student");
        query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        List list1 = query1.list();
 
        for (Object object : list1) {
            Map row = (Map) object;
            System.out.println("name: " + row.get("name"));
            System.out.println("standard:" + row.get("standard"));
        }
 

Reference

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

Hibernate Inheritance Table per Concrete class example using Annotations

Hibernate API supports Inheritance mapping in 3 ways

Table per class hierarchy
Table per subclass
Table per concrete class

Table per Concrete class

In this example we will see how to implement one Table per Concrete class , it means each concrete class is mapped as normal persistent class and mapping of the subclass repeats the properties of the parent class.

Let us consider Vehicle as parent class and Bus, Car are the subclasses, as per Table per concrete class three table will create and in the sub class table will get the properties of the super class Vehicle.

[image%255B3%255D.png]

Final table structure (Each sub table will have the properties of parent class e.g.: Vehicle Type)

imageimage

image

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)

image

2. Create Vehicle class (Vehicle.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
@Entity
@Table(name = "VEHICLE")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
 
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)  
    @Column(name = "Vehicle_Id")
    int vehicleId;
 
    @Column(name = "Vehicle_Type")
    String vehicleType;
    public Vehicle(String vehicleType)
    {
        this.vehicleType=vehicleType;
    }
    public int getVehicleId() {
        return vehicleId;
    }
    public void setVehicleId(int vehicleId) {
        this.vehicleId = vehicleId;
    }
    public String getVehicleType() {
        return vehicleType;
    }
    public void setVehicleType(String vehicleType) {
        this.vehicleType = vehicleType;
    }
    public Vehicle() {
    }
 
}

3. Create Bus.java (Sub class)

package com.pretech;
 
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.AttributeOverride;
 
@Entity
@Table(name="BUS")  
@AttributeOverrides({
    @AttributeOverride(name="vehicleId", column=@Column(name="Vehicle_Id")),
    @AttributeOverride(name="vehicleName", column=@Column(name="Vehicle_Name"))
 
})
public class Bus extends Vehicle {
 
    @Column(name = "Bus_Model")
    String busmodel;
    @Column(name="Vehicle_name")
    String vehiclename;
    public Bus() {
    }
    public Bus(String vehicleType,String vehicleName, String busmodel) {
        super(vehicleType);
        this.busmodel = busmodel;
        this.vehiclename = vehicleName;
 
    }
    public String getBusmodel() {
        return busmodel;
    }
    public void setBusmodel(String busmodel) {
        this.busmodel = busmodel;
    }
    public String getVehiclename() {
        return vehiclename;
    }
    public void setVehiclename(String vehiclename) {
        this.vehiclename = vehiclename;
    }
 
}

4. Create Car.java (Sub class)

package com.pretech;
 
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="CAR")  
@AttributeOverrides({
    @AttributeOverride(name="vehicleId", column=@Column(name="Vehicle_Id")),
    @AttributeOverride(name="vehicleName", column=@Column(name="Vehicle_Name"))
 
})
public class Car extends Vehicle {
 
    @Column(name = "Car_Model")
    String carmodel;
    @Column(name="Vehicle_name")
    String vehiclename;
   
    public Car() {
 
    }
 
    public Car(String vehicleType,String vehicleName, String carmodel) {
        super(vehicleType);
        this.carmodel = carmodel;
        this.vehiclename = vehicleName;
 
    }
    public String getCarmodel() {
        return carmodel;
    }
    public void setCarmodel(String carmodel) {
        this.carmodel = carmodel;
    }
    public String getVehiclename() {
        return vehiclename;
    }
    public void setVehiclename(String vehiclename) {
        this.vehiclename = vehiclename;
    }
}

In the above two sub classes we used two additional annotations ie @AttributeOverrides annotation is used to override mappings of multiple properties or fields and  @AttributeOverride annotation is used to override the mapping of property.

5. Create Hibernate config file (hibernate.cfg.xml)

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
  <mapping class="com.pretech.Vehicle"></mapping>  
  <mapping class="com.pretech.Bus"></mapping>  
  <mapping class="com.pretech.Car"></mapping>            
    </session-factory>
</hibernate-configuration>

6. Create Main class

Create a main class to create and save Vehicle objects.

package com.pretech;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class VehicleMain {
 
    private static SessionFactory sessionFactory;
 
    public static void main(String[] args) {
 
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
        Vehicle vehicle = new Vehicle("Four Wheeler");
        Bus bus = new Bus("Four Wheeler","Bus", "Volvo");
        Car car = new Car("Four Wheeler","Car", "Honda");
        session.beginTransaction();
        session.save(vehicle);
        session.save(bus);
        session.save(car);
        session.getTransaction().commit();
        System.out.println("Vehicle objects Saved");
 
        if (session != null)
            session.close();
    }
 
}

Note that these classes are persisted in different tables and parent attributes are repeated in all tables.

Output

Hibernate: insert into VEHICLE (Vehicle_Type, Vehicle_Id) values (?, ?)
Hibernate: insert into BUS (Vehicle_Type, Bus_Model, Vehicle_name, Vehicle_Id) values (?, ?, ?, ?)
Hibernate: insert into CAR (Vehicle_Type, Car_Model, Vehicle_name, Vehicle_Id) values (?, ?, ?, ?)
Vehicle objects Saved

image

image

image 

Download Source code

Hibernate Table per concrete class example

Hibernate Inheritance Table per Sub class example using Annotations

Hibernate API supports Inheritance mapping in 3 ways

Table per class hierarchy
Table per subclass
Table per concrete class

Table per sub class

In this example we will see how to implement one Table per sub class . It means each class persist the data in its own separate table but a foreign key relationship exists between the subclass tables and super class table and common data will store in to the parent class

Let us Consider Vehicle is root class and Bus and Car are sub classes. Vehicle id will be as foreign key in Bus and Car table and common data is stored in VEHICLE table and subclass specific fields are stored in BUS and CAR tables.

image

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)

image

2. Create a Vehicle class

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
 
@Entity
@Table(name = "VEHICLE")
@Inheritance(strategy = InheritanceType.JOINED)
public class Vehicle {
 
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)  
    @Column(name = "Vehicle_Id")
    int VehicleId;
    @Column(name = "Vehicle_Name")
    String VehicleName;
    public Vehicle() {
    }
    public Vehicle(String VehicleName) {
        this.VehicleName = VehicleName;
    }
    public int getVehicleId() {
        return VehicleId;
    }
    public void setVehicleId(int vehicleId) {
        VehicleId = vehicleId;
    }
    public String getVehicleName() {
        return VehicleName;
    }
    public void setVehicleName(String vehicleName) {
        VehicleName = vehicleName;
    }
}

3. Create a sub class (Car.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="CAR")  
public class Car extends Vehicle {
 
    @Column(name = "Car_Model")
    String carmodel;
    public Car() {
 
    }
    public Car(String vehicleName, String carmodel) {
        super(vehicleName);
        this.carmodel = carmodel;
    }
    public String getCarmodel() {
        return carmodel;
    }
    public void setCarmodel(String carmodel) {
        this.carmodel = carmodel;
    }
}

4.Create Bus entity (Bus.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
 
@Entity
@Table(name="BUS")  
public class Bus extends Vehicle {
 
    @Column(name = "Bus_Model")
    String busmodel;
    public Bus() {
 
    }
    public Bus(String vehicleName, String busmodel) {
        super(vehicleName);
        this.busmodel = busmodel;
    }
    public String getBusmodel() {
        return busmodel;
    }
    public void setBusmodel(String busmodel) {
        this.busmodel = busmodel;
    }
}

5.Create Hibernate config file(hibernate.cfg.xml)

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
  <mapping class="com.pretech.Vehicle"></mapping>  
  <mapping class="com.pretech.Bus"></mapping>  
  <mapping class="com.pretech.Car"></mapping>            
    </session-factory>
</hibernate-configuration>

6. Create a main program to Save Vehicles

package com.pretech;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class VehicleMain {
 
    private static SessionFactory sessionFactory;
 
    public static void main(String[] args) {
 
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
 
        Vehicle vehicle = new Vehicle("Four Wheeler");
        Bus bus = new Bus("Bus", "Volvo");
        Car car = new Car("Car", "Honda");
        session.beginTransaction();
        session.save(vehicle);
        session.save(bus);
        session.save(car);
        session.getTransaction().commit();
        System.out.println("Vehicle objects Saved");
 
        if (session != null)
            session.close();
    }
 
}

7. Run it

Once you run the program we will see below output

Hibernate: insert into VEHICLE (Vehicle_Name, Vehicle_Id) values (?, ?)
Hibernate: insert into VEHICLE (Vehicle_Name, Vehicle_Id) values (?, ?)
Hibernate: insert into BUS (Bus_Model, Vehicle_Id) values (?, ?)
Hibernate: insert into VEHICLE (Vehicle_Name, Vehicle_Id) values (?, ?)
Hibernate: insert into CAR (Car_Model, Vehicle_Id) values (?, ?)
Vehicle objects Saved

Database Table output

image

image

image 

Download Source Code

Hibernate Inheritance Table per sub class Example

References

Hibernate Annotations

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts