JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

EclipseLink / JPA Annotations – @AttributeOverride And @AssociationOverride

March 2, 2014 by Amr Mohammed Leave a Comment

At this tutorial we’ll introduce using of @AttributeOverride and @AssocationOverride that mentioned intentionally at the @MappedSuperclass tutorial. As you’ve remembered at @MappedSuperclass annotation tutorial, we’ve mentioned at the Database Design section the possibility of using @AttributeOverride and @AssociationOverride to override the attributes and associations that inherited from the mapped superclass. An entity can inherit a persistent entity state and mapping information using different annotations, one of them was using of @MappedSuperclass, but even if you were achieving such that inheritance using @Inheritance or @MappedSuperclass annotations or by using an  abstract entity, you have sometimes to override a superclass’s attribute(s) or association(s) to be compliant the sub classes mapping. That’s what you are going to do; override the mapping information that inherited from the inheritance hierarchy.

Anatomy of @AttributeOverride Annotation

The @AttributeOverride annotation is used to override the mapping of property or field or Id property or field.

  • Target: Type, Method, Field
  • Uses: @AttributeOverride
  • Arguments: The @AttributeOverride annotation takes multiple arguments when it used and these are:
  1. name (Required): This argument specify the name of the property whose mapping is being overridden if property-based access is being used, or the name of the field if field-based access is used.
  2. column (Required): This argument specify the column that is being mapped to persistent attribute. The mapping type will remain the same as is defined in the embeddable class or mapped superclass.

Anatomy of @AssociationOverride Annotation

The @AssociationOverride annotation is used to override a many-to-one or one-to-one mapping of property or field for an entity relationship.

  • Target: Type, Method, Field
  • Uses: @AssociationOverride
  • Arguments: The @AssociationOverride annotation takes multiple arguments when it used and these are:
  1. name (Required): This argument specify the name of the relationship property whose mapping is being overridden if property-based access is being used, or the name of the relationship field if field-based access is used.
  2. joinColumns (Required): This argument specify the join column that is being mapped to the persistent attribute. The mapping type will remain the same as is defined in the mapped superclass.

Classes Design

Let’s see the design of classes that’s being used for defining a proper use of @AttributeOverride and @AssociationOverride annotations. See Figure 1.1.

ClassesDesign

Figure 1.1

Pay attention at the following notes:

  • The License entity does define a licenseId and employee as protected attributes.
  • The licenseId defines an attribute.
  • The employee defins as association.
  • DriverLicense entity defined as a sub-class of the License.
  • ICDLComputerLicense entity defined as a sub-class of the license.

Database Design

In the database design we’ve used two tables (cause the mapped superclass doesn’t refer any table) one for the DriverLicense entity and the second one for ICDComputerLicense. See Figure 1.2.

DriverLicenseTable

icdlLicenseTable

Figure 1.2

Pay attention at the following points:

  • The driverlicense table defines two major attributes, one for licenseId and the second one for association with the employee.
  • The icdlcomputerlicense defins two major attributes, one for licenseId called (icdlLicenseId) and the second for association with the employee called (icdlEmployeeId).
  • The columns in both tables are named differently cause such that case could lead us to use @AttributeOverride and @AssociationOverride.
  • These tables are defined a foreign key for employee association.

Persistence Confication

persistence.xml

[code lang=”java”]
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EclipseLink-JPA-Installation" transaction-type="RESOURCE_LOCAL">
<!– Entities Created Before –>
<class>net.javabeat.eclipselink.data.Employee</class>
<class>net.javabeat.eclipselink.data.Developer</class>
<class>net.javabeat.eclipselink.data.Address</class>
<class>net.javabeat.eclipselink.data.Phone</class>
<class>net.javabeat.eclipselink.data.Project</class>
<class>net.javabeat.eclipselink.data.GlobalProject</class>
<class>net.javabeat.eclipselink.data.LocalProject</class>
<class>net.javabeat.eclipselink.data.License</class>
<class>net.javabeat.eclipselink.data.DriverLicense</class>
<!– New Entity Added –>
<class>net.javabeat.eclipselink.data.ICDLComputerLicense</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
[/code]

Anatomy of Mapped Superclass

License.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import javax.persistence.CascadeType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class License {

@Id
protected int licenseId;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "employeeId")
private Employee employee;

public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public int getLicenseId() {
return licenseId;
}

public void setLicenseId(int licenseId) {
this.licenseId = licenseId;
}
}
[/code]

The license mapped superclass will be used for sharing an persistent entity states (licenseId and employee) and mapping infotrmation for those attributes and associations that could be inherited from it. Let’s take a look at these entities that doing that inheritance.

Anatomy of DriverLicense And ICDLComputerLicense Entities Before Overriding

DriverLicense.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="driverlicenses")
public class DriverLicense extends License{

private String driverLicenseName;
@Temporal(TemporalType.DATE)
private Date driverLicenseExpiryDate;
@Temporal(TemporalType.DATE)
private Date driverLicenseIssueDate;

public String getDriverLicenseName() {
return driverLicenseName;
}
public void setDriverLicenseName(String driverLicenseName) {
this.driverLicenseName = driverLicenseName;
}
public Date getDriverLicenseExpiryDate() {
return driverLicenseExpiryDate;
}
public void setDriverLicenseExpiryDate(Date driverLicenseExpiryDate) {
this.driverLicenseExpiryDate = driverLicenseExpiryDate;
}
public Date getDriverLicenseIssueDate() {
return driverLicenseIssueDate;
}
public void setDriverLicenseIssueDate(Date driverLicenseIssueDate) {
this.driverLicenseIssueDate = driverLicenseIssueDate;
}
}
[/code]

ICDLComputerLicense.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="icdlcomputerlicense")
public class ICDLComputerLicense extends License{
private String icdlLicenseDegree;

public String getIcdlLicenseDegree() {
return icdlLicenseDegree;
}

public void setIcdlLicenseDegree(String icdlLicenseDegree) {
this.icdlLicenseDegree = icdlLicenseDegree;
}

}
[/code]

The following points you should take care of:

  • The DriverLicense inherit the License mapped superclass, so it should define a table for it.
  • The table that the DriverLicense mapped into called (driverlicenses).
  • The driverlicenses table defines a columns that identical to these attributes defined in the License mapped superclass.
  • No need for overriding any persistent states or association in the DriverLicense entity, cause the mapping information that provided by the mapped superclass License does correspond those columns that’s provided by the driverlicenses table.
  • The ICDLComputerLicense inherit the License mapped superclass, so it should define a table for it.
  • The table that the ICDLComputerLicense mapped into called (icdlcomputerlicense).
  • The icdlcomputerlicense table defines a columns that vary differ from that attributes defined in the License mapped superclass.
  • The ICDLComputerLicense entity will not persisted anymore.

Executable Sample for Creating DriverLicense Entity

JPAImpl.java

[code lang=”java”]
package net.javabeat.eclipselink;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.eclipselink.data.Address;
import net.javabeat.eclipselink.data.Developer;
import net.javabeat.eclipselink.data.DriverLicense;
import net.javabeat.eclipselink.data.Employee;
import net.javabeat.eclipselink.data.GlobalProject;
import net.javabeat.eclipselink.data.ICDLComputerLicense;
import net.javabeat.eclipselink.data.LocalProject;
import net.javabeat.eclipselink.data.Phone;
import net.javabeat.eclipselink.data.Project;

public class JPAImpl {
static EntityManagerFactory factory = null;
static EntityManager em = null;
static {
factory = Persistence.createEntityManagerFactory("EclipseLink-JPA-Installation");
em = factory.createEntityManager();
}
public static void main(String [] args){
// Begin a Transaction
em.getTransaction().begin();
// Create Employee
createEmployee();
// Commit
em.getTransaction().commit();

// Begin another Transaction
em.getTransaction().begin();
// Find the Employee
Employee employee = em.find(Employee.class, 2);
// Create a Driver License
createDriverLicense(employee);
// Create an ICDLComputerLicense
createICDLComputerLicense(employee);
// Commit
em.getTransaction().commit();

}

public static void createICDLComputerLicense(Employee employee){
ICDLComputerLicense license = new ICDLComputerLicense();
license.setEmployee(employee);
license.setLicenseId(2);
license.setIcdlLicenseDegree("A");
em.persist(license);
}

public static void createDriverLicense(Employee employee){
DriverLicense license = new DriverLicense(); // Create a driver license
license.setLicenseId(1);// Set license id
license.setDriverLicenseName("All Vehicles License"); // Set License Name
license.setDriverLicenseIssueDate(new Date()); // Anonymous date
license.setDriverLicenseExpiryDate(new Date()); // Anonymous date
license.setEmployee(employee);
em.persist(license);
}

public static void createEmployee(){
// Create an address entity
Address address = new Address();
address.setAddressId(2);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Employee employee = new Employee();
employee.setEmployeeId(2);
employee.setEmployeeName("John Smith");
// Associate the address with the employee
employee.setAddress(address);
// Create a Phone entity
Phone firstPhone = new Phone();
firstPhone.setPhoneId(3);
firstPhone.setPhoneNumber("+221 4050 615");
firstPhone.setEmployee(employee);
// Create a new phone entity
Phone secondPhone = new Phone();
secondPhone.setPhoneId(4);
secondPhone.setPhoneNumber("+221 4050 619");
// Use the old employee entity
secondPhone.setEmployee(employee);
// Create a list of phone
List<Phone> phones = new ArrayList<Phone>();
phones.add(firstPhone);
phones.add(secondPhone);

// Create a Project entity
Project project = new Project();
project.setProjectId(2);
project.setProjectName("Nasa Project");

// Create a list of projects
List<Project> projects = new ArrayList<Project>();

// add the project into the list
projects.add(project);

// Set the project into employee
employee.setProjects(projects);
// Set the phones into your employee
employee.setPhones(phones);

// Persist the employee

em.persist(employee);
}

}

[/code]

If we’ve used the same code that provided previously for creating an ICDLComputerLicense without any modifications on the mapping information, we are about getting such that exception:

[code lang=”java”]
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column ‘LICENSEID’ in ‘field list’
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:890)
… 32 more

[/code]

The exception says licenseId isn’t defined, that’s because the licenseId attribute that defined in the mapped superclass doesn’t mapped properly in the sub-class.

ICDLComputerLicense Entity Does Override the Mapped Superclass mapping information

Having ICDLComputerLicense entity full functional requires to override both of inherited attribute and association. The provided ICDLComputerLicense update code shows you the difference required.

ICDLComputerLicense.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import javax.persistence.AssociationOverride;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

@Entity
@Table(name="icdlcomputerlicense")
@AttributeOverride(name="licenseId",column=@Column(name="icdlLicenseId"))
@AssociationOverride(name="employee",joinColumns={@JoinColumn(name="icdlEmployeeId")})
public class ICDLComputerLicense extends License{
private String icdlLicenseDegree;

public String getIcdlLicenseDegree() {
return icdlLicenseDegree;
}

public void setIcdlLicenseDegree(String icdlLicenseDegree) {
this.icdlLicenseDegree = icdlLicenseDegree;
}

}
[/code]

ICDLComputerLicense Row Instance Has Persisted

By following the previous updated ICDLComputerLicense code, you should be able to persist a new instance of both DriverLicense and ICDLComputerLicense entities. See Figure 1.3 shows you the records that’s inserted into database after the required changes has made.

ICDLComputerLicenseEntity

Figure 1.3

@AttributeOverrides and @AssociationOverrides

If you’ve multiple persistent entity states or associations you would be overridden, let your code use the @AttributeOverrides and @AssociationOverrides, that can provide an override for the mappings of multiple properties or fields and for mapping of multiple one-to-one and many-to-one associations. When it comes to use them, nothing changed except the @AttributeOverrides and @AssociationOverrides accpet multiple @AttributeOverride and @AssociationOverride.

Download Source Code For This Example

Summary

When you have an inheritance hierarchy, it is possible to have a mapping information provided in the root entity or mapped super class differs from the remaining mapping that possibly occurred at the sub-classes. The JPA implementation take care of such that cases, so an important provided annotations could be used for overriding the mapping that already established. @AttributeOverride and @AssociationOverride override the mapping information for attribute (persistent entity states) and association respectively. This tutorial should clarify using of such those annotations.

Filed Under: Java EE Tagged With: EclipseLink, JPA

EclipseLink / JPA Annotations – @MappedSuperclass

March 2, 2014 by Amr Mohammed Leave a Comment

This tutorial will explain the using of @MappedSuperclass, that could be considered as an alternative choice for sharing a persistent entity state and mapping information. An entity may inherit from a super class that provides a persistent entity state and mapping information as we’ve seen previously in the @Inheritance tutorials. Unlike using of @Inheritance, the @MappedSuperclass doesn’t involve in any persistent activity and it doesn’t involve in any operations that managed by the EntityManager. The main purpose of using a @MappedSuperclass is to define a common states and mapping information that could be shared by multiple entity classes.

A @MappedSuperclass annotated class is not persisted itself, but the sub-classes are persistent. So, this annotation is used for an abstract class or a non-persistent class. The equivalent XML element is mapped-superclass in the persistent configuration file.

Some of the characteristics of @MappedSuperclass is:

  • Normally class is abstract, but it never be a persistence instance
  • Mapped superclasses can not define a table, but can define mapping for attributes.
  • This annotation doesn’t have any attributes.

Classes Design

Let’s see the classes design that would be formed the field MappedSuperclass annotation could provide a help inside it. See figure 1.1.

MappedSuperclassDesign

Figure 1.1

The License class is an abstract class contains one attribute named licenseId. Set of classes have a chance to inherit from License abstract class, but because of we are not aware of the number of classes that may inherit it we’ve denoted for any future coming classes with (AnyClass extends License).

We are supposed to have a new class called DriverLicense as an extended class and you will see it in the next section.

License.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class License {

@Id protected int licenseId;

public int getLicenseId() {
return licenseId;
}

public void setLicenseId(int licenseId) {
this.licenseId = licenseId;
}
}
[/code]

DriverLicense.java

[code lang=”java”]
package net.javabeat.eclipselink.data;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity // Annotate the DriverLicense as an Entity that must be persisted by the JPA
@Table(name="driverlicenses") // The Table name that the instance of DriverLicense should be persisted there
public class DriverLicense extends License{
// DriverLicense Inherited  protected int
private String driverLicenseName;
@Temporal(TemporalType.DATE) // The temporal is mandatory when we are coming to deal with Date
private Date driverLicenseExpiryDate;
@Temporal(TemporalType.DATE)
private Date driverLicenseIssueDate;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="employeeId")
private Employee employee;

public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getDriverLicenseName() {
return driverLicenseName;
}
public void setDriverLicenseName(String driverLicenseName) {
this.driverLicenseName = driverLicenseName;
}
public Date getDriverLicenseExpiryDate() {
return driverLicenseExpiryDate;
}
public void setDriverLicenseExpiryDate(Date driverLicenseExpiryDate) {
this.driverLicenseExpiryDate = driverLicenseExpiryDate;
}
public Date getDriverLicenseIssueDate() {
return driverLicenseIssueDate;
}
public void setDriverLicenseIssueDate(Date driverLicenseIssueDate) {
this.driverLicenseIssueDate = driverLicenseIssueDate;
}
}
[/code]

Database Design

The License class annotated with MappedSuperclass, so no need for creating any database table for it, meanwhile and at the other side, any entities that inherit from License class and not annotated using MappedSuperclass need a database mapping table. See Figure 1.2 that shows you the final view for the database tables.

MappedSuperclassDatabaseDesign

Figure 1.2

Notes:

  • The License class doesn’t consider as a persisted entity, cause it’s annotated as a MappedSuperclass.
  • The DriverLicense class considered as an entity, cause it’s annotated as @Entity and it’s mapped into DriverLicense table.
  • The DriverLicense inherit a licenseId attribute from the License MappedSuperclass.
  • The DriverLicense can override any inherited attributes or associations using @AttributeOverride and @AssociationOverride.
  • The DriverLicense associate the Employee with an OneToMany unidirectional association.
  • The DriverLicense table should hold all attributes that are defined by the entity and its MappedSuperclass (licenseId).

Persistence Configuration

The persistence.xml should mention the mapped sueprclass and its sub classes. If you’ve omit the License mapped superclass you are almost getting a compiler error tells you (The License is managed but is not listed in the persistence.xml file). Even if the License will not be part of any EntityManager’s operation, but it should be declared there for making the mapping sharing possible.

[code lang=”xml”]

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EclipseLink-JPA-Installation" transaction-type="RESOURCE_LOCAL">
<!– The entities mentioned here covers previous examples –>
<class>net.javabeat.eclipselink.data.Employee</class>
<class>net.javabeat.eclipselink.data.Developer</class>
<class>net.javabeat.eclipselink.data.Address</class>
<class>net.javabeat.eclipselink.data.Phone</class>
<class>net.javabeat.eclipselink.data.Project</class>
<class>net.javabeat.eclipselink.data.GlobalProject</class>
<class>net.javabeat.eclipselink.data.LocalProject</class>
<!– License & DriverLicense are required classes for this example –>
<class>net.javabeat.eclipselink.data.License</class>
<class>net.javabeat.eclipselink.data.DriverLicense</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/JavaBeat"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>

[/code]

Executable Application

Look at the Java code that runs a JPA persistence for persisting a DriverLicense associated with an Employee.

[code lang=”java”]
package net.javabeat.eclipselink;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import net.javabeat.eclipselink.data.Address;
import net.javabeat.eclipselink.data.Developer;
import net.javabeat.eclipselink.data.DriverLicense;
import net.javabeat.eclipselink.data.Employee;
import net.javabeat.eclipselink.data.GlobalProject;
import net.javabeat.eclipselink.data.LocalProject;
import net.javabeat.eclipselink.data.Phone;
import net.javabeat.eclipselink.data.Project;

public class JPAImpl {
static EntityManagerFactory factory = null;
static EntityManager em = null;
static {
factory = Persistence.createEntityManagerFactory("EclipseLink-JPA-Installation");
em = factory.createEntityManager();
}
public static void main(String [] args){
// Begin a Transaction
em.getTransaction().begin();
// Create Employee
createEmployee();
// Commit
em.getTransaction().commit();

// Begin another Transaction
em.getTransaction().begin();
// Find the Employee
Employee employee = em.find(Employee.class, 2);
// Create a Driver License
createDriverLicense(employee);
// Commit
em.getTransaction().commit();

}

public static void createDriverLicense(Employee employee){
DriverLicense license = new DriverLicense(); // Create a driver license
license.setLicenseId(1);// Set license id
license.setDriverLicenseName("All Vehicles License"); // Set License Name
license.setDriverLicenseIssueDate(new Date()); // Anonymous date
license.setDriverLicenseExpiryDate(new Date()); // Anonymous date
license.setEmployee(employee);
em.persist(license);
}

public static void createEmployee(){
// Create an address entity
Address address = new Address();
address.setAddressId(2);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Employee employee = new Employee();
employee.setEmployeeId(2);
employee.setEmployeeName("John Smith");
// Associate the address with the employee
employee.setAddress(address);
// Create a Phone entity
Phone firstPhone = new Phone();
firstPhone.setPhoneId(3);
firstPhone.setPhoneNumber("+221 4050 615");
firstPhone.setEmployee(employee);
// Create a new phone entity
Phone secondPhone = new Phone();
secondPhone.setPhoneId(4);
secondPhone.setPhoneNumber("+221 4050 619");
// Use the old employee entity
secondPhone.setEmployee(employee);
// Create a list of phone
List<Phone> phones = new ArrayList<Phone>();
phones.add(firstPhone);
phones.add(secondPhone);

// Create a Project entity
Project project = new Project();
project.setProjectId(2);
project.setProjectName("Nasa Project");

// Create a list of projects
List<Project> projects = new ArrayList<Project>();

// add the project into the list
projects.add(project);

// Set the project into employee
employee.setProjects(projects);
// Set the phones into your employee
employee.setPhones(phones);

// Persist the employee

em.persist(employee);
}
}
[/code]

Summary

This tutorial introduced a new annotation for sharing a mapping information rather using @Inheritance. @MappedSuperclass used to annotate a class whose instance won’t be persisted or participate in any persisting operation, while its sub classes will do. In the previous examples we’ve seen a License class that annotated with an @MappedSuperclass, even if it has no abstract non-access modifier, it’s will not considered in a any future persisting operation. However, all sub classes that inherit from the License and doesn’t marked as @MappedSuperclass will participate in the persisting operations such DriverLicense. Remember that – The main goal of @MappedSuperclass is to share the mapping information with the sub classes.

Filed Under: Java EE Tagged With: Annotation, EclipseLink, JPA

EclipseLink / JPA Annotations – @Inheritance With Table Per Concrete Strategy

March 1, 2014 by Amr Mohammed Leave a Comment

The inheritance is one of the most scenarios that can be encountered once we’ve been coming into business field. Inside the Java Persistence API (JPA) The entities support inheritance, polymorphic, polymorphic associations, and polymorphic queries. Both abstract and concrete classes can be entities, and both of them can be annotated with the @Entity annotation, mapped as entities and queried for as entities.

Entities can extend non-entity classes and non-entity classes can extend entity classes, so you will find samples for entities classes inherit from a non-entity classes and non-classes entities inherit from entities classes. The purpose of this tutorial is to cover the inheritance in an entity class hierarchy; which means that the super class and its sub classes will be marked as entities.

The Mapping of class hierarchies has different implementation techniques, that’s depends on the Java Persistence API (JPA) vendor. It is important to know that this tutorial consider the EclipseLink – JPA as a JPA provider, so be sure that you are willing enough to use the EclipseLink.(See EclipseLink Maven Installation and EclipseLink Installation).

To implement an inheritance you’ve different implementations that might be used:

Single Table Inheritance Strategy:

In the single table inheritance, the entire hierarchy is represented by a single table, in that the entity of super class defines set of mapped states and the entity of subclass inherits most of its mapped states from its super class entity.The discriminator column (TYPE) is added to the table to distinguish between the stored instances. That’s column will determine what class in the hierarchy the stored object belongs to. Also, additional columns will be added into that table for those newly defined attributes in the sub classes entities. 

Joined Table Inheritance Strategy:

In the joined table inheritance, each class shares data from the root table. In addition, each subclass defines its own table that adds its extended state. Where the shared data is stored in a single table while the newly defined fields are stored in separate table.

Table per Concrete Strategy:

This strategy is an optional, based on the specification “Support for the table per concrete class inheritance mapping strategy is optional”. In table per class inheritance a table is defined for each concrete class in the inheritance hierarchy to store all the attributes of that class and all of its super classes.

At this tutorial, we will cover the Table Per Concrete Strategy for achieving the inheritance mapping, the next coming tutorial shall cover other strategies.

Anatomy of Inheritance Hierarchy (Classes Design)

Let’s assume an inheritance hierarchy, in that Project entity represents the root of it and set of entities inherit the Project like GlobalProject and LocalProject entities.

Let’s see a class design for the suggested inheritance relationship at the Figure 1.1:

JoinEntitiesUMLDesign

Figure 1.1

Based on the design of classes that shown in the Figure 1.1, you’ve seen a different inheritance relationships achieved between both of Employee and Developer from a side and Project, GlobalProject and LocalProject from a different side.

This time we’re using the Table Per Concrete Strategy rather using of Joined Strategy as you’ve seen before in the Joined Inheritance tutorial.

Anatomy of Database Design

Table per class inheritance allows inheritance to be used in the object model, when it doesn’t exist at the data model. In table per class inheritance, a table is defined for each concrete class in the hierarchy to store all attributes of that class and all of its super classes. We’ve changed the design of the Project entity and its sub classes for enabling the Table Per Concrete philosophy or strategy, so see the Figures 1.2,1.3 and 1.4 that shows you the final form of suggested tables.

TablePerConcreteProjectTable

Figure 1.2

TablePerConcreteGlobalProjectTableFigure 1.3

TablePerConcreteLocalProjectTable

Figure 1.4

  • Each entity is mapped to a separate table.
  • All properties of the entity, including inherited properties are mapped to columns of the table for the entity.

How Should The Project, GlobalProject and LocalProject Looks Like?

The following snippet of code must shows you a proper clarification for the final form of the Project, GlobalProject and LocalProject entities respectively.

Project.java

[code lang=”java”]

// The final form of Project entity that required for applying the Table Per Concrete

package net.javabeat.eclipselink.data;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToMany;

@Entity(name="Project")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Project {
@Id
private int projectId;

private String projectName;

@ManyToMany(mappedBy="projects",cascade=CascadeType.ALL)
private List<Employee> employees;

public int getProjectId() {
return projectId;
}

public void setProjectId(int projectId) {
this.projectId = projectId;
}

public String getProjectName() {
return projectName;
}

public void setProjectName(String projectName) {
this.projectName = projectName;
}

public List<Employee> getEmployees() {
return employees;
}

public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}

[/code]

GlobalProject.java

[code lang=”java”]

// The final form of GlobalProject entity that required for applying the Table Per Concrete

package net.javabeat.eclipselink.data;

import java.math.BigDecimal;

import javax.persistence.Entity;

@Entity
public class GlobalProject extends Project {
private String projectCountry;
private BigDecimal projectBudget;
public String getProjectCountry() {
return projectCountry;
}
public void setProjectCountry(String projectCountry) {
this.projectCountry = projectCountry;
}
public BigDecimal getProjectBudget() {
return projectBudget;
}
public void setProjectBudget(BigDecimal projectBudget) {
this.projectBudget = projectBudget;
}
}

[/code]

LocalProject.java

[code lang=”java”]

// The final form of LocalProject entity that required for applying the Table Per Concrete

package net.javabeat.eclipselink.data;

import java.math.BigDecimal;

import javax.persistence.Entity;

@Entity
public class LocalProject extends Project {
private BigDecimal projectBudget;

public BigDecimal getProjectBudget() {
return projectBudget;
}

public void setProjectBudget(BigDecimal projectBudget) {
this.projectBudget = projectBudget;
}

}

[/code]

  • The Project class represents the root of the inheritance tree.
  • The Project class should contains the @Inheritance annotation.
  • Unlike the Single Table Inheritance and the Join Inheritance strategies, the Table Per Concrete uses the strategy of TABLE_PER_CLASS inside the @Inheritance annotation.
  • There is no @DiscriminatorColumn annotation used. Neither the root of the inheritance hierarchy nor the sub classes does provide such that annotation.
  • There is no @DiscriminatorValue annotation used. Neither the root of the inheritance hierarchy nor the sub classes does provide such that annotation.
  • If you’ve remembered that ManyToMany relationship between Employee and Project that discussed previously, you are almost remembering the JoinTable that already used for achieving such that relation. Now for a proper use of the Table Per Concrete Strategy, you have to remove the constraint that had been used for referencing the ProjectId column that located at the Project Table from the Employee_Project JoinTable. If you didn’t remove that constraint, you are about getting an exception tells you that the records of Project sub classes cannot be inserted into your database. 

Persistence Configuration Required

We need no any change that could happen at the Persistence Configuration (persistence.xml). So you could use the previous one that’s used in the Join Inheritance.

Executable Application

Use the same executable application mentioned at Join Inheritance for achieving the persistence operation. it should work properly, cause nothing changed at the executable class.

Database Persisted Records

If you’ve noticed the persisted records using Single Table Strategy, you can notice that by every persisted record at the database, you have one record and only one. But when you’ve used the Join Inheritance Strategy, you can notice that by every persisted record at the database, we have one record at the Root of the hierarchy (Super Class) and another record represents the entity itself (Subclass). Now look at the Figures 1.5, 1.6 and 1.7 that show you the persisted records when we are considering the Table Per Concrete.

TablePerConcreteProjectRecord

Figure 1.5

TablePerConcreteGlobalProjectRecord

Figure 1.6

TablePerConcreteLocalProjectRecord

Figure 1.7

Summary

This tutorial covers the @Inheritance annotation and its used for achieving an inheritance relationship. Already we’ve established a Project entity and both of GlobalProject and LocalProject inherit it. When you are coming into inheritance, you have multiple choices to implement it. One of the major strategies that could be used is a Table Per Concrete Strategy which in all classes in the hierarchy persisted in their own tables. The main difference between the Joined Strategy & Table Per Concrete is the Table per concrete doesn’t consider any previous records that could be inserted into the Super class Table, while the Join Inheritance consider it.

Filed Under: Java EE Tagged With: EclipseLink, JPA

JSTL Function fn:substringBefore()

March 1, 2014 by Krishna Srinivasan Leave a Comment

The <fn: substringBefore> is function of JSTL which is used to extract the part of the string before the specified substring.

Syntax Of <fn: substringBefore> Tag

[code lang=”html”]
String fn: substringBefore(string, substring)
[/code]

Example

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fn:substringBefore()</title>
</head>
<body>

<c:set var="str" value="hello world!!!! Welcome to JavaBeat"></c:set>
<p>Characters after assigning substring:</p>
${fn:substringBefore(str,’W’)}

</body>
</html>
[/code]

Details of the Code

  • < c:set var=”str” value=”hello world!!!! Welcome to JavaBeat”> tag is used to set variable name and to display result in the output using value attribute.
  • ${fn: substringBefore(str,’W’)} contains two parameters. First parameter is target string from which we need to derive substring and second parameter is substring which breaks the string and returns the substring before it.

Steps for Execution

  • Save the file as substringBeforeExample.jsp in eclipse IDE.
  • Now select the jsp file, right click on mouse and select Run as -> Run on Server.

Output

After successful execution of the program we will get the following result:
substringBefore

Previous Tutorial :  JSTL Function fn:substringAfter() :: Next Tutorial : JSTL Function fn:contains()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Function fn:substringAfter()

March 1, 2014 by Krishna Srinivasan Leave a Comment

The <fn: substringAfter> is function of JSTL which is used to extract the part of the string after the specified substring.

Syntax Of <fn: substringAfter> Tag

[code lang=”html”]
String fn: substringAfter (string, substring)
[/code]

Example

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL fn:substringAfter()</title>
</head>
<body>

<c:set var="str" value="hello world..Welcome to JavaBeat"></c:set>
<p>Characters after assigning substring:</p>
${fn:substringAfter(str,"d..")}

</body>
</html>
[/code]

Details of the Code

  • < c:set var=”str” value=”hello world..Welcome to JavaBeat”> tag is used to set variable name and to display result in the output using value attribute.
  • ${fn:substringAfter(str,”d..”)} contains two parameters. First parameter is target string from which we need to derive substring and second parameter is substring which returns the substring after breaking the string.

Steps for Execution

  • Save the file as substringAfterExample.jsp in eclipse IDE.
  • Now select the jsp file, right click on mouse and select Run as -> Run on Server.

Output

After successful execution of the program we will get the following result:
substringAfter

 

Previous Tutorial :  JSTL Functions :: Next Tutorial : JSTL Function fn:substringBefore()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Functions

March 1, 2014 by Krishna Srinivasan Leave a Comment

JSTL function tag library contains set of string manipulation functions that can be used with the JSP Expression Language.

Syntax of JSTL Functions Tag Library

[code lang=”html”]
<%@ taglib uri=”http://java.sun.com/jsp/jstl/functions “prefix=”fn” %>
[/code]

JSTL Function Tags

  • <fn:contains()>: It is used to check whether string contains specified sub string or not.
  • <fn:containsIgnoreCase()>:It returns true if string contains specified substring ,ignores case and also returns true or false based on evaluation condition.
  • <fn:endsWith()>: It returns true if string ends with specified suffix.
  • <fn:escapeXml()>: It is used to escape XML markup characters. It takes only one parameter of type string.
  • <fn:indexOf()>: It returns index for the first occurrence of the specified sub string.
  • <fn:join()>: It is used to join all the elements contained in an array with the specified string.
  • <fn:length()>: It returns number of elements from an array or collection, characters from a string.
  • <fn:replace()> :It is used to replace a string with another string.
  • <fn:split()>: It returns array of string by separating the string with separator.
  • <fn:startsWith()>:It returns true if string starts with prefix.
  • <fn:endsWith()>: It returns true if string ends with prefix.
  • <fn:substring()>: It returns substring of string with begin index till the end index.
  • <fn:substringAfter()>:It returns subset of string after the substring.
  • <fn:substring()>: It returns subset of string before the specific substring.
  • <fn:toLowerCase()>:It returns all the characters of string to lower case.
  • <fn:toUpperCase()>: It returns all the characters of string to upper case.
  • <fn:trim()>: It is used to remove white spaces from the start and end of the string.

Previous Tutorial :  JSTL SQL sql:setDataSource Tag :: Next Tutorial : JSTL Function fn:substringAfter()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL SQL sql:setDataSource Tag

March 1, 2014 by Krishna Srinivasan Leave a Comment

The <sql:setDataSource> tag is used to create data source variable directly from JSP and it can be stored in a scoped variable with the help of scoped attribute. It can be used as input to other database actions.

Attributes of <sql:setDataSource> Tag

  • datasource: It specify data source name or java.sql.DataSource object.
  • driver: It specifies JDBC driver class name used to create a connection.
  • url: It specifies JDBC URL associated with database.
  • user: It specifies database username.
  • password: It specifies database password.
  • var: It specifies name of the variable which is used to store created data source object.
  • scope: It specifies scope of the variable like page or session or request or application.

Example

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SQL:setDataSource Tag</title>
</head>
<body>
<!– Connect to the database –>
<sql: setDataSource var="ds" driver="com.mysql.jdbc.Driver"
url="jdbc: mysql: //localhost/test" user="root" password="" />

The data is below:
<br>

<!– Execute the SQL –>
<sql:query dataSource="${ds}"
sql="select * from employees where id >=100" var="result" />

<!– How may rows are returned –>
<c:out value="The rows returned by SQL : ${result.getRowCount()}" />

</body>
</html>
[/code]

Details of the Code

    • <sql: setDataSource var=”ds” driver=”com.mysql.jdbc.Driver” url=”jdbc: mysql: //localhost/test” user=”root” password=”” /> tag is used to connect to the data base and specify variable name for data source and driver name, url , user name and password of the database.
    • <sql:query dataSource=”${ds}” sql=”select * from employees where id >=100″ var=”result” /> tag is used to specify SQL statement to be run on the database and stores result of SQL statement in the variable.
    • <c:out value=”The rows returned by SQL : ${result.getRowCount()}” /> tag is used to display the result of SQL statement in the output using getRowCount() method which indiacates number of rows returned by the SQL statement.

Steps for Execution

  • Save the file as setDataSourceExample.jsp in eclipse IDE.
  • Now select the jsp file, right click on mouse and select Run as -> Run on Server.

Output

After successful execution of the program we will get the following result:
setDataSource

Previous Tutorial : JSTL SQL sql:transaction  Tag :: Next Tutorial : JSTL Functions

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL XML x:parse Tag

February 27, 2014 by Krishna Srinivasan Leave a Comment

The <x: parse> tag is used to parse the xml content and the result will be stored in specified variable.

Syntax Of <x: parse> Tag

[code lang=”html”]
<x: parse attributes> body content </x: parse>
[/code]

Attributes Of <x: parse> Tag

Attributes Description
doc Specifies that source XML document to be parsed.
systemId Specifies the system identifier in xml document for parsing.
filter Filter object is been used in xml document to filter the document.
var It specifies the variable name which stores parse xml document.
scope The Scope into which the variable attribute has to be set.
varDom Specifies the variable name of the parsed xml document has to be set.
scopeDom Specifies the scope of varDom attribute has to be set.

Example

Listing 1: xParse.xml file

[code lang=”html”]
<fruits>
<fruit>
<name>Grapes</name>
<price>40/kg</price>
</fruit>

<fruit>
<name>Orange</name>
<price>30/kg</price>
</fruit>

<fruit>
<name>Apple</name>
<price>90/kg</price>
</fruit>

</fruits>
[/code]

Listing 2: example.jsp file

[code lang=”html”]
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title> x:parse Tags</title>
</head>
<body>

<h3>Fruits Information:</h3>

<c:import var="fruitinfo" url="xParse.xml"/>

<x:parse xml="${fruitinfo}" var="output"/>

<b>Name of the Fruit is</b>:

<x:out select="$output/fruits/fruit[1]/name" /><br>

<b>The price of the Apple</b>:

<x:out select="$output/fruits/fruit[3]/price" />

</body>
</html>
[/code]

Details of the Code

  • <c:import var=”fruitinfo” url=”xParse.xml”/> tag is used to include the content of another resource in the current JSP.
  • <x:parse xml=”${fruitinfo}” var=”output”/> tag is used to parse the xml content and the result is been stored in specified variable.
  • <x:out select=”$output/fruits/fruit[1]/name” /> tag is used to display the particular fruit name in the output.
  • <x:out select=”$output/fruits/fruit[3]/price” /> tag is used to display the price of the particular fruit which we want.

Steps for Execution

Before executing the xml programs we should add jar files in eclipse namely:
xalan-2.7.0.jar

<

  • Save this file as example.jsp in your eclipse IDE.
  • Now select this jsp file, right mouse click and select Run as ->Run on server

Output

When the execution process is completed successfully we will get the following output :

x parse tag output

Previous Tutorial :  JSTL XML x:set Tag :: Next Tutorial : JSTL XML x:transform Tag

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL XML x:set Tag

February 27, 2014 by Krishna Srinivasan Leave a Comment

The <x: set> tag is used to store the result of xml path expression in scoped variable.

Syntax of <x: set> Tag

[code lang=”html”]
<x: set attributes/>
[/code]

Attributes of <x: set> Tag

Example

[code lang=”html”]
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title>JSTL Tags</title>
</head>
<body>

<h3>Fruits Information:</h3>

<c:set var="fruit">

<fruits>

<fruit>
<name>Grapes</name>
<price>40/kg</price>
</fruit>

<fruit>
<name>Orange</name>
<price>30/kg</price>
</fruit>

<fruit>
<name>Apple</name>
<price>90/kg</price>
</fruit>

</fruits>

</c:set>

<x:parse xml="${fruit}" var="output"/>
<x:set var="fragment" select="$output/fruits/fruit[3]/price"/>

<b>The price of the Apple</b>:
<x:out select="$fragment" />

</body>
</html>
[/code]

Details of the Code

  • <c:set var=”fruit”> tag is used to set the variable name which we want to display in the output.
  • <x:parse xml=”${fruit}” var=”output”/> tag is used to parse the xml content and the result is been stored in specified variable.
  • <x:set var=”fragment” select=”$output/fruits/fruit[3]/price”/> tag is used to store the result in xml path expression using the attribute var and select.
  • <x:out select=”$output/fruits/fruit[3]/price” /> tag is used to display the price of the particular fruit which we want.

Steps for ExecutionBefore executing the xml programs we should add jar files in eclipse namely:
xalan-2.7.0.jar

  • Save this file as example.jsp in your eclipse IDE.
  • Now select this jsp file, right mouse click and select Run as ->Run on server

OutputThe below is screen shot of the output.x set tag output

Attributes Description
select To evaluate the particular object it specifies xml Xpath expression.
var It specifies the variable name which stores parse xml document.
scope The Scope into which the variable attribute has to be set.

 

Previous Tutorial : JSTL XML x:if  Tag :: Next Tutorial : JSTL XML x:parse Tag

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL XML x:forEach Tag

February 27, 2014 by Krishna Srinivasan Leave a Comment

The <x: forEach> tag is used for looping a list of elements in an xml document.

Syntax of <x: forEach> Tag

[code lang=”html”]
<x: forEach attributes> body content </x: forEach>
[/code]

Attributes of <x: forEach> Tag

Example[code lang=”html”]
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title> x:if Tags</title>
</head>
<body>

<h2>Fruits Information:</h2>

<c:set var="fruitss">

<fruits>

<fruit>
<name>Grapes</name>
<price>40</price>
</fruit>

<fruit>
<name>Orange</name>
<price>30</price>
</fruit>

<fruit>
<name>Apple</name>
<price>90</price>
</fruit>

</fruits>

</c:set>

<x:parse xml="${fruitss}" var="output"/>

<table>

<x:forEach select="$output/fruits/fruit/name" var="item" begin="1" end="2">

<tr><td>Fruit Name:</td> <td><x:out select="$item" /></td></tr>

</x:forEach>

</table>

</body>
</html>
[/code]

Details of the Code

  • <c:set var=”fruitss”> tag is used to set the variable name which we want to display in the output.
  • <x:parse xml=”${fruitss}” var=”output”/> tag is used to parse the xml content and the result is been stored in specified variable.
  • <x:forEach select=”$output/fruits/fruit/name” var=”item” begin=”1″ end=”2″> tag is used to looping a list of element by using some attributes.

Steps for ExecutionBefore executing the xml programs we should add jar files in eclipse namely:
xalan-2.7.0.jar

  • Save this file as example.jsp in your eclipse IDE.
  • Now select this jsp file, right mouse click and select Run as ->Run on server

OutputWhen the execution process is completed successfully we will get the following output :
x forEach tag output

Attributes Description
select To evaluate the particular object it specifies xml Xpath expression.
var It specifies the variable name where current item has to be set.
varStatus Specifies the variable name and tells the status of loop
begin Specifies the particular value from where the user want to start in the list.
end Specifies the particular value where the user wants to end the list.
step Specifies the increment of the loop.

Filed Under: Java EE Tagged With: JSTL Tutorials

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • …
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved