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

How To Create EclipseLink Project Using Maven Archetype

February 16, 2014 by Amr Mohammed Leave a Comment

This article should discuss the installation and configuration of EclipseLink-JPA using Maven dependencies and Maven archetype project creation principle. This article assumes that the machine that used for installation is already have installed a Maven. So the “mvn” command should works. This article will use an Eclipse Kepler release 1 as an Integrated Development Environment, so be sure that you have installed one. To install the Eclipse Kepler refer to the following Eclipse Kepler IDE.

Installation of Maven

Check if the maven has installed or not by using the maven command, “mvn -version”. The proper reply should be as shown at the figure 1.1. (Maven Windows and Maven Ubuntu)

Maven-Check

Figure 1.1

Create Project Using Maven

To create a Java project using maven, you should use the maven archetype. The Archetype is a template toolkit that used for creating a standard Java projects. Those templates are used to create several types of Java projects starting from a standard simple Java into very complicated Enterprise application.

Creating a maven Java project should follow these steps mentioned below:

  • Download the latest maven-archetypes-templates from an official “Github” site Maven Archetypes Zip File using the “Download Zip” link that’s appended at the right panel of the page.
  • Unzip the file inside an empty folder and navigate into quickstart-java-app folder and execute the following maven commands to install the template that will be used to create a simple standard Java project:
  1. Execute mvn clean archetype:create-from-project. The result of execution should be a new template that must be installed on your local repository to be used later.
  2. Navigate to “target/generated-sources/archetype” and execute mvn install to install the created template into your local repository.
  3. Navigate into an empty folder and execute mvn archetype:generate -DarchetypeCatalog=local -DgroupId=net.javabeat.eclipselink –DartifactId=EclipseLink-Installation -Dversion=1.0
  4. A list of local archetype will be listed if you have different archetypes that have been created.
  5. Enter the number beside of the archetype named “quickstart-java-app-archetype”.
  6. List all folders that created in a step 3 by using dir or ls based on your Os. You should see the artifact EclipseLink-Installation.
  7. The EclipseLink-Installation is a Java standard project that created by the maven. The created project contains your own named package that passed in the -DgroupId.

See the Figure 1.2 that shows you the created project and its structure.

MavenProjectStructure

Figure 1.2

Import Maven Project Into Eclipse IDE

Eclipse IDE provides the developer capability of importing a maven project through an eclipse driven wizard. Follow the following steps to import the project created previously.

  1. Open EclipseIDE.
  2. Right-Click at the “Project Explorer”.
  3. Choose import option and from the right menu click import.
  4. Expand the maven tree.
  5. Choose Existing Maven Projects. And click next.
  6. Navigate into your created project by using the browse and click ok. In our case the path is C:\JavaBeat\archetype.
  7. The Eclipse IDE should read the pom.xml and tell you with the name of the projects found there.
  8. In our case the Eclipse IDE will mention /EclipseLink-Installation/pom.xml. See Figure 1.3 as the only project there.
  9. Select the project & click finish.

The project created is imported successfully. See Figure 1.4

EclipseIDEImportMavenProjectWizardResult

Figure 1.4

Compile & Execute the Project

To compile the project, click on the project from the project menu and choose clean. The project must be compiled successfully. See Figure 1.5. Try to run using CTRL+Shift+x & j or by using the run from the menu.

ProjectCompilation

Figure 1.5

If you have noticed that the project execution doesn’t print out “Hello” followed by the entered name. Make sure the log4j.properties uses the correct rootLogger. If the logger uses “debug” while the rootLogger configured to use “info”; the logger will not behave as you expect and thereby it will not print any message. Let they use the same type of message. As you have noticed the logger in the Figure 1.5 uses the info method, so the rootLogger must also use the info.

EclipseLink Artifacts For Maven

Adding external libraries have never been easier than now. To add the EclipseLink-JPA library, you should add the following lines at your project’s pom.xml file.

[code lang=”xml”]
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
</repositories>
[/code]

Also, you should add the required dependency within dependencies tag

[code lang=”xml”]
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
[/code]

Configure persistence.xml

The persistence API requires a persistence.xml that is located under META-INF folder.

To be able to use the persistence API, you should follow the following steps:

  1. Create a folder under src/main/java called META-INF
  2. Create a file named persistence.xml.
  3. Copy the persistence.xml file that produced at the article Eclipse Link – JPA Installation and Configuration Using Eclipse into META-INF.

Testing Application

Add at your default generated HelloService Java class the code that uses the persistence API.

[code lang=”java”]
System.out.println(Persistence.createEntityManagerFactory("EclipseLink-Installation").isOpen());
[/code]

See the Figure 1.6 that shows you the HelloService that uses Persistence API successfully.

TestingApplication

Figure 1.6

Filed Under: Java EE Tagged With: EclipseLink, Maven

EclipseLink – JPA Installation And Configuration Using Eclipse

February 15, 2014 by Amr Mohammed Leave a Comment

This article should teach you how can do you install and use the EclipseLink-JPA. The Integrated Development Environment that will be used in this installation guide is “Eclipse Java EE IDE for Web Developers- Kepler Service Release 1”.

Install Eclipse IDE

First of all you should install Eclipse IDE from Eclipse official site. Open the Eclipse after finishing the installation. This tutorial uses the Kepler version of Eclipse IDE. The view of the Eclipse IDE should be as shown in the figure 1-1.

EclipseIDE-Welcome

Figure 1.1

Install EclipseLink JAR Files

  • Download EclipseLink 2.5.1 Installer Zip from the eclipse organization site or follow this link https://www.eclipse.org/eclipselink/downloads/ link.  That contains the implementation for all persistence services that EclipseLink provides.
  • The JAR files that should be used for JPA persistence service are:
  1. eclipselink.jar
  2. javax.persistence.source_2.1.0.v201304241213.jar
  3. javax.persistence_2.1.0.v201304241213.jar
  • Unzip the file into any directory you would use for completing the installation. Already we have Unzip the file into “C:/JavaBeat” folder.

Set JPA Facet in Eclipse IDE

Create an eclipse dynamic project and prepare it for adding JPA facet. Follow the steps:

  1. Open an Eclipse IDE.
  2. Create a Dynamic project.
  3. Right-click on the project created. Select properties.
  4. Click on the Project Facets.
  5. Make the JPA option selected, and choose JPA version 2.1. See the figure .1.2.

Dynamic-Project-Created

Figure 1.2

A further configuration is required, so proceed to complete it by pressing on “Further configuration required” error message that shown below. This action should open a new dialog for setting a JPA Facet.

Add JPA Facet

The JPA Fact dialog should be displayed as shown at Figure 1.3. This dialog allows the user to add the required libraries to implement the JPA.

JPA-Facet

 Figure 1.3

  1. The dialog shows the platform of the persistence that will be used; it is by default select the “Generic 2.1” option. Change the platform to be “EclipseLink 2.5.x”.

  2. Let the JPA implementation menu without any change. The type “User Library” allows you to add a user driven library. And add the JPA library.
  3. Click on “Manage Libraries”. Another way of adding library can be achieved by using “Download Library” that not covered at this tutorial.
  4. Click on “New” to add a new library.
  5. Set the name of the library and click Okay.

Now, the library is ready to add the required JARs that mentioned in the “Install EclipseLink JAR files” step. See the figure 1.4.

Create-JPA-User-Library

Figure 1.4

Library Configuration

The configuration of the library require adding the needed JARs file for implementing the JPA. Follow the next steps for achieving that configuration.

  • Click on “Add External JARs”.
  • Add eclipselink.jar that’s located under “C:/JavaBeat/eclipselink/jlib”.
  • Add each JAR starting with javax.persistence.* that’s located under “C:/JavaBeat/eclipselink/jlib/jpa”. See Figure 1.5.

Add-Libraries

Figure 1.5

  • Click Okay, should close the add library dialog. But to avoid the JPA Facet: “At least one user library must be selected”.
  • Select the created library.
  • Click “Okay”.

The dynamic project created is ready now for using a JPA. But the JPA is a persistence service that relates with the Relational-Database system. So one step remaining and it is the database connection creation.

Database Connection Creation

Once you have finished creating a user library, it is now the step of creating a database connection. The final dialog should appear as you can see at Figure 1.6.

UserLibraryAdded

Figure 1.6

To create a database connection, follow the following steps:

  1. Click on “Add Connection”.
  2. Connection profile dialog will be opened.
  3. Choose the type of the database that your project would use. This tutorial assumes that the database that would be used is a MySQL database.
  4. Change the name of the connection. Click next.
  5. Fill the form of the “Specify a Driver and Connection Details”. The dialog should select the driver of the database that you had selected automatically. if it doesn’t, you have to go through to install a new driver definition; that will not be covered at this article. But when you come to the properties of the connection, you should specify the correct database connection information and then click on the “Test Connection”. See Figure 1.7.
  6. By end of the step 5, you are ready to use your connection in your JPA project.
  7. Click finish.
  8. The dialog should be closed, so be sure that the created connection has been selected.
  9. Click Okay will close the Further configuration dialog.
  10. Click Okay will close the project facets.

ConnectionTest

Figure 1.7

Now, you have created a new “Dynamic Project” and configured it for JPA use. Navigate the project created and open the persistence.xml that you have within a “META-INF” folder.

Persistence Configuration

I you have reached here, it seems everything are done successfully, so it’s a time for editing the persistence.xml that would help us to connect our database.

To configure the persistence.xml file you have to double click on it. It should be opened in a separate editor. The opened editor has multiple titled tabs shown at the bottom of the editor. Follow the below steps for full configuration of persistence.xml.

  1. Navigate to Connection tab.
  2. Change the transaction type into “Resource Local”. This change should activate the EclipseLink connection pool.
  3. Click on “populate from connection”.
  4. Choose the connection that created before.
  5. Use the Ctrl + S to save the file.
  6. Navigate to Source tab. You should see the minimal amount of configuration that required to connect your database.

See the Figure 1.8 for correct database connection.

ConnectionWithinPersistence

Figure 1.8

Testing EclipseLink Application

For testing the configuration of your project if whether it is working or not, you have to develop a Java Class. That Java Class should use the persistence name of your persistence.xml. In our case, the persistence name is “EclipseLink-JPA-Installation”.

  • Write a main method and use Persistence class to create EntityManagerFactory; that is consider as an entry point for the JPA.
  • Test you connection via calling isOpen() method from the entity manager that created before. See Figure 1.9.

TestResult

Figure 1.9

The code of the testing application:

[code lang=”java”]
package net.javabeat.eclipselink;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAImpl {
public static void main(String [] args){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("EclipseLink-JPA-Installation");
System.out.println("Is opened connection :: "+ factory.createEntityManager().isOpen());
}
}
[/code]

Filed Under: Java EE Tagged With: EclipseLink

Annotation Based Bean Wiring @Autowired in Spring framework

May 27, 2012 by Amr Mohammed Leave a Comment

Since Spring 2.5, one of the most interesting ways of wiring beans in Spring has been to use annotations to automatically wire bean properties. Auto wiring with annotations isn’t much different than using the autowire attribute in XML. But it does allow for more fine-grained auto wiring, where you can selectively annotate certain properties for autowiring.

Annotation wiring isn’t turned on in the Spring container by default. So, before we can use annotation-based autowiring, we’ll need to enable it in our spring configuration. The simplest way to do that is with annotation element from the context Spring’ configuration namespace.

[java]
<context:annotation-config/>
[/java]

Adding the above line would enable the autowiring mechanism in the spring framework. Alternatively, you can include the AutowiredAnnotationBeanPostProcessor to enable the autowiring feature as follows:

[java]
<bean class="org.springframework.beans.factory.
annotation.AutowiredAnnotationBeanPostProcessor"/>
[/java]

The following is the simplest way to enable:

[java]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/XMLSchema-instance
xmlns:context=http://www.springframework.org/schema/context
xsi:schmeaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schmea/context/spring-context-3.0.xsd”>
<context:annotation-config/>
<context:component-scan base-package="com.java.beat.beans"/>
</beans>
[/java]

tells the Spring that you intend to use annotation-based wiring in Spring. Once it’s in place you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors.

also read:

  • Spring interview questions
  • Introduction to Spring framework

elements works by scanning a package and all of its sub-packages, looking for classes that could be automatically registered as beans in the Spring container. The base-package attributes tells the package to start its scan from. @Component annotation used to register classes as beans in a Spring container.

Spring 3.0 support a few different annotations for autowiring.

Spring’s own @Autowired annotation.

  • The @Inject annotation from JSR-330.
  • The @Resource annotation from JSR-250.

We’ll look at how to use @Autowired first. Then we’ll cover the remaining annotations in other posts.

@Autowired

Marked a bean property with @Autowired will surely push Spring framework to wire it with the targeted one using by Type. What’s especially interesting about @Autowired is that you don’t have to use it with a property declaration or a setter method. You can use it on any method to automatically wire in bean references.

[java]
package com.java.beat.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component("holderBean")
public class HolderBean {
@Autowired
@Qualifier("wiredBean")
private WiredBean wiredBean;
public WiredBean getWiredBean() {
return wiredBean;
}
public void setWiredBean(WiredBean wiredBean) {
this.wiredBean = wiredBean;
}
}
[/java]
[java]
package com.java.beat.beans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component("wiredBean")
@Qualifier("wiredBean")
public class WiredBean {
}
[/java]

As you can see in the previous example, HolderBean has a reference to WiredBean, autowired using @Autowired annotation. As you can see, @Autowired won’t even thwarted by the private keyword. Even though the wiredBean property is private, it will still be autowired. Is there no limit to @Autowired ’s reach ?

Actually, there are a couple of circumstances that could keep @Autowired from getting its job done. Specifically, there must be exactly one bean that’s applicable for autowiring into the @Autowired property or parameter. If there are no applicable beans or if multiple beans could be autowired, then @Autowired will run into some trouble. Fortunately, there’s a way can we help @Autowired out in those circumstances.

First, let’s look at how to keep @Autowired from failing when there is not a matching bean.

Optional Autowiring

By default, @Autowired has a strong contract, requiring that the thing it annotates is wired. If no bean can be wired into the @Autowired – annotated property or argument, then autowired fails (with a nasty NoSuchBeanDefinitionException). That may be what you want – to have Spring fail early when autowiring goes bad rather than later with NullPointerException.

But it’s also possible that the property being wired is truly optional and a null value is acceptable. In that case, you can configure optional autowiring be setting @Autowired’s required attribute to false.

[java]
@Autowired(required=false)
Private WiredBean wiredBean;
[/java]

Qualifying Ambiguous Dependencies

In the other hand may be the problem’s not a lack of beans for Spring autowiring to choose from. May be it’s an abundance of (or at least two) beans, each of which is qualified to be wired into a property or parameter.

For example, suppose you have two beans that of type WiredBean. In that event, there is no way for @Autowired to choose which one you really want. So instead of guessing, a NoSuchBeanDefinitionException will be thrown and wiring will fail.

To help @Autowired figure out which bean you want, you can accompany it with Spring’s @Qualifier annotation.

[java]
@Autowired
@Qualifier("wiredBean")
private WiredBean wiredBean;
[/java]

Filed Under: Spring Framework Tagged With: @Autowired, Spring, Spring 3.0, Spring 3.0 @Autowired, Spring 3.0 annotations, Spring 3.0 wiring beans with annotations, Spring Framework, Spring MVC

Spring 3 Features

May 21, 2012 by Amr Mohammed Leave a Comment

Before we talk about the Spring 3.0 features, it is quite reasonable to walk through a list of features introduced in the Spring 2.5 release. Looking into the Spring 2.5 features would help you to understand the new features in the Spring 3.0 release. In November 2007, the Spring team released version 2.5 of the Spring framework. The significance of Spring 2.5 was that it marked Spring’s embrace of annotation-driven development. Prior to Spring 2.5, XML-based configuration was the norm. Spring 2.5 introduced several ways of using annotations to greatly reduce the amount of XML needed to configure Spring. Some of these annotations are:

also read:

  • Introduction to Spring Framework
  • Introduction to Spring MVC
  • Spring Tutorials

New Features in Spring 2.5

  • Annotation-driven dependency injection through @Autowired annotation and fine-grained auto wiring control with @Qualifier.
  • Support for JSR-250 annotations, including @Resource for dependency injection of a named resource, as well as @PostConstruct and @PreDestroy for life-cycle methods.
  • Auto-detection of Spring components that are annotated with @Component.
  • An all-new annotation-driven Spring MVC programming model that greatly simplifies Spring web development such as @Controller.
  • A new integration test framework that’s based on JUnit 4 and annotations.

Even though annotations were the big story of Spring 2.5, there’s more:

  • Full Java 6 and Java EE 5 support, including JDBC 4.0, JTA 1.1, Java Mail 1.4 and JAX-WS2.0.
  • A new bean name pointcut expression for weaving aspects into Spring beans by their name.
  • Built-in support for AspectJ load-time weaving.
  • New XML configuration namespaces, including context namespace for configuring application context details and a jms namespace for configuring message-driven beans.

Once you are looking for all of those features, you may ask yourself about really what the added value of Spring 3.0 is and what the new features that are added in it. Next paragraph will clarify that.

What’s new In Spring 3.0?

Spring 3.0 makes the entire spring code base to take advantage of the Java 5.0 technology. The notable Java 5 features like Generics, Varargs, Annotations and other improvements has been extensively implemented with the Spring 3.0 release. This release is one of the major and important release for Spring 3.0.

With all of good stuff in Spring 2.5, it’s hard to imagine what could possibly follow in Spring 3.0. But with the 3.0 release, Spring one-upped itself with the continuation of annotation-driven theme and several new features:

  • Full-scale REST support in Spring MVC, including Spring MVC controllers that respond to REST-style URLs with XML, JSON, RSS or any other appropriate response. REST support in spring is one of the beautiful addition to the spring framework itself. It make life easier for the developers who want to write the RESTful webservices.
  • A new expression language that brings Spring dependency injection to a new level by enabling injection of values from a verity of sources, including beans and system properties.
  • New annotations for Spring MVC, including @CookieValue and @Request–Header, to pull values from cookies and request headers, respectively.
  • A new XML namespace for easing configuration of Spring MVC.
  • Support for declarative validation with JSR-303 (Bean Validation) annotations.
  • Support for the new JSR-330 dependency injection specification.
  • Annotation-oriented declaration of asynchronous and scheduled methods.
  • A new annotation-based configuration model that allows for nearly XML-free Spring configuration.
  • The Object-to-XML (OXM) mapping functionality from the Spring Web services project has been moved into the core Spring framework.

Just as important as what’s new in Spring 3.0 is what’s not in Spring 3.0. Specifically, starting with Spring 3.0, Java 5 is now required, as Java 1.4 has reached end-of-life and will no longer be supported in Spring. The above list is brief introduction to what are the new features introduced in this release. Going forward, I would write each feature in detail with the appropriate examples. Looking forward to your comments and feedback after reading the article. If you are looking for any specific feature, please post it in the comments section.

Filed Under: Spring Framework Tagged With: Spring 3.0, Spring 3.0 New Features, Spring 3.0 Versus Spring 2.5

  • « Previous Page
  • 1
  • …
  • 13
  • 14
  • 15

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