Saturday, October 24, 2015

JPA entities and persistence with Hibernate(hbm2ddl.auto)

JPA entities and persistence with Hibernate(hbm2ddl.auto)

Assuming that you have your project set up complete, we are proceeding in this tutorial with the demonstration of the JPA entity creation. In this tutorial we will create an entity called Student and will use Hibernate's auto generation property to persist the entity in the database.
entity creation
To create a new Entity right click the project module which holds your JPA module, In our case we have put our JPA structure in EJB project. So right click EJB project and New > JPA Entity. This will open a JPA entity wizard. In this you need to provide the package name and class name for the entity. Once fields are filled press Next. We are using com.em.jpa.entity and class name as Student.
Project Details
field creation
In the second screen you are presented with the options to create the fields for entity, its up to you that you want to create fields here or code them later manually. We are creating four fields here.
int id
String firstName
String lastName
String Standerd
mark the key after creating fields
Click Add and enter the data type in first field and property name in second field, click OK. Repeat the process for the number of properties you want to create for your entity. After creating these fields we are marking "id" as key, this will annotate the id field with @Id which makes it the primary key for the table in database.
Now click Finish to complete the wizard and generate the code. Once you are through the code will be presented to you with the fields you created and pre generated getters and setters method for the fields. Also there shall be Serializable Interface implemented and auto generated serial version id. initially the fields generated looks like following code snippet.

@Id
private int id;
private String firstName;
private String lastName;
private String standerd;
private static final long serialVersionUID = 1L;
Now we need some changes in this code, first of all we need the primary key to be generated automatically whenever we create and new entry, fo this we are going to use @GeneratedValue annotation with strategy AUTO, this is the way to tell JPA that we want the id to be automatically generated, here you can leave on system to decide the way key is generated or you can specify the way you want to generate it. GenerationType is an enumeration provided with four types, AUTO, IDENTITY, SEQUENCE, TABLE. Choose as it suites you, however we are proceeding with AUTO.
Also we want to make sure that our columns are not null, so we use @NotNull annotation which is a validation constraint to ensure the not null property on the table column, also we want to limit the length of the fields so we are using @Length annotation with property max. This will make sure when the table is generated it has limited length defined for the columns. So after the basic tuning here is how our code looks like.

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int id;
 
 @NotNull
 @Length(max=20)
 private String firstName;

 @NotNull
 @Length(max=20)
 private String lastName;

 @NotNull
 @Length(max=5)
 private String standerd;

 private static final long serialVersionUID = 1L;
In future when we query(using JPQL) the table generated corresponding to this entity, we would like to fetch all the rows at once available, beside the custom query structure, for that purpose it is good practice to specify a NamedQuery for the entity. Named query is marked by the @NamedQuery annotation with two properties, name, which is the name of query, and query, which is the actual query to be executed. and this annotation is of entity level so placed on the entity class definition.

@Entity
@NamedQuery(name="Student.getAll",query="SELECT s FROM Student s")
public class Student implements Serializable {
...
So final code for the entity looks like this

package com.em.jpa.entity;

import java.io.Serializable;
import java.lang.String;
import javax.persistence.*;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;

/**
 * Entity implementation class for Entity: Student
 *
 */
@Entity
@NamedQuery(name="Student.getAll",query="SELECT s FROM Student s")
public class Student implements Serializable {
 
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int id;
 
 @NotNull
 @Length(max=20)
 private String firstName;

 @NotNull
 @Length(max=20)
 private String lastName;

 @NotNull
 @Length(max=5)
 private String standerd;

 private static final long serialVersionUID = 1L;

 public Student() {
  super();
 }   
 public int getId() {
  return this.id;
 }

 public void setId(int id) {
  this.id = id;
 }   

 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getStanderd() {
  return standerd;
 }
 public void setStanderd(String standerd) {
  this.standerd = standerd;
 }  
}
Now our entity is ready but to connect JPA to the database we need to configure persistence unit of JPA. This configuration is to be done in persistence.xml file which is available in META-INF directory of the application. We have created a datasource which we are going to use here. in the persistence.xml file, create a persistence unit using tag persistence-unit with the property name. And after that specify the JNDI name of the datasource for this persistence unit using tag, jta-data-source tag. so our code in persistence.xml looks like this.

<persistence-unit name="DemoEJB">
  <jta-data-source>java:jboss/datasources/school</jta-data-source>
...
As we mentioned earlier, that we are going to use hibernate's auto generation property(hbm2ddl.auto) we need to specify this property with our datasource, so that system can operate on it. We use properties and property tag for the purpose. Our complete persistence.xml looks like following.

<?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="DemoEJB">
  <jta-data-source>java:jboss/datasources/school</jta-data-source>
  <properties>
   <property name="hibernate.hbm2ddl.auto" value="update"/>
  </properties>
 </persistence-unit>
</persistence>
with this property we specify the value as update which tells the system to not create the entities from scratch every time the application is deployed, but to update it with any changes required.
Our persistence unit is now ready to work, when you deploy the application you will notice the creation of table named Student in the database and on checking the structure you will find that table has been created in database.
Database structure of entitiy
In the Image above please note the properties of the fields these are what we specified in our entities, also the name of the columns are same as the fields of the entity class.
Please feel free to comment if you find some error in the program or there is some problem in the implementation of the program. In the next part we will describe the use of EJB, we are going to divide the EJB part in two subpart, that would be using Local and Remote interface implementation.

JavaEE7 project set up with Eclipse, Wildfly, MySql, JPA, Hibernate, EJB, CDI, JSF and RS

JavaEE7 project set up with Eclipse, Wildfly, MySql, JPA, Hibernate, EJB, CDI, JSF and RS

In this project structure we are going to create a project structure for our Application. The over all structure is going to be of three main modules and inside them will be sub modules. This is a simplest form of structure however if we need something later on in series we will include it later in the series as required.
First step is to create and "Enterprise Application Project". for that right click in the project window and select project. Or you can use small project icon on the upper left corner of Eclipse window. In the project selection wizard search and select Enterprise Application Project.

In the project creation wizard enter the Project name and select target runtime, in our case Wildfly 8. If you want to configure the EAR version you can do here other wise its good enough to leave it like that and click Next.

In this part we don't have any dependencies yet so we will leave that part alone and click the checkbox displaying "Generate application.xml deployment descriptor". Afterward press click Finish to complete the wizard.
Now that EAR part is complete, this will act as a whole of container for the sub modules of our application, which are coming up in following content.
Next Create an EJB Project in the same way you created the EAR project.
EJB Project Creation
On the first screen add the project name, Target runtime again same as EAR project and you can select the EJB version to use in application. Important part is to check the checkbox, "Add project to an EAR" and here selecting the EAR application created earlier(usually is selected by default).
Leave Screen Default
Generate ejb-jar
Press Next and on second screen there is nothing to alter, press Next again and here un-mark the "EJB client JAR" checkbox and mark the checkbox to generate ejb-jar.xml for the project. Finally press Finish to complete the wizard.
We are not done yet, we will come back to this module but before there is another part to be created. In the next section we will create the Web client part for the application. In our specification we are going to do this using Web application with JSF.
Dynamic Web project
Leave default
Create deployment descriptor
So now is turn to create a Dynamic Web Project, the process remains identical to the creation of EJB project. Give this project a name and add it to EAR project, click Next and Next again, click checkbox to generate deployment descriptior then click Finish to complete the wizard.
We have all three component of our project ready now we need some configuration part, As you may ask, There were mention of JSF, RS, JPA, Hibernate and CDI and I haven't seen any traces of these.
Wait ! we are coming onto these now. First things first, right click the EJB project in your project explorer and go to Properties > Project Facets.
EJB Facets
here select the Facets you need in the application, in our application we are going to include CDI, JAX-RS and JPA. Wait, Wait, Wait! we are not done yet, once you select the Facets press Apply and in the side bar look for corresponding Facets.
Enable hibernate
Go to CDI and make sure it is enabled. When we select JPA we are going to use JPA with Hibernate so we need to make sure that Hibernate is also enabled. Same goes with JAX-RS.
It may happen that JPA option is not yet available in the sidebar. Nothing to worry, press OK, that will save the progress and again right click the project and go to Properties. This time JPA will be enabled.
jpa settings
Go to JPA. In the Platform selection, Select Hibernate. Leave Implementation to Library provided by Target Runtime(unless you want to specify some other JPA Implementation). In the bottom of the window, Select the RadioButton for "Discover annotated classed automatically". This helps when we are working with with annotations, when we annotate any entity it will be discovered by the JPA automatically we wouldn't need to specify it into persistence.xml file.
Finally click OK to complete the configuration and Exit.
jsf enabling
ejb dependency
After this, we need to configure the web application, so right click the Web Application and go to Properties > Project Facets. Here mark JSF as selected, and as we are going to use the EJB as a dependency for web application we don't need to select JPA or RS as of now. Press Apply and move to option Java Build Path in the sidebar. Here click Add and select EJB project we created to add as dependency. Press OK and exit the wizard.
index file
Now, out set up is nearly complete, all we need is to see that our project deployment is working. So, right click the web application and create an XHTML file. Name it as index.xhtml(make sure file is created in directory Web Content, or you may create sub directory in the Web Content). select the default xhtml template and write Hello World in the body. The page shall be looking something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"> 

<h:head></h:head> 
<h:body> 
Hello World!
</h:body> 
</html>
When you add the JSF facet to the project a JSF configuration file is created in WEB-INF by the name of faces-config.xml, make sure this file is there. And an entry is marked in your web.xml file under servlet tag. Just make sure initially it looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>DemoWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
Our key concern is to make sure that URL-pattern looks like "/*" instead of "/faces/*" because in other case you would need to place the xhtml files inside faces directory.
We are all set now, right click the EAR project and Run As > Run on server. the result will print Hello World on the welcome page.
Hello World

Focus HTML element after AJAX call with PrimeFaces

Fixing focus issue

The first scenario describes the situation where the focus must be placed in a certain field which is updated by the AJAX call.  But it is always the same field regardless of the result of the server side code.
This can easily achieved by using the oncomplete attribute of the PrimeFaces widget who initiated the AJAX call.
This is JavaScript code which is performed when the AJAX call was successful (and thus there was no error) and the replacement of the DOM elements in the browser is completed.
So at this point the DOM tree is stable again and we can give a field the focus.
oncomplete="PrimeFaces.focus('frm:newProjectName');"
The above snippet places the focus in the newProjectName field when the AJAX is finished.

Conditionally define the focus

Another scenario is where the fields that needs to get the focus needs to be defined conditionally.  Lets examen this use case better with some screen example.
In the above case, we have a field to enter some kind of code.  And depending on the code, we sometimes needs additional information from the user.
So, there will be an AJAX handler (p:ajax) which call some java listener method to perform the server side functionality which defines if there is additional information needed. 
Initially the 'additional' field is disabled, so the focus is not placed in this field by the browser. And since the field is replaced by the AJAX call in the DOM tree, the focus would be lost anyway.
But from within the Java listener method, we can execute some JavaScript when the AJAX call is finished.  This is one of the great features of PrimeFaces.
So, by adding the following code in the Java method, we can place the focus in the additional field. And within Java it is easy when this focus must be placed there (the conditional aspect of this usecase)

RequestContext.getCurrentInstance().execute("PrimeFaces.focus('frm:additionalInfo');");

Conclusion

The focus and AJAX combination has some conflicts. In the Expert group for JSF 2.3, they are considering some additional tags to handle those situations.
Within PrimeFaces, we saw with 2 usecases that you can manage the problem with the usage of the excellent integration of JavaScript within PrimeFaces. This from within the view (JSF pages) as from within Java.

Monday, October 19, 2015

Creando MySql datasource in Wildfly 9

En la siguiente seri de tutoriales se detalla información paso a paso para la elaboración de una aplicación JavaEE7, desde la creación de su respectivo Datasource hasta la elaboración de un CRUD básico  Las herramientas usadas son: Wildfly 8.x.x, MySql-5.x.x y mysql-connector-5.1.3 3.jar  Se asume que se tiene ya instalado Mysql-server, Phpymyadmin, Eclipse y WildFLy 8 o superior, luego de estar el servidor Wildlfy adherido y confiurado dentro de Elclipse abrimos en un navegador web la siguiente Url http://localhost:9990  y nos dirimimos a la ruta Configuration > Connector > Datasources allí daremos click en Add, allí se desplegara un Wizard el cual nos guiara en los pasos para crear el Datasource



Luego de dar click en Add definimos el nombre de la conexión JNDI Name:school JNDI Name:java:jboss/datasources/school  Asumimos que estamos creado la conexión en base a la base de datos school

Para finalizar el proceso, necesitamos proveer las configuraciones de conexion URL y password
Connection URL: jdbc:mysql://localhost/School
Username: root
Password:

Si despues de haber realizado el testeo de conexión nos devuelve  OK el proceso finaliza exitosamente.


 public class AuthSuperAdminFilter implements Filter {

    private FilterConfig configuration;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.configuration = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (((HttpServletRequest) request).getSession().getAttribute(
                AuthBean.USER_KEY) == null || !((UserBean)((HttpServletRequest) request).getSession().getAttribute(
                AuthBean.USER_KEY)).getRole().equals("superadmin") ) {
            ((HttpServletResponse) response).sendRedirect("../forbidden.xhtml");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        this.configuration = null;
    }

}