Friday, July 26, 2013

Tapestry5 Project with Hibernate Example Project

Hello guys,
  I am going to show an example of how to create a tapestry5 Project to manage employee master details using Grid and beanEditForm Component. The database we are using is postgres. We are using Hibernate to connect to database.

Employee Master
 
 
 Edit Employee Detail



pom.xml
  Setup an empty maven project for eclipse. Once the project is imported to eclipse, create an empty project with org.my.in.sample as project namespace.

Open sample.pom and copy and paste the below code. We need to configure the dependencies
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.my.in</groupId>
    <artifactId>sample</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>sample Tapestry 5 Application</name>
        <dependencies>
        <!-- Too set up an application with a database, change the artifactId below to
             tapestry-hibernate, and add a dependency on your JDBC driver. You'll also
             need to add Hibernate configuration files, such as hibernate.cfg.xml. -->
        <dependency>
            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-core</artifactId>
            <version>${tapestry-release-version}</version>
        </dependency>

        <!-- This adds automatic compression of JavaScript and CSS when in production mode. -->
        <dependency>
            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-yuicompressor</artifactId>
            <version>${tapestry-release-version}</version>
        </dependency>

        <!-- Uncomment this to add support for file uploads:

         <dependency>
            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-upload</artifactId>
            <version>${tapestry-release-version}</version>
        </dependency>

        -->

        <!-- A dependency on either JUnit or TestNG is required, or the surefire plugin (which runs the tests)
will fail, preventing Maven from packaging the WAR. Tapestry includes a large number
of testing facilities designed for use with TestNG (http://testng.org/), so it's recommended. -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng-release-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>${easymock-release-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-test</artifactId>
            <version>${tapestry-release-version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Provided by the servlet container, but sometimes referenced in the application
       code. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet-api-release-version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- Provide dependency to the Tapestry javadoc taglet which replaces the Maven component report -->
        <dependency>
            <groupId>org.apache.tapestry</groupId>
            <artifactId>tapestry-javadoc</artifactId>
            <version>${tapestry-release-version}</version>
            <scope>provided</scope>
        </dependency>
<!--           Hibernate Begin             -->
  <dependency>
      <groupId>org.apache.tapestry</groupId>
      <artifactId>tapestry-hibernate</artifactId>
      <version>${tapestry-release-version}</version>
    </dependency>
     <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.2.2.ga</version>
    </dependency>  
    <dependency>
               <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.0</version>
        </dependency>
    <dependency>
      <groupId>geronimo-spec</groupId>
      <artifactId>geronimo-spec-jta</artifactId>
      <version>1.0-M1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.2.1.ga</version>
    </dependency>
  <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>8.3-603.jdbc3</version>
    </dependency>
    
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

    <!--           Hibernate End              -->
    </dependencies>
    <build>
        <finalName>sample</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                    <optimize>true</optimize>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.7.2</version>
                <configuration>
                    <systemPropertyVariables>
                        <tapestry.execution-mode>Qa</tapestry.execution-mode>
                    </systemPropertyVariables>
                </configuration>
            </plugin>

            <!-- Run the application using "mvn jetty:run" -->
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.16</version>
                <configuration>
                    <!-- Log to the console. -->
                    <requestLog implementation="org.mortbay.jetty.NCSARequestLog">
                        <!-- This doesn't do anything for Jetty, but is a workaround for a Maven bug
                             that prevents the requestLog from being set. -->
                        <append>true</append>
                    </requestLog>
                    <systemProperties>
                        <systemProperty>
                            <name>tapestry.execution-mode</name>
                            <value>development</value>
                        </systemProperty>
                    </systemProperties>
                </configuration>
            </plugin>
            
             <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
     <artifactId>tomcat7-maven-plugin</artifactId>
     <version>2.0</version> 
     <configuration>
      <url>${tomcat.manager}</url>
      <server>tomcat7</server>
      <username>${tomcat.manager.username}</username>
      <password>${cargo.remote.password}</password>
      <home>${catalina.home}</home>
      <path>/${project.build.finalName}</path>
      <update>true</update>
       <synchronization>
       <extensions>
        <extension>.html</extension>
        <extension>.class</extension> <!-- if you want to update each time you build with mvn compile -->
       </extensions>
      </synchronization>
       <reloadOnUpdate>true</reloadOnUpdate> 
       </configuration>
    </plugin>
        </plugins>
    </build>

    <reporting/>

    <repositories>

        <!-- This repository is only needed when the Tapestry version is a preview release, rather
             than a final release. -->
        <repository>
            <id>apache-staging</id>
            <url>https://repository.apache.org/content/groups/staging/</url>
        </repository>
    </repositories>

    <properties>
        <tapestry-release-version>5.3.7</tapestry-release-version>
        <servlet-api-release-version>2.5</servlet-api-release-version>
        <testng-release-version>5.14.10</testng-release-version>
        <easymock-release-version>3.0</easymock-release-version>
        <tomcat.manager>http://localhost:8080/manager/text</tomcat.manager>
  <tomcat.manager.username>admin</tomcat.manager.username>
    </properties>
</project>

Configuring Hibernate
Create a new xml file hibernate.cfg.xml file. In this file we are going to configure for hibernate for postgres database. We are using a local database here


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 <session-factory>
  <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
  <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
  <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/testing</property>
  <property name="hibernate.connection.username">postgres</property>
  <property name="hibernate.connection.password">postgres</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <mapping resource="sample.hbm.xml" />
 </session-factory>
</hibernate-configuration>

Create a new file sample.hbm.xml and define the entities as shown below. There are 2 entities we are going to use. one is for showing and another is for CRUD Operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping> 

<class name="org.my.in.sample.entities.EmployeeMasterListVO">
  <id name="id" type="long" />
  <property name="empId" type="long" />
  <property name="empName" type="string" />
  <property name="createdBy" type="long" />
  <property name="createdDate" type="timestamp" />
 </class>
 
 <class name="org.my.in.sample.entities.EmployeeMasterEntityEO" table="employeemaster">
  <id name="id" type="long" >
    <generator class="increment"></generator>
  </id>
  <property name="empId" type="long" />
  <property name="empName" type="string" />
  <property name="createdBy" type="long" />
  <property name="createdDate" type="timestamp" />
 </class>  
</hibernate-mapping>

Entity
EmployeeMasterListVO
First we are going to create an entity to view the list of employees.. Create a namespace org.my.in.entities in src/main/java. create a class EmployeeMasterListVO under it with the below code. Marking an object as @Nonvisual will hide it in the page.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package org.my.in.sample.entities;


import java.util.Date;

import javax.persistence.*;

import org.apache.tapestry5.beaneditor.NonVisual;
import org.apache.tapestry5.beaneditor.Validate;

@Entity
public class EmployeeMasterListVO
{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @NonVisual
  private long id;

  @Validate("required")
  private String empName;

  @Validate("required")
  private long empId;
  
  private long createdBy;
  
  private Date createdDate; 


 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getEmpName() {
  return empName;
 }
 
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 
 public long getEmpId() {
  return empId;
 }
 
 public void setEmpId(long empId) {
  this.empId = empId;
 }

 public long getCreatedBy() {
 return createdBy;
 }

 public void setCreatedBy(long createdBy) {
  this.createdBy = createdBy;
 }
 
 public Date getCreatedDate() {
  return createdDate;
 }
 
 public void setCreatedDate(Date createdDate) {
  this.createdDate = createdDate;
 }

 }

EmployeeMasterEntityEO
Now we are going to create an entity for create, update, delete operations for employees..  Create a class EmployeeMasterEntityEO with the below code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package org.my.in.sample.entities;


import java.util.Date;

import javax.persistence.*;
import org.apache.tapestry5.beaneditor.NonVisual;
import org.apache.tapestry5.beaneditor.Validate;


@Entity
@Table(name="employeemaster")
public class EmployeeMasterEntityEO
{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @NonVisual
  private long id;

  @Validate("required")
  private String empName;

  @Validate("required")
  private long empId;
  
  private long createdBy;
  
  private Date createdDate; 


 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getEmpName() {
  return empName;
 }
 
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 
 public long getEmpId() {
  return empId;
 }
 
 public void setEmpId(long empId) {
  this.empId = empId;
 }

 public long getCreatedBy() {
 return createdBy;
 }

 public void setCreatedBy(long createdBy) {
  this.createdBy = createdBy;
 }
 
 public Date getCreatedDate() {
  return createdDate;
 }
 
 public void setCreatedDate(Date createdDate) {
  this.createdDate = createdDate;
 }

 }

Page - EmployeeMasterPG
Employee Master Page. In package org.my.in.sample under src/main/resources create a page EmployeeMasterPG.tml. This is the page where we will be showing Employee master details. Copy and paste the contents of below into the page .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<html t:type="layout" title="sample Index"
      t:sidebarTitle="Framework Version"
      xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
      xmlns:p="tapestry:parameter">

   <t:grid source="employees" row ="employee" add="delete">
      <p:empIdCell>
                <t:pagelink page="CreateEmployeeMasterPG" context="employee.id">${employee.empId}</t:pagelink>
         </p:empIdCell>
          <p:deletecell>
                <t:actionlink t:id="delete" context="encrypt(employee.id)">Delete</t:actionlink>
            </p:deletecell>
        
         <p:empty>
              <p>There are no users to display; you can <t:pagelink page="createEmployeeMasterPG">add some</t:pagelink>.</p>
          </p:empty>
      </t:grid>
   <br/>
   <a t:type="eventlink" t:event="CreateEmployee" href="#">Create Employee</a><br/><br/>
   
</html>

If you notice we are creating a grid to show the results using the Grid Component

Java - EmployeeMasterPG.java
       Create a new java file in src/main/java folder inside namespace org.my.in.sample.pages

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.my.in.sample.pages;

import org.my.in.sample.Util.AESencrp;
import org.my.in.sample.entities.EmployeeMasterEntityEO;
import org.my.in.sample.entities.EmployeeMasterListVO;
import org.my.in.sample.model.EmployeeMasterAM;

import java.util.List;

import javax.inject.Inject;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.services.Request;
import org.hibernate.Hibernate;
import org.hibernate.Session;


public class EmployeeMasterPG 
{
  @Inject
     private Session session;
  
  @InjectPage
  private CreateEmployeeMasterPG createEmployeeMaster;
  
  @Property
  private EmployeeMasterListVO employee;
  

  private String id;
  

  private static final String serialVersionUID = "EmployeeMaster";

  @SuppressWarnings("unchecked")
  public List<EmployeeMasterListVO> getAddresses()
     {
   List<EmployeeMasterListVO> emp = session.createSQLQuery("SELECT id, empId, empName, createdBy, createdDate FROM employeemaster")
      .addEntity(EmployeeMasterListVO.class)
      .list();

         System.out.println(emp.size());
   return emp;
     }
  
  void prepareForRender ()
  {
   //System.out.println(request.getSession(false).g)
  }
  

  Object onCreateEmployee()
  {
   return createEmployeeMaster;
  }
  
  void onActionFromDelete(long id)
  {
   EmployeeMasterAM.delete(id);
  }

  
}

Model -EmployeeMasterAM
Create a namespace org.my.in.sample.model in src/main/java folder. Inside it create a class file named EmployeeMasterAM.java with the below code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package org.my.in.sample.model;

import java.util.List;

import org.my.in.sample.entities.EmployeeMasterEntityEO;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class EmployeeMasterAM 
{
 public static void delete(long id)
 {
  Configuration configuration = new Configuration();
        SessionFactory  sessionFactory = configuration.configure().buildSessionFactory();
     Session session = sessionFactory.openSession();
     
  EmployeeMasterEntityEO employeeMaster;
  List<EmployeeMasterEntityEO> empList = session.createSQLQuery("SELECT id, empId, empName, createdBy, createdDate FROM employeemaster where id =" + id)
     .addEntity(EmployeeMasterEntityEO.class)
     .list();

     org.hibernate.Transaction transaction = session.beginTransaction();
     transaction.begin();
     if(empList != null && empList.size()>0)
     {
      System.out.println("Delete id-" +empList.get(0).getId());
   session.delete(empList.get(0));
     }
  transaction.commit();
  session.close();
 }
}

Template - CreateEmployeeMasterPG.tml
Now we have created page to list the Employees. Now we will create a page to edit the employees and update it. Page - CreateEmployeeMasterPG.tml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<html t:type="layout" title="Employee Master"
      t:sidebarTitle="Framework Version"
      xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
      xmlns:p="tapestry:parameter">
 
  <t:beaneditform t:id="employeeMasterForm" object="employeeMaster" t:submitLabel="Save"
 reorder="empName,empId">
 </t:beaneditform>
 <form t:type="form" t:id="employeeMasterEdit">
   <t:textField t:id="hiddenId" value="hiddenId" type="hidden" />
     </form>
  
</html>

Java-CreateEmployeeMasterPG.Java
Now we will create a java page for the same in org.my.in.sample.pages namespace under src/main/resources

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package org.my.in.sample.pages;

import org.my.in.sample.Util.AESencrp;
import org.my.in.sample.entities.EmployeeMasterEntityEO;

import java.util.List;

import javax.inject.Inject;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.InjectPage;

import org.my.in.sample.model.CreateEmployeeMasterAM;

import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.TextField;

import org.apache.tapestry5.services.Request;
import org.hibernate.Session;



public class CreateEmployeeMasterPG 
{
  
  @Inject
     private Session session;
  
  @Inject 
  private Request request; 
  
  @Property
  @Persist
  private String hiddenId;
  
  @InjectPage
  private EmployeeMasterPG employeeMasterPage;
  
  
  
  @Property
  @Persist(PersistenceConstants.FLASH)
  private EmployeeMasterEntityEO employeeMaster;
  
 
  void onActivate(long id)
  {
   this.hiddenId =id;
   if(id >0) 
   {
    List<EmployeeMasterEntityEO> emp = session.createSQLQuery("SELECT id, empId, empName, createdBy, createdDate FROM employeemaster where id =" + id)
       .addEntity(EmployeeMasterEntityEO.class)
       .list();
    employeeMaster = emp.get(0);
          System.out.println("size" + emp.size()); 
   }
  }
  

     Object onSuccess()
     {
      System.out.println("On Success -id is " + hiddenId);
      long id = hiddenId;
      if(id > 0)
       employeeMaster.setId(id);
      CreateEmployeeMasterAM.save(employeeMaster);
         return employeeMasterPage;
     }


 
}

Model -CreateEmployeeMasterAM
Now we will create model page CreateEmployeeMasterAM.java under org.my.in.sample.model

 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package org.my.in.sample.model;

import java.util.List;

import org.my.in.sample.entities.EmployeeMasterEntityEO;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class CreateEmployeeMasterAM 
{
 public static void save(EmployeeMasterEntityEO employeeMaster)
 {
  Configuration configuration = new Configuration();
        SessionFactory  sessionFactory = configuration.configure().buildSessionFactory();
     Session session = sessionFactory.openSession();
     org.hibernate.Transaction transaction = session.beginTransaction();
     transaction.begin();
     System.out.println("id-" +employeeMaster.getId());
  session.saveOrUpdate(employeeMaster);
  transaction.commit();
  session.close();
 }
 
}

No comments: