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

EclipseLink / JPA Annotations – @Embeddable, @Embedded and @EmbeddedId

March 5, 2014 by Amr Mohammed Leave a Comment

We’ve been providing several examples so far, most of the examples are being provided weren’t use complex persistent entity states; we are using a primitive data types such (int, String, BigDecimal, Date and etc ..).

But what’s happened if you we’ve created an entity whose persistent states are other types (classes). No doubt that it should make the developed applications more easier rather enclose the entity states to be only primitive types. Such that situation is happened frequently, so the JPA specifier takes in its consideration in that cases.

This tutorial will cover @Embeddable, @Embedded and @EmbeddedId, in that the @Embeddable annotation is used to specify a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Also, @Embedded is used to specify a persistent field or property of an entity whose value is an instance of an embeddable class. And finally the @EmbeddedId is applied to a persistent field or property of an entity class or mapped superclass to denote the composite primary key that is an embeddable class.

Let’s start discussing the @Embeddable, cause it’s the entry point for understanding the new concept.

@Embeddable

As we’ve mentioned before and from the definition of the @Embeddable, it is used to specify or define a class (Type) whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. So the @Embeddable annotation has never been used with the properties or attributes.

Anatomy of @Embeddable Annoation

The specification of the @Embeddable is:

[code lang=”java”]
@Target({TYPE}) @Retention (Runtime)
public @interface Embeddable {}
[/code]

  • Target: Types
  • Uses: @Embeddable
  • Arguments: No argument provided

Classes Design

If you’ve read through the previous examples that provided before (See EclipseLink – JPA Tutorial), you’ll find an Employee entity, by adding a new property (not an association or relation; just a property) into Employee entity called (employeePeriod) which contains startDate and endDate as a primitive types. See Figure 1.0 that depict what should Employee and EmployeePeriod entities looks like.

JPA Annotation Class Design

Figure 1.0

  • Employee entity does composite an EmployeePeriod type.
  • EmployeePeriod type is used to declare the employeePeriod property within an Employee.

Employee Table

See Figure 1.2 that shows you the impact of adding an EmployeePeriod into Employee Table.

EmployeeTable

Figure 1.2

  • A new EmployeeStartDate and EmployeeEndDate columns are added into Employee Table.
  • The new columns are added into Employee Table, because of the Embeddable class (Type) persistent states are persisted into the owning entity.

EmployeePeriod Class (Type)

As you’ve noted at the classes design, the EmployeePeriod is an attribute defined within an Employee entity, so when Entity Manager comes to persist an Employee, it should take care of EmployeePeriod.

EmployeePeriod.java

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

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Embeddable
public class EmployeePeriod {
@Column(name="EmployeeStartDate")
@Temporal(TemporalType.DATE)
private Date startDate;

@Column(name="EmployeeEndDate")
@Temporal(TemporalType.DATE)
private Date endDate;

public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}

}
[/code]

  • The @Embeddable class (type) isn’t specify a Table, cause the the Embeddable class (type) should depends on the owning entity when it comes to persist.
  • The properties that defined in the EmployeePeriod embeddable class (type) defines their mapping information and the columns that should be referred to using @Column.
  • As defined properties are Date, so it is important to specify the @Temporal annotation.

Employee Entity With @Embedded

Employee.java

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

import java.util.List;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="EmployeeType")
@DiscriminatorValue(value="EMP")
public class Employee {

@Id
private int employeeId;

@Basic(optional=false)
private String employeeName;

@Embedded
private EmployeePeriod employeePeriod;

@OneToMany(mappedBy="employee", cascade=CascadeType.ALL)
private List<Phone> phones;

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(
joinColumns={@JoinColumn(name="employeeId")},
inverseJoinColumns={@JoinColumn(table="project",name="projectId"),@JoinColumn(table="localproject",name="projectId"),@JoinColumn(table="globalproject",name="projectId")}
)
private List<Project> projects;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="AddressId")
private Address address;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public int getEmployeeId() {
return employeeId;
}

public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public List<Phone> getPhones() {
return phones;
}

public void setPhones(List<Phone> phones) {
this.phones = phones;
}

public List<Project> getProjects() {
return projects;
}

public void setProjects(List<Project> projects) {
this.projects = projects;
}

public EmployeePeriod getEmployeePeriod() {
return employeePeriod;
}

public void setEmployeePeriod(EmployeePeriod employeePeriod) {
this.employeePeriod = employeePeriod;
}

}
[/code]

  • The Employee defines a new property named (employeePeriod) that’s embeddable type.
  • The properties of employeePeriod depend on Employee entity for specifying the table that they are going to persist into.
  • The JPA doesn’t know if you were using an Embeddable class (type) or not, except if you were specifying the @Embedded.
  • The Embedded notify the JPA implementation that, it has an Embeddable class (Type), so consider the mapping information in the Embeddable class in the context of the owning (Employee) entity.

Persistence Configuration Changes Required

Nothing needs a change, except the adding of new EmployeePeriod class (type) in the Persistence Context. For the detailed configuration, please read our previous tutorials.

[code lang=”xml”]
<class>net.javabeat.eclipselink.data.EmployeePeriod</class>
[/code]

Executable Application

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.ContractDeveloper;
import net.javabeat.eclipselink.data.Developer;
import net.javabeat.eclipselink.data.DriverLicense;
import net.javabeat.eclipselink.data.Employee;
import net.javabeat.eclipselink.data.EmployeePeriod;
import net.javabeat.eclipselink.data.FreelanceDeveloper;
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();
createEmployee();
// Commit
em.getTransaction().commit();
}

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");

// Create an Employee Period Instance
EmployeePeriod period = new EmployeePeriod();
period.setStartDate(new Date());
period.setEndDate(new Date());

employee.setEmployeePeriod(period);

// 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 list of projects
List<Project> projects = new ArrayList<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 the Embeddable class (Type) is used within an Employee, so no overrides required on the mapping information that provided by the EmployeePeriod properties. But in case you’ve needed to use the EmployeePeriod in an entities rather Employee and these entities reference a different column names, so you should use an @OverrideAttributes annotation.
  • Let’s assume that we’ve considered a columns that differ from the mapping information that’s provided in the EmplyeePeriod Embeddable class (type), in that you have to consider the @OverrideAttributes change the take place inside Employee entity. See the following snippet of code.

[code lang=”java”]
@Embedded
@AttributesOverride({
@AttributeOverride(name="startDate",column=@Column(name="EMP_START")),
@AttributeOverride(name="endDate",column=@Column(name="EMP_END"))
})
private EmployeePeriod employeePeriod; // employeePeriod property
[/code]

@EmbeddedId

  • The EmbeddedId isn’t vary differs as a concept from the previous concepts that discussed before about Embedded and Embeddable, except it is covering a composite primary key point.
  • The EmbeddedId annotation is applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class.
  • Let’s assume that we’ve a new Embeddable class (Type) named (AddressPK), that’s should determine the primary key of the Address entity.(See previous examples that depict the Address entity by referring the eclipselink jpa tutorial).

AddressPK.java

[code lang=”java”]

package net.javabeat.eclipselink.data;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class AddressPK implements Serializable{
@Column(name="AddressCountryId")
private int addressCountryId;
@Column(name="AddressCityId")
private int addressCityId;
@Column(name="AddressId")
private int addressId;
public int getAddressCountryId() {
return addressCountryId;
}
public void setAddressCountryId(int addressCountryId) {
this.addressCountryId = addressCountryId;
}
public int getAddressCityId() {
return addressCityId;
}
public void setAddressCityId(int addressCityId) {
this.addressCityId = addressCityId;
}
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}

public boolean equals(Object obj){
if(obj instanceof AddressPK){
AddressPK addPK = (AddressPK) obj;
if(this.addressId == addPK.getAddressId() &&
this.addressCountryId == addPK.getAddressCountryId() &&
this.addressCityId == addPK.getAddressCityId()){
return true;
}
}
else {
return false;
}
return false;
}

public int hashCode(){
return super.hashCode();
}

}

[/code]

  • The AddressPK Embeddable class (Type) defines three properties and they are addressId, addressCountryId and addressCityId, so the Adress entities should be identified by the group of properties rather one addressId property.
  • When the developer uses the Embeddable class (Type) for primary key, he should override equals and hashCode(). The JPA itself doesn’t accept the Embeddable class if it was used as primary key unless it ensure that the two methods are overridden.
  • The AddressPK should implement the Serializable.
  • By using AddressPK, we have been using a new version of primary key that could depend on to identify the Address entities. But if you’ve reviewed the eclipselink jpa previous examples, you should be realized that the Employee entity related to the Address entity by OneToOne association. Let’s see the required changes that should take place once the primary key of the Address has been changed.

Employee.java

[code lang=”java”]

package net.javabeat.eclipselink.data;

import java.util.List;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="EmployeeType")
@DiscriminatorValue(value="EMP")
public class Employee {

@Id
private int employeeId;

@Basic(optional=false)
private String employeeName;

@Embedded
private EmployeePeriod employeePeriod;

@OneToMany(mappedBy="employee", cascade=CascadeType.ALL)
private List<Phone> phones;

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(
joinColumns={@JoinColumn(name="employeeId")},
inverseJoinColumns={@JoinColumn(table="project",name="projectId"),@JoinColumn(table="localproject",name="projectId"),@JoinColumn(table="globalproject",name="projectId")}
)
private List<Project> projects;

// Updated Mapping information that took a consideration for changing the Address’s primary key

@OneToOne(cascade=CascadeType.ALL)
@JoinColumns({
@JoinColumn(name="AddressId",referencedColumnName="AddressId"),
@JoinColumn(name="EmployeeAddressCountryId",referencedColumnName="AddressCountryId"),
@JoinColumn(name="EmployeeAddressCityId",referencedColumnName="AddressCityId")}
)
private Address address;

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public int getEmployeeId() {
return employeeId;
}

public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public List<Phone> getPhones() {
return phones;
}

public void setPhones(List<Phone> phones) {
this.phones = phones;
}

public List<Project> getProjects() {
return projects;
}

public void setProjects(List<Project> projects) {
this.projects = projects;
}

public EmployeePeriod getEmployeePeriod() {
return employeePeriod;
}

public void setEmployeePeriod(EmployeePeriod employeePeriod) {
this.employeePeriod = employeePeriod;
}

}

[/code]

  • The Employee defines a new mapping information cause the Address entity primary key has been changed.
  • The Employee references three columns at the Address Table. (In the next section, you could see the Employee Table is also has been changed by adding a new two columns).
  • The referencedColumnName isn’t mandatory when we are going to use the @JoinColumns.It does define the name of the column referenced by the foreign keys column defined in the Employee table. Employee Table has (AddressId, AddressCountryId, AddressCityId) as foreign keys.

Database Design

Figure 1.3 shows you the changes that made on the Employee and Address Table.

EmbeddedIdEmployeeTable

EmbeddedIdAddressTable

Figure 1.3

  • Address Table add a new two columns (AddressCountryId and AddressCityId).
  • Employee Table does reference the new columns that was added into Address Table.

Executable Application

[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.AddressPK;
import net.javabeat.eclipselink.data.ContractDeveloper;
import net.javabeat.eclipselink.data.Developer;
import net.javabeat.eclipselink.data.DriverLicense;
import net.javabeat.eclipselink.data.Employee;
import net.javabeat.eclipselink.data.EmployeePeriod;
import net.javabeat.eclipselink.data.FreelanceDeveloper;
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();
createEmployee();
// Commit
em.getTransaction().commit();
}

public static void createEmployee(){
// Create an address entity
Address address = new Address();

// Address Embeddable class (Type) instantiation
AddressPK addressPK = new AddressPK();
addressPK.setAddressId(1);
addressPK.setAddressCountryId(1);
addressPK.setAddressCityId(1);
address.setAddressId(addressPK);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Employee employee = new Employee();
employee.setEmployeeId(2);
employee.setEmployeeName("John Smith");

// Create an Employee Period Instance
EmployeePeriod period = new EmployeePeriod();
period.setStartDate(new Date());
period.setEndDate(new Date());

employee.setEmployeePeriod(period);

// 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 list of projects
List<Project> projects = new ArrayList<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]

Database Records That Are Persisted Using a New Primary Key

Figure 1.4 shows the results in of the executable application.

EmployeeRecords

AddressRecords

Summary

This tutorial experiment using of Embeddedable, Embedded and EmbeddedId annotations. In general the Embeddable annotation should define a new class (Type) that’s going to be persisted with the owning entity. The JPA implementation requires the developer to mention those properties that considered as an Embeddable class (Type). The EmbeddedId works at the same kind as the Embedded except the EmbeddedId defines an Embeddable primary key.

Filed Under: Java EE Tagged With: EclipseLink, JPA

JSTL Function fn:indexOf()

March 5, 2014 by Krishna Srinivasan Leave a Comment

The <fn:indexOf()> is a string function of JSTL. This function returns the index within a string of a specified substring. This function is used to get the first occurrence of the substring in the given string. This function takes string type as arguments and returns int type.

Syntax of <fn:indexOf()> Tag

[code lang=”html”]
int indexOf(String,String)
[/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 prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

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

<html>

<head>

<title>Example of fn:indexof tag of JSTL</title>

</head>

<body>

<form method="POST">

This will calculate the first occurance of given character/string in
the <br>specified String.

<table>

<tr>

<td>Enter Text</td>

<td><input type="text" name="text"></td>

</tr>

<tr>

<td>Search</td>

<td><input type="text" name="str"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="search"></td>

</tr>

</table>

</form>

<c:if test="${pageContext.request.method==’POST’}">

<c:set var="text" value="${param.text}" />

<c:set var="str" value="${param.str}" />

<font size="3" color="Red"> Index of first occurance : </font>
<font size="3" color="Blue"> <c:out
value="${fn:indexOf(text,str)}" />

</font>

</c:if>

</body>

</html>
[/code]

Steps for Execution

  • 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 :
Suppose if we enter the string Javabeat and if we want to index of the first occurrence of the “a” then it will shows the following output.
output of jstl function fn indexOf1
When we enter the string Javabeat and if we press search button it will shows the following output:
output of jstl function fn indexOf2

Previous Tutorial :  JSTL Function fn:escapeXml()   :: Next Tutorial : JSTL Function fn:join()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Function fn:escapeXml()

March 5, 2014 by Krishna Srinivasan Leave a Comment

The <fn:escapeXml()> function is used to escape characters that could be interpreted as XML markup. This is a string function of JSTL. This function also used to replace all characters which have a special meaning in XML.

The syntax of<fn:escapeXml()> Tag

[code lang=”html”]
java.lang.String escapeXml (java.lang.String)
[/code]

In this syntax string is of data type “String” it returns a string.

Example of <fn:escapeXml()>

[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 prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

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

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>JSTL EscapeXML Example</title>

</head>

<body>

<c:set var="testString"
value="This is <b>JSTL escapeXML example</b>
in this JSTL function tutorial."></c:set>
<br> Without escapeXml function : ${testString}

<br> Using escapeXml function : ${fn:escapeXml(testString)}

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

Steps for Execution

  • 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 :
output of jstl function fn escapeXml

In above example fn:escapeXml() function takes string parameter as string and returns the string after escaping XML markup characters. This takes string type as arguments and also returns the string type. This function helps to remove invalid character from address variables

 

Previous Tutorial :  JSTL Function fn:endsWith()   :: Next Tutorial :  JSTL Function fn:indexOf()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Function fn:endsWith()

March 5, 2014 by Krishna Srinivasan Leave a Comment

The <fn:endsWith()> function is used for checking the suffix of a string. This function manipulates the string that ends with specific character or string in JSP.

Syntax of <fn:endsWith()> Tag

[code lang=”html”]
boolean fn:endsWith(string,suffix)
[/code]

In the syntax string and suffix are data type String. It returns the Boolean value. If the input string is tested successfully then the functions returns true else it gives false.

Example of <fn:endsWith()> function is as follows:

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<title>JSTL fn:endsWith Example</title>
</head>
<body>
<form>
<p>
Enter a name <input type="text" name="str" />
</p>
<input type="submit" value="submit" />
</form>

<c:set var="str" value="${param.str}" />

<c:choose>

<c:when test="${fn:endsWith(str, ‘esh’)==true}">

Welcome ${str}

</c:when>
<c:otherwise>
Sorry ! You have entered wrong name please enter correct name
</c:otherwise>

</c:choose>

</body>

</html>
[/code]

Details of the Code

  • < c:set var=”str” value=”${param.text1}”> tag is used to set the variable name which we want to display in the output.
  • < c:when test=”${fn:endsWith(str, ‘JavaBeat.net’)==true}”> this line of code is used to demonstrate If the input string is tested successfully then the functions returns true else it gives false.

Steps for Execution

  • 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

Above example demonstrate working of fn:endsWith() function. In this we checked whether the entered string JavaBeat.com has the suffix. Since it is correct the function returns true.
endsWith tag

When we enter the value that contains the suffix as JavaBeat.net as showed in the above figure and when we will click on submit button it will show the following output.
endsWith2 tag

 

Previous Tutorial :  JSTL Function fn:containsIgnoreCase()  :: Next Tutorial :  JSTL Function fn:escapeXml()

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Function fn:containsIgnoreCase()

March 5, 2014 by Krishna Srinivasan Leave a Comment

The <fn:containsIgnoreCase()> function is a string function of JSTL. This function is used to check whether the entered string contains the specified substring irrespective of upper case or lower case. This function returns the boolean value.

Syntax of Function <fn:containsIgnoreCase()>

[code lang=”html”]
boolean:fn:containsIgnoreCase(string,substring)
[/code]

Example of Function <fn:containsIgnoreCase()>

In the above syntax string and substring are of data type String it returns the boolean value.

[code lang=”html”]
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:containsIgnoreCase() example</title>
</head>
<body>
<c:set var="string1" value="Welcome to JavaBeat.net"/>
<c:set var="string2" value="javabeat" />
<c:if test="${fn:containsIgnoreCase(string1, string2)}">
<c:out value="String1: Welcome to JavaBeat.net contains"/><br><br>
<c:out value="String2: javabeat"/>
</c:if>
</body>
</html>
[/code]

Details of the Code

  • < c:set var=”JavaBeat” value=”Welcome to javabeat.net”> tag is used to set the variable name which we want to display in the output.
  • <c:if test=”${fn:containsIgnoreCase(JavaBeat, ‘JavaBeat.net’)}”> this line of code
    checks whether the entered string contains the specified substring irrespective of upper case or lower case.

Steps for Execution

  • 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 :
output of JSTL Function fn containsIgnoreCase

 

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

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL Function fn:contains()

March 5, 2014 by Krishna Srinivasan Leave a Comment

The fn: contains() is a string function of JSP Standard Tag Library (JSTL). It is used to specify whether the string contains specified substring or not. If it contains substring, it returns true or else false.

Syntax of Function fn: contains()

[code lang=”html”]
boolean: fn: contains(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>Function fn:contains()</title>
</head>
<body>

Welcome to Javabeat contains "Java" word :
<c:out value="${fn:contains(myjavabeat,java)}"/>

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

Details of the Code

  • <c:out value=”${fn:contains(myjavabeat,java)}”/> tag is used evaluate result of the expression using “out” tag of core library and to search specified string into existing string we have used fn:contains() function of function library which returns true if substring found otherwise returns false.

Steps for Execution

  • Save this file as contains_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:
fn_contains

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

Filed Under: Java EE Tagged With: JSTL Tutorials

Eclipselink / JPA – Abstract Entity And Non-Entity Classes In The Entity Inheritance

March 4, 2014 by Amr Mohammed Leave a Comment

When we’ve discussed the inheritance and mapped superclasses concepts in the previous tutorials, we are avoiding concepts that could confuse the readers or makes misunderstanding for them.

Most of the clarified examples didn’t provide an Abstract Entity as a target entities that can be managed by the entity manager. On the contrary an Abstract Entity was only used in the tutorial of mapped superclass (See MappedSuperclass tutorial) in that the mapped superclass provides its children capability to inherit both of persistent entity states and the mapping information that belongs to. However, this isn’t the only concept that we would to discuss at this tutorial, but also we are going to discuss a non-entity class lies at the middle of the inheritance hierarchy for managed entities.

These relations might cause a confusion if they were coming in the middle of explanation. In this tutorial concepts like Abstract Entity, non-Entity class and Entity class will be used intensively.

Managed Entity

A managed entity instance is an instance with a persistent identity that’s currently associated with a persistent context. Meaning of managed entity is the contrary of Detached Entity, detached entity instance is an instance with a persistent identity that’s not (or no longer) associated with the persistent context. It is the basic term often used with the persistence technologies.

When an entity is being managed ?

In a brief we can define that, an entity is being managed by entity manager when it’s persisted to the database via an EntityManager’s persist method, which must be invoked within an active transaction. Also Entity objects retrieved from the database by an entity manager are also in the managed state, and if a managed entity instance is modified within an active transaction the changes that’s happened at that instance will be persisted into database once the transaction has been committed. for more information follow this link EntityManager.

Abstract Entity

An abstract entity can be specified as an entity, an abstract entity differs from a concrete entity only in that it cannot be directly instantiated. An abstract entity is mapped as an entity and can be the target of the queries (which will operate over and/or retrieve of its concrete sub-classes).

By returning to previous inheritance examples that implemented before, and by changing the Project entity from a normal entity into Abstract Entity. See Figure 1.1 that shows you the classes design for the whole system that’s being implemented.

Note : The examples in this tutorials are continued from the previous tutorials. For the better understanding of whole code, please read the previous tutorials (EclipseLink Tutorials).

ClassesDesign

Figure 1.1

  • The Project class displayed in an italic form. UML Design shows a class name by using an italic form if it was an abstract.
  • The GlobalProject and LocalProject are classes inherit from Project abstract entity.
  • Project is an abstract class, so it cannot be instantiated anymore.
  • The database can contains two types of Project instances, one for GlobalProject and the second for LocalProject. So no way to have a managed entity instance of type Project and consequently, the Project instance couldn’t be used for query results.

Anatomy of Project Abstract Entities Inheritance Hierarchy

Project.java

[code lang=”java”]
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) // The same inheritance strategy that is used
public abstract 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”]

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”]

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]

  • Although Project class is an abstract entity, but it contains an persistent entity states and mapping information.
  • The LocalPorject and GlobalProject are sub-classes from Project and they are inherit the persistent entity states and mapping information.
  • The strategy used for achieving the inheritance is Table Per Concrete Strategy.

Required Persistence Configuration

[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">
<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>

<!– Project Inheritance Hierarchy Entities–>
<class>net.javabeat.eclipselink.data.Project</class>
<class>net.javabeat.eclipselink.data.GlobalProject</class>
<class>net.javabeat.eclipselink.data.LocalProject</class>

<!– End –>
<class>net.javabeat.eclipselink.data.License</class>
<class>net.javabeat.eclipselink.data.DriverLicense</class>
<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]

Executable Application

The following JPAImpl class should show you how can we achieve a persistent operation for Project inheritance hierarchy.

JPAImp.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
createDeveloper();
// Commit
em.getTransaction().commit();

}</pre>
public static void createDeveloper(){
// Create an address entity
Address address = new Address();
address.setAddressId(1);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Developer developer = new Developer();
developer.setEmployeeId(1);
developer.setEmployeeName("John Smith");
developer.setTitle("Senior Java Developer");
// Associate the address with the employee
developer.setAddress(address);
// Create a Phone entity
Phone firstPhone = new Phone();
firstPhone.setPhoneId(1);
firstPhone.setPhoneNumber("+221 4050 615");
firstPhone.setEmployee(developer);

// Create a list of phone
List<Phone> phones = new ArrayList<Phone>();
phones.add(firstPhone);

// Project is an abstract entity class, no way to instantiate it
// Project project = new Project(); // That’s getting compiler error

// Create a Global Project
GlobalProject globalProject = new GlobalProject();
globalProject.setProjectId(2);
globalProject.setProjectName("Global Project");
globalProject.setProjectCountry("Brazil");
globalProject.setProjectBudget(new BigDecimal(150000));

// Create a Local Project
LocalProject localProject = new LocalProject();
localProject.setProjectId(3);
localProject.setProjectName("Local Project");
localProject.setProjectBudget(new BigDecimal(50000));

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

projects.add(globalProject);
projects.add(localProject);

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

// Persist the employee
em.persist(developer);

}

}

[/code]

Database Persisted Records

The Figure 1.2 shows you, that how the project abstract entity sub-classes are persisted at the database, although the Project itself isn’t persisted.

Project

GlobalProject

LocalProject

Figure 1.2

  • The Project abstract entity does provides a persistent entity states and mapping information and it’s capable of inherit them into its sub-classes.
  • No records has been persisted for project abstract entity into database, although the GlobalProject and localProject are inserted.
  • The Table Per Concrete Strategy provide separate table for every sub-class of Project.
  • In case, we are using Single Table Strategy or Joined Table, the project database will contains those common attributes that shared between Project and its sub-classes.

Non-Entity Inherit from Entity & Entity Inherit from Non-Entity

Let’s have the a new additional classes added to our classes design listed above, in that the Employee is a root of inheritance tree. A Developer is a direct sub-class for Employee. Meanwhile the Developer has two sub-classes (ContractDeveloper and FreelanceDeveloper).

Employee is an entity, but Developer isn’t, the Developer is a mapped superclass (Not managed at all). ContractDeveloper and FreelanceDeveloper are another entities.

Developer.java

[code lang=”java”]

package net.javabeat.eclipselink.data;

import javax.persistence.MappedSuperclass;

// Developer extends Employee entity, but it’s annotated using @MappedSuperclass
@MappedSuperclass
public class Developer extends Employee{

private String title;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}

[/code]

ContractDeveloper.java

[code lang=”java”]

package net.javabeat.eclipselink.data;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value="CDEV")
public class ContractDeveloper extends Developer {

}

[/code]

FreelanceDeveloper.java

[code lang=”java”]

package net.javabeat.eclipselink.data;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value="FDEV")
public class FreelanceDeveloper extends Developer {

}

[/code]

  • You should add the ContractDeveloper and FreelanceDeveloper into above persistence.xml file.
  • The Developer is a mappedSuperclass, so it’s just a way to share the persistent entity states and mapping information that inherit them from the Employee plus those added inside it to its sub-classes.

Executable Application for persisting new Sub-classes

[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.ContractDeveloper;
import net.javabeat.eclipselink.data.Developer;
import net.javabeat.eclipselink.data.DriverLicense;
import net.javabeat.eclipselink.data.Employee;
import net.javabeat.eclipselink.data.FreelanceDeveloper;
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 Freelance Developer
createFreelanceDeveloper();
// create Contract Developer
createContractDeveloper();
// Commit
em.getTransaction().commit();

}

public static void createFreelanceDeveloper(){
// Create an address entity
Address address = new Address();
address.setAddressId(1);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Developer developer = new FreelanceDeveloper();
developer.setEmployeeId(1);
developer.setEmployeeName("John Smith");
developer.setTitle("Senior Java Developer");
// Associate the address with the employee
developer.setAddress(address);
// Create a Phone entity
Phone firstPhone = new Phone();
firstPhone.setPhoneId(1);
firstPhone.setPhoneNumber("+221 4050 615");
firstPhone.setEmployee(developer);

// Create a list of phone
List<Phone> phones = new ArrayList<Phone>();
phones.add(firstPhone);

// Create a Global Project
GlobalProject globalProject = new GlobalProject();
globalProject.setProjectId(1);
globalProject.setProjectName("Global Project");
globalProject.setProjectCountry("Brazil");
globalProject.setProjectBudget(new BigDecimal(150000));

// Create a Local Project
LocalProject localProject = new LocalProject();
localProject.setProjectId(2);
localProject.setProjectName("Local Project");
localProject.setProjectBudget(new BigDecimal(50000));

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

projects.add(globalProject);
projects.add(localProject);

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

// Persist the employee
em.persist(developer);

}

public static void createContractDeveloper(){
// Create an address entity
Address address = new Address();
address.setAddressId(2);
address.setAddressCountry("United Kingdom");
address.setAddressCity("London");
// Create an employee entity
Developer developer = new ContractDeveloper();
developer.setEmployeeId(2);
developer.setEmployeeName("John Smith");
developer.setTitle("Senior Java Developer");
// Associate the address with the employee
developer.setAddress(address);
// Create a Phone entity
Phone firstPhone = new Phone();
firstPhone.setPhoneId(2);
firstPhone.setPhoneNumber("+221 4050 615");
firstPhone.setEmployee(developer);

// Create a list of phone
List<Phone> phones = new ArrayList<Phone>();
phones.add(firstPhone);

// Create a Global Project
GlobalProject globalProject = new GlobalProject();
globalProject.setProjectId(3);
globalProject.setProjectName("Global Project");
globalProject.setProjectCountry("Brazil");
globalProject.setProjectBudget(new BigDecimal(150000));

// Create a Local Project
LocalProject localProject = new LocalProject();
localProject.setProjectId(4);
localProject.setProjectName("Local Project");
localProject.setProjectBudget(new BigDecimal(50000));

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

projects.add(globalProject);
projects.add(localProject);

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

// Persist the employee
em.persist(developer);

}

}

[/code]

  • If you’ve been trying to persist a Developer instance, you are almost getting an exception tells you that the Developer isn’t a known entity even it’s not an abstract.
  • The ContractDeveloper and FreelanceDeveloper is the only developer instances that could persisted.
  • The ContractorDeveloper and FreelanceDeveloper should provide their discriminator values.

Database Persisted Records

Figure 1.3 depicts you the records that inserted.

Employees

Figure 1.3

  • The Freelance and contractor developer has been inserted by using the persistent entity states which inherited from the Developer. However, the Developer mapped superclass by its turn inherit some persistent states and mapping information from the Employee.

What’s happened if we’ve created a Simple Developer class?

Let’s create a simple Developer class (i.e. not mapped superclass).

Developer.java

[code lang=”java”]

package net.javabeat.eclipselink.data;
public class Developer extends Employee{
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

[/code]

  • The executable application mentioned above executes successfully.

Impact of using Entity and non-Entity on The Entity Manager for Querying

What’s heppened if you’ve used a sample query code like

[code lang=”java”]
em.createQuery("select d from Developer d"); // Developer non-entity
em.createQuery("select p from Project p"); // Project Entity
[/code]

  • The first query that used in the sample would be thrown an exception, cause the Developer isn’t an entity even if we’ve replaced the normal class to be mapped superclass. The Developer isn’t queryable and cannot be passed as an argument to EntityManager, also it couldn’t be a target of a persistent relationship.
  • The second query should executed successfully cause the Project is an entity, so it’s queryable and can be passed into EntityManager and it could be a target for persistent relationship.

Summary

What we should do if we have different type of classes in the same inheritance hierarchy? is JPA support that’s illusion between those entities and non-entities? This tutorial summarizes a different scenarios that could happen in the inheritance hierarchy, you’ve seen how can non-entity class inherit from an entity and vice versa. Also if you’ve decided to avoid the mapped superclass you are able to complete your inheritance hierarchy. Also, this tutorial gives you an examples of how we could differentiate between entity and non-entity once we are coming to make a query. The entity is queryable rather using of mappedsuper class or normal class.

Filed Under: Java EE Tagged With: EclipseLink, JPA

JSTL XML x:param Tag

March 4, 2014 by Krishna Srinivasan Leave a Comment

The tag is subtag of <x:transform> tag. This tag is used with transform tag to set a parameter in the XSLT stylesheet. This tag is used as nested with <x:transform> tag for sending the parameter along with the values.

Syntax of xml <x:param> tag

[code lang=”html”]
<x:param name=”string” value=”string”></x:param>
[/code]

Attributes of xml <x:param> tag

  • name : This attribute specifies the name of the XSLT parameter
  • value : This attribute specifies the value of the XSLT parameter.

Example of xml x:param tag

[code lang=”html”]
<em><strong>Listing 1:XML file-param.xml</strong></em>
[code lang="xml"]
<?xml version="1.0" ?>
<employee>
<employee>
<name>Mahantesh</name>
<roll>Software Designer</roll>
<designation>Associate</designation>
</employee>
<employee>
<name>Rushali</name>
<roll>Web Designer</roll>
<designation>Associate</designation>
</employee>
<employee>
<name>Ganesh</name>
<roll>Java Programmer</roll>
<designation>Associate</designation>
<span style="font-size: 12px; line-height: 18px;"> </employee></span>
<span style="font-size: 12px; line-height: 18px;"></employee></span>
[/code]

Listing 2:XSL File-param.xsl

[code lang=”xml”]
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
<xsl:param name="color" />
<xsl:param name="color1" />
<xsl:param name="color2" />
<xsl:template match="employee">
<html>
<body>
<h2>Employee Detail</h2>
<table border="1">
<tr>
<td align="left">
<b>Name</b>
</td>
<td align="left">
<b>designation</b>
</td>
<td align="left">
<b>Age</b>
</td>
</tr>
<span style="font-size: 12px; line-height: 18px;"> <xsl:for-each select="employee"></span>
<span style="font-size: 12px; line-height: 18px;"> <tr></span>
<span style="font-size: 12px; line-height: 18px;"> <td bgColor="{$color}"></span>
<span style="font-size: 12px; line-height: 18px;"> <i></span>
<xsl:value-of select="name" />
</i>
<span style="font-size: 12px; line-height: 18px;"> </td></span>
<td bgColor="{$color1}">
<xsl:value-of select="roll" />
</td>
<td bgColor="{$color2}">
<xsl:value-of select="designation" />
</td>
<span style="font-size: 12px; line-height: 18px;"> </tr></span>
<span style="font-size: 12px; line-height: 18px;"> </xsl:for-each></span>
<span style="font-size: 12px; line-height: 18px;"> </table></span>
<span style="font-size: 12px; line-height: 18px;"> </body></span>
<span style="font-size: 12px; line-height: 18px;"> </html></span>
<span style="font-size: 12px; line-height: 18px;"> </xsl:template></span>
<span style="font-size: 12px; line-height: 18px;"></xsl:stylesheet></span>
[/code]

Details of the Code

  • We have written the above file in xsl sheet and named as transform.xsl
  • <xsl:output method=”xml” omit-xml-declaration=”yes” indent=”yes”/> tag is used define the format of the output document.
  • <xsl:param name=”color”/> tag is used to display parameter name
  • <xsl:template match=”employee”> tag is used to match the specified node in the document.
  • <xsl:for-each select=”employee”> tag is used to loop the nodes in the xml document
  • <xsl:value-of select=”name”/> tag is used to select the particular value in the document.

Listing 3:JSP file-example.jsp

[code lang=”html”]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>JSTL x:param Example</title>

</head>
<body>
<c:import url="param.xml" var="xmlDoc" />
<c:import url="param.xsl" var="xslDoc" />
<x:transform doc="${xmlDoc}" xslt="${xslDoc}">
<x:param name="color" value="yellow" />
<x:param name="color1" value="red" />
<x:param name="color2" value="pink" />
</x:transform>
<span style="font-size: 12px; line-height: 18px;"></body></span>
<span style="font-size: 12px; line-height: 18px;"></html></span>
[/code]

Details of the Code

  • <c:import url=”param.xml” var=”xmlDoc” />tag is used to include the content of another resource in the current JSP. The var attribute is used to specify the variable name to which transformed XML document has to be set. The url is transform.xml
  • <x:transform doc=”${xmlDoc}” xslt=”${xslDoc}”> tag is used to transform the xml file into other format
  • <x:param name=”color” value=”yellow”/> tag is used to set the transformation parameter.

Steps for Execution

Before executing the xml programs we should add jar files 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 :
jstl xml x param tag

Previous Tutorial :  JSTL XML x:choose ,x:when and x:otherwise Tags :: Next Tutorial : JSTL SQL Tags Library

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL XML x:choose ,x:when and x:otherwise Tags

March 4, 2014 by Krishna Srinivasan Leave a Comment

The <x:choose> tag is XML tag used for checking conditional statements. This is similar to java switch statement. In java program we use the case statement but in JSTL we use <c:when< and <x:otherwise< instead of case statement.

Syntax of <x:choose> Tag

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

JSTL XML <x:when> Tag

This is the subtag of <x:choose> tag. The <x:when> tag is checks to see whether the expression evaluates to true, if it is true then it executes the body of <x:when> tag. This tag encloses a single case within the <x:choose> tag.

Syntax of <x:when> tag

[code lang=”html”]
<x:when attribute> body content </x:when>
[/code]

Attribute of <x:when> tag

  • select: This tag is used to specifies whether the body of the tag will be executed or no.

JSTL XML <x:otherwise> Tag

This is the subtag of <x:choose> which is used with <x:when> tag. This is similar as <x:when> tag but it is unconditional. This tag includes its body when all of the conditions specified using <x:when> tags evaluated to false.

Syntax of <x:otherwise> tag

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

Example of <x:choose&gt ,<x:when>, and <x:otherwise> tag

[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 x:choose Tags</title>

</head>
<body>

<h3>Fruits Info:</h3>

<c:set var="fruitss">

<fruits>

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

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

</fruits>

</c:set>

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

<x:choose>

<x:when select="$output//fruit/price = ’90’">
The apple price is rs 90
</x:when>

<x:otherwise>
Unknown Fruit.
</x:otherwise>

</x:choose>

</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:choose> tag is used to check the conditional statement.
  • <x:when select=”$output//fruit/name = ‘apple'”> tag is used to execute the particular statement when it is true.
  • <x:otherwise> tag is used to define unconditional statement.

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 :
jstl_xchoose_demo

 

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

Filed Under: Java EE Tagged With: JSTL Tutorials

JSTL XML x:transform Tag

March 4, 2014 by Krishna Srinivasan Leave a Comment

The <x:transform> tag is used to transform an xml data based on XSLT script. This tag used to apply an XSL transformation on an XML document.

Syntax of <x:transform> Tag

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

Attributes of <x:transform> Tag

Attributes Description
var This attribute specifies the variable name to which transformed XML document has to be set.
scope This attribute specifies the scope of the var attribute.
doc This attribute specifies the source XML document to be transformed.
xslt This attribute specifies javax.xml transform source transform stylesheet as string, reader or source object.
xmlSystemId This attribute is deprecated attribute, used with attribute xml.
docSystemId This attribute takes the system identifier(URI) for parsing the XML document.
result The javax.xml transform. result object that captures or processes the transformation result.

Example of <x:transform> Tag

Listing 1:transform.xsl file

[code lang=”xml”]
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="doc"/>

<xsl:template match="/">
<html>
<body>

<h2>Company’s Employee detail</h2>

<table border="1">
<tr>
<th align="left">name
</th>
<th align="left">designation
</th>
<th align="left">age
</th>
</tr>
<xsl:for-each select="org/company/emp">
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td>
<xsl:value-of select="designation"/>
</td>
<td>
<xsl:value-of select="age"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>

</xsl:template>
</xsl:stylesheet>
[/code]

Details of the Code

  • We have written the above file in xsl sheet and named as transform.xsl
  • <xsl:param name=”doc”/> tag is used to display parameter name.
  • <xsl:template match=”/”> tag is used to match the specified node in the document.
  • <xsl:for-each select=”org/company/emp”> tag is used to loop the nodes in the xml document.
  • <xsl:value-of select=”name”/> tag is used to select the particular value in the document.

Listing 2:Xml File transfor.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<org>
<company>
<emp>
<name>Mahantesh Nagathan</name>
<designation>Sr. Sofware developer</designation>
<age>25</age>
</emp>

<emp>
<name>Rushali Bhatkande</name>
<designation>Graphics Designer</designation>
<age>23</age>
</emp>
</company>

<company>
<emp>
<name>Ganesh Patil</name>
<designation>Sr. Java Programmer</designation>
<age>24</age>
</emp>

<emp>
<name>Maruti Patil</name>
<designation>Sr. Flash Programmer</designation>
<age>23</age>
</emp></company></org>
[/code]

Listing 3:JSP file-example.jsp

[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" %>

<c:import var="xml" url="transform.xml" />
<c:import var="xsl" url="transform.xsl" />
<x:transform xml="${xml}" xslt="${xsl}" />
[/code]

Details of the Code

  • <c:import var=”xml” url=”transform.xml” /> tag is used to include the content of another resource in the current JSP. The var attribute is used to specify the variable name to which transformed XML document has to be set. The url is transform.xml
  • <c:import var=”xsl” url=”transform.xsl” /> in this tag the url is transform.xsl
  • <x:transform xml=”${xml}” xslt=”${xsl}” /> tag is used to transform the xml file into other format.

Steps for Execution

Before executing the xml programs we should add jar files namely:
xalan-2.7.0.jar,serializer-2.7.1.jar,xercesImpl-2.8.1.jar,xml-apis-2.0.2.jar

  • Click on the jsp File
  • Right click on mouse and select run as ->click run on server
  • Then output page will get displayed.

Output

When the execution process is completed successfully we will get the following output :
JSTL xml x transform tag

 

Previous Tutorial :  JSTL XML x:parse Tag :: Next Tutorial : JSTL XML x:choose ,x:when and x:otherwise Tags

Filed Under: Java EE Tagged With: JSTL Tutorials

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • 5
  • …
  • 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