Select only few columns in Hibernate create query API

 

Step : 1

Set up Java + Hibernate Environment as by this post.

image

Step : 2

Alter our patient table as shown

image

Step : 3

Now let go back to our patient.java and add the columns as follows

package mypack;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Transient;

@Entity
@Table(name = "patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;
private String password;
private String email;
private String address1;
private String address2;
private String city;
private String state;
private String zipCode;


@Transient
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Id
@GeneratedValue
@Column(name = "ID")
public Integer getId() {
return id;
}

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

@Column(name = "firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name = "lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getAddress1() {
return address1;
}

public void setAddress1(String address1) {
this.address1 = address1;
}

public String getAddress2() {
return address2;
}

public void setAddress2(String address2) {
this.address2 = address2;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getZipCode() {
return zipCode;
}

public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}


}


Step : 4



Modify our Test.java file as follows


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Utility.HibernateUtil;

public class Test {


public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List<patient> allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
HibernateUtil.CommitTransaction();
}


}


Step : 5



Please remember from the above step, it will retrieve all the columns from the DB, you can check this by printing each value. But suppose if we want to select Firstname, lastname, then how we can do that ?  Let us try now


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Utility.HibernateUtil;

public class Test {


public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List<patient> allpatients = null;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("Select firstName, lastName from patient");
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
allpatients = q1.list();
HibernateUtil.CommitTransaction();
}


}


If we now run this, then it will throw error, just let us remove the for loop and see


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Utility.HibernateUtil;

public class Test {


public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List<patient> allpatients = null;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("Select firstName, lastName from patient");
allpatients = q1.list();
HibernateUtil.CommitTransaction();
}


}


Now it will compile and run even though there is no output.


So what is happening ?  Here is the concept


if you use select, then it becomes Native SQL Query. So the output will not be your collection of patient objects, instead of that it will return list of object arrays. So we need to change our for loop as follows


package mypack;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Utility.HibernateUtil;

public class Test {


public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("Select firstName, lastName from patient");
allpatients= q1.list();
for (Iterator it = allpatients.iterator(); it.hasNext(); ) {
Object[] myResult = (Object[]) it.next();
String firstName = (String) myResult[0];
String lastName = (String) myResult[1];
System.out.println( "Found " + firstName + " " + lastName );
}
HibernateUtil.CommitTransaction();
}


}


Now if you run , you can see the output as follows


Hibernate: select patient0_.firstname as col_0_0_, patient0_.lastname as col_1_0_ from patient patient0_
Found Simth John
Found ROBERT DAVID
Found RICHARD JOSEPH
Found Mark Anderson


 



Step : 6



What is the alternate way to retrieve as patient objects ?


Here you go


Query q1 = session.createQuery("Select new patient(firstName,lastName) from patient");


Before this step, we should have proper constructor to create object with only two values. Now let us go back to our patient.java and add the constructor as follows


package mypack;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Transient;

@Entity
@Table(name = "patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;
private String password;
private String email;
private String address1;
private String address2;
private String city;
private String state;
private String zipCode;

//Our default Constructor
public patient()
{

}

//constructor with only two columns
public patient(String fname, String lname)
{
this.firstName= fname;
this.lastName = lname;
}

@Transient
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Id
@GeneratedValue
@Column(name = "ID")
public Integer getId() {
return id;
}

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

@Column(name = "firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name = "lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getAddress1() {
return address1;
}

public void setAddress1(String address1) {
this.address1 = address1;
}

public String getAddress2() {
return address2;
}

public void setAddress2(String address2) {
this.address2 = address2;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getZipCode() {
return zipCode;
}

public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}


}


 


Step : 7



Let us modify our test.java file as follows


package mypack;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import Utility.HibernateUtil;

public class Test {


public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("Select new patient(firstName,lastName) from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
System.out.println(pt.getFirstName());
}
HibernateUtil.CommitTransaction();
}

}


Now you can run and see the output. Now it retrieves as patient objects

ZK MVVM CRUD - Part 1

Step 1 :

Set up the ZK + Hibernate setup as explained in this post.

Step 2 :

Initial Project structure
image

Step 3:

Create Mysql Table as follows
CREATE TABLE `practice` (
  `Practice_ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `PRACTICE_NAME` VARCHAR(255) DEFAULT NULL,
  `NPI_NUMBER` VARCHAR(255) DEFAULT NULL,
  `EMAIL` VARCHAR(255) DEFAULT NULL,
  `ADDRESS1` VARCHAR(255) DEFAULT NULL,
  `ADDRESS2` VARCHAR(255) DEFAULT NULL,
  `CITY` VARCHAR(255) DEFAULT NULL,
  `COUNTRY_GEO` VARCHAR(255) DEFAULT NULL,
  `POSTAL_CODE` VARCHAR(255) DEFAULT NULL,
  `POSTAL_CODE_EXT` VARCHAR(255) DEFAULT NULL,
  `STATE_PROVINCE_GEO` VARCHAR(255) DEFAULT NULL,
  `FAX_NUMBER` VARCHAR(255) DEFAULT NULL,
  `OFFICE_EXT` VARCHAR(255) DEFAULT NULL,
  `OFFICE_PHONE` VARCHAR(255) DEFAULT NULL,
  `PracticeLoginURL` VARCHAR(25) NOT NULL,
  `IS_ACTIVE` BIT(1) DEFAULT NULL,
  `CREATED_BY` BIGINT(20) DEFAULT NULL,
  `CREATE_TX_TIMESTAMP` DATETIME NOT NULL,
  `UPDATE_BY` BIGINT(20) DEFAULT NULL,
  `UPDATED_TX_TIMESTAMP` DATETIME DEFAULT NULL,
  PRIMARY KEY  (`Practice_ID`),
  UNIQUE KEY `UniqueLoginURL` (`PracticeLoginURL`)
) ENGINE=INNODB DEFAULT CHARSET=utf8


Insert some records as follows

INSERT INTO practice(practice_name,city,POSTAL_CODE,STATE_PROVINCE_GEO)
VALUES('eCosmos','City1','1111','St1')

INSERT INTO practice(practice_name,city,POSTAL_CODE,STATE_PROVINCE_GEO,PracticeLoginURL)
VALUES('bPractice2','City2','2222','St2','url1')

INSERT INTO practice(practice_name,city,POSTAL_CODE,STATE_PROVINCE_GEO,PracticeLoginURL)
VALUES('cPractice2','City2','2222','St2','url2')

INSERT INTO practice(practice_name,city,POSTAL_CODE,STATE_PROVINCE_GEO,PracticeLoginURL)
VALUES('dPractice2','City2','2222','St2','url3')



Step 4:



Prepare the View Part in MVVM . i.e create the ZUL File as follows

image

Here is the source code for practiceList.zul file

<?page title="Practice List" contentType="text/html;charset=UTF-8"?>
<zk>

    <window title="Practice List" border="normal">

        <div>
            <button label="Add Practice" />
        </div>
        <separator />
        <groupbox height="40px">
            <label value="Practice Name" />
            <space />
            <space />
            <textbox id="practicefilter" cols="50" />
            <button id="gobutton" label="Go" />
            <space spacing="20px" />
            <checkbox id="activechk" label="Show only active"
                checked="true" />
            <space spacing="20px" />
        </groupbox>
        <separator />
        <listbox id="PracticeList">
            <listhead sizable="true">
                <listheader label="Practice Name" sort="auto" />
                <listheader label="City" sort="auto" />
                <listheader label="State" sort="auto" />
                <listheader label="Zip Code" sort="auto" />
            </listhead>
        </listbox>
    </window>
</zk>


Remember, we did not put any binding concept at this point , we will do it later stage. Now just run this zul file and check whether you get the following output

image

Step 5:


Now let us create Java Bean Pojo for Practice as shown

image

Here is the Code


package domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "practice")
public class Practice {

    private Integer practiceID;
    private String practiceName;
    private String city;
    private String ZipCode;
    private String state;
    private Integer isActive; 

    @Id
    @GeneratedValue
    @Column(name = "PRACTICE_ID")
    public Integer getPracticeID() {
        return practiceID;
    }

    public void setPracticeID(Integer practiceID) {
        this.practiceID = practiceID;
    }

    @Column(name = "PRACTICE_NAME")
    public String getPracticeName() {
        return practiceName;
    }

    public void setPracticeName(String practiceName) {
        this.practiceName = practiceName;
    }

    @Column(name = "CITY")
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Column(name = "POSTAL_CODE")
    public String getZipCode() {
        return ZipCode;
    }

    public void setZipCode(String zipCode) {
        ZipCode = zipCode;
    }

    @Column(name = "STATE_PROVINCE_GEO")
    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Column(name = "IS_ACTIVE")
    public Integer getIsActive() 
    {
        if (isActive== null)
            return 1;
        else
            return isActive;
    }

    public void setIsActive(Integer isActive) {
        this.isActive = isActive;
    }

}



Since we are done with Mapping class, we need tell this to hibernate. Let us do this in the hibernate.cfg.xml

Now go back to hibernate.cfg.xml, add the following line for the mapping class section


<!-- Mapping Classes -->
    <mapping class="domain.Practice" />


Step 6:


Now let us create our DAO Class. Please remember still we didn't touch the MVVM + Data binding. Just we are going reverse and keep every thing is ready before we connect our VIEW with MVVM Data binding

Let us create our practiceDAO Class as shown

image

package DomainDAO;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import domain.Practice;

import HibernateUtilities.HibernateUtil;

public class practiceDAO {

    public List<Practice> getListingItems() {

        List<Practice> practiceListing = null;

        try {
            Session session = HibernateUtil.beginTransaction();
            Query q1 = session.createQuery("from Practice ");
            practiceListing = q1.list();
            HibernateUtil.CommitTransaction();
        } catch (RuntimeException e) {
            if (HibernateUtil.getSession().getTransaction() != null) {
                HibernateUtil.rollbackTransaction();
            }
            e.printStackTrace();
        }
        return practiceListing;
    }
}


Step 7:


Now let us move to MVVM. Now we will create ViewModel as shown here.

image

Here is the code PracticeListVM


package UIVMs;

import domain.Practice;
import java.util.List;
import DomainDAO.practiceDAO;
public class PracticeListVM {

    private List<Practice> AllPracticeInDB = null;
    public List<Practice> getprlist() {
        AllPracticeInDB= new practiceDAO().getListingItems();
        return AllPracticeInDB;
    }
}
    
    



Step 8:


Now let us modify our view practiceList.zul to take care of MVVM + New data binding

<?page title="Practice List" contentType="text/html;charset=UTF-8"?>
<zk>

    <window apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vm') @init('UIVMs.PracticeListVM')">
        <div>
            <button label="Add Practice" />
        </div>
        <separator />
        <groupbox height="40px">
            <label value="Practice Name" />
            <space />
            <space />
            <textbox id="practicefilter" cols="50" />
            <button id="gobutton" label="Go" />
            <space spacing="20px" />
            <checkbox id="activechk" label="Show only active"
                checked="true" />
            <space spacing="20px" />
        </groupbox>
        <separator />
        <listbox id="PracticeList"   model="@load(vm.prlist)">
            <listhead sizable="true">
                <listheader label="Practice Name" sort="auto" />
                <listheader label="City" sort="auto" />
                <listheader label="State" sort="auto" />
                <listheader label="Zip Code" sort="auto" />
            </listhead>
            <template name="model" var="p1">
                <listitem>
                    <listcell label="@load(p1.practiceName)" />
                    <listcell label="@load(p1.city)" />
                    <listcell label="@load(p1.state)" />
                    <listcell label="@load(p1.zipCode)" />
                </listitem>
            </template>
            
        </listbox>
    </window>
</zk>


Step 9:


Now run our practiceList.zul file , you should get the following output

image

Next Part 2


Java List and ArrayList


What is Difference between List and ArrayList
For the handling of objects collection in Java, Collection interface have been provided.
This is avail in java.util package.

"List" is an interface, extends collection interface, provides some sort of extra methods
than collection interface to work with collections. Where as "ArrayList" is the actual
implementation of "List" interface.

So both the following are correct
List x= new ArrayList(); or ArrayList x= new ArrayList();


List:
List is an interface in collection framework. several classes like ArrayList,
LinkedList implement this interface. List is an ordered collection ,
so the position of an object does matter.

ArrayList:
An ArrayList is a class which can grow at runtime. you can store java objects in an ArrayList
and also add new objects at run time.
you will use ArrayList when you dont have to add or remove objects frequently from it.
Because when you remove an object, all other objects need to be repositioned inside the ArrayList,
if you have this kind of situation, try using LinkedList instaed.


Example:
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;   public class ArrayToList {
     public static void main(String[] argv) {   String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };   // convert array to list
 List<String> lList = Arrays.asList(sArray);   // iterator loop
 System.out.println("#1 iterator");
 Iterator<String> iterator = lList.iterator();
 while (iterator.hasNext()) {
  System.out.println(iterator.next());
 }   // for loop
 System.out.println("#2 for");
 for (int i = 0; i < lList.size(); i++) {
  System.out.println(lList.get(i));
 }   // for loop advance
 System.out.println("#3 for advance");
 for (String temp : lList) {
  System.out.println(temp);
 }   // while loop
 System.out.println("#4 while");
 int j = 0;
 while (j < lList.size()) {
  System.out.println(lList.get(j));
  j++;
 }
    }
}



import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ListExample {

    public static void main(String[] args) {

        // List Example implement with ArrayList
        List<String> ls=new ArrayList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        Iterator it=ls.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}

Annotate non persistent properties with the @Transient Annotation

In Most of the cases, all the Java bean properties (example, firstname, lastname, email, etc.) that need to be stored to the database. But in some situation, we might have other properties that do not need to be stored in the database. In this case, we need to say to hibernate that do not take this property for all the Database operation. This can be done using @Transient annotation.

By default, all fields in your class will be persisted to the database if possible. If there is a field that should not be recorded in the database, mark that field with the @Transient annotation

Now let us do an example on the above subject

Step 1:

Create the hibernate setup as shown here;

Step 2:

Now let us modify our patient.java by adding a non persistent field

package mypack;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.Transient;

@Entity
@Table(name = "patient")
public class patient {

    private Integer id;
    private String firstName;
    private String lastName;
    private String password;

    @Transient
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Id
    @GeneratedValue
    @Column(name = "ID")
    public Integer getId() {
        return id;
    }

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

    @Column(name = "firstname")
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name = "lastname")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Step 3:

Let us modify test.java to create new patient as follows

package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

import Utility.HibernateUtil;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
createpatient();
getAllRecords();
}

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
HibernateUtil.CommitTransaction();
}

public static void createpatient() {

Session session = HibernateUtil.beginTransaction();
patient p1 = new patient();
p1.setFirstName("Mark");
p1.setLastName("Anderson");
p1.setPassword("1234");
session.save(p1);
HibernateUtil.CommitTransaction();
}

}


Step 4:


Run the test.java as Java Application and the following is the output


Hibernate: insert into patient (firstname, lastname) values (?, ?)
Hibernate: select patient0_.ID as ID0_, patient0_.firstname as firstname0_, patient0_.lastname as lastname0_ from patient patient0_
John
DAVID
JOSEPH
Anderson


Another good example


public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
private Gender g;
private long id;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() { return id; }
public void setId(long id) { this.id = id; }

public Gender getGender() { return g; }
public void setGender(Gender g) { this.g = g; }

@Transient
public boolean isMale() {
return Gender.MALE.equals(g);
}

@Transient
public boolean isFemale() {
return Gender.FEMALE.equals(g);
}
}

MVVM Example 3–List item

Next we will see how to load the list items using MVVM

Tab box with tool bar CSS

 We will see how we can customize the look and feel for Tabbox With toolbar

Change the location of the label in radio element

 Change the location of the label in radio element

Hibernate 4.1.1 will create the column if we misspelled in the annotation

If we misspelled the column name in the annotation, then hibernate will create that column automatically. I don’t know whether we can turn this feature off.

Steps to Reproduce

  1. Setup the environment as said here.
  2. Now go back to patient.java and change @Column(name="firstname") to @Column(name="firtname")
  3. Now run the test java file.
  4. You can see, it will run successfully without any error.
  5. And now go back to db. and if you check the patient table, now you can see one more column added and null inserted for all the records

MVC–CRUD Application with ZK 5 Data Binding

Here is the summary of what we have completed in this subject.
  1. We created new ZK Project, set up the hibernate and created Modal-View- Controller files to display all the record from the DB. Please click here to go that post.
  2. Next, we added filter feature such that if the user type any value, then the list will be filtered accordingly. Please click here to go that post
  3. Next, we’ve seen how to add more search parameters and filter the list. Please click here to go that post
All these are completed without using any data binding concept. Now let us see how we can use ZK 5 Data binding concepts and makes our job easy. If you are new ZK 5 Data binding, then first go here and learn basic stuffs.

Hibernate–Java Environment setup

Environment

  1. Eclipse 3.7 Indigo IDE Download
  2. Hibernate 4.1.1 Download
  3. JavaSE 1.6  Download
  4. MySQL 5.1 Download
  5. JDBC Driver for MySQL ((MySQL-connector-java-5.1.19.zip)) Download
  6. Extract the Hibernate, MySql driver files in a separate folder

 

Step 1:

  1. 1. In the eclipse, Click New –>  Java Project
  2. Enter the Project Name <ExampleXXXX>
  3. Click Next
  4. Goto Libraries Tab as shown

         image 

Click On Add External Jar files. Add the following files from the hibernate folder and MySQL driver folder.

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

image

Click Finish Button

 

Step 2:

Now let us setup the mysql. Create the following table in mysql

image

Insert some values as shown here

image

Step 3:

Now let us create the Patient Java Bean class with JPA Annotations

 

           image

  1. Right Click on Src folder as shown
  2. Select New->Class
  3. Enter package name as mypack and Class name as patient
  4. Here is the Java Bean code
package mypack;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;



@Entity
@Table(name="patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;

@Id
@GeneratedValue
@Column(name="ID")
public Integer getId() {
return id;
}

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

@Column(name="firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name="lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}


Step 4:



Create hibernate.cfg.xml




    1. Right Click on Src folder
    2. Select New –> Other->General->File
    3. Enter the file name as hibernate.cfg.xml
    4. Goto the Source view and paste the following code
    5. image


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Mapping Classes -->
<mapping class="mypack.patient" />

</session-factory>
</hibernate-configuration>


Step 5:



Create Test.java to test all the above are fine.



  1. Right Click on Src->mypack folder
  2. Select New –> Class
  3. Enter the Class Name as Test


image


Test.Java code


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {

try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate SessionFactory**");
System.out.println("----------------------------------------");

List allpatients;

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}


Step 6:


Right click on Test.Java in the Editor window and Select Run as –> Java Application


The output as follows


**Example : Hibernate  SessionFactory**
----------------------------------------
Hibernate: select patient0_.ID as ID0_, patient0_.firstname as firstname0_, patient0_.lastname as lastname0_ from patient patient0_
John
DAVID
JOSEPH


 


 


Step 7:



Now we will move all the hibernate session creation part into separate class and we will reuse whenever we need it.  We will call this as Hibernate Utility class


package Utility;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static Configuration getInitConfiguration() {
Configuration config = new Configuration();
config.configure();
return config;
}

public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtil.getInitConfiguration();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}

public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void CommitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

}


 


Step 8:


Now let us reduce the code in test.java as shown


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

import Utility.HibernateUtil;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
HibernateUtil.CommitTransaction();
}

}

How to refer CSS File in ZK Style tag

In this example, we will see how to create CSS file as separate file and include in zul file to change the look and feel

MVVM Examples–Example 2

Concept

Initialization

The binder is responsible for creating and initializing a ViewModel instance. If you want to perform your own initialization in a ViewModel, you can declare your own initial method by annotating a method with @Init . The Binder will invoke this method when initializing a ViewModel. Each ViewModel can only have one initial
method


MVVM Examples–Example 1

Example 1:
In this example, how we can convert MVC GenericForwardComposer into new MVVM + Data binding

Input Form Validation window


We will see here how to validate all the input elements and show all the message in one window after submit button is clicked.  This can be done using ZK Data binding and CreateComponents method.
This example is based on Executions.CreateComponents. For more example, please check here.
Project Structure
image

Step 1:

ValidationMessage.Java
package MyDomain;

public class ValidationMessage 
{
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}


Step 2:


ValidateWindow.zul

<?xml version="1.0" encoding="UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" arg0="./modalDialog" ?>
<zk>
    <window id="modalDialog" title=" " width="420px" height="auto"
        border="normal" minimizable="false" mode="modal" maximizable="false"
        closable="true" action="hide: slideUp">
        <listbox vflex="1" id="test" model="@{arg.vList}">
            <listhead sizable="true">
                <listheader label="Messages" width="300px" />
            </listhead>
            <!-- define variable p1 here-->
            <listitem self="@{each='p1'}">
                <listcell label="@{p1.Message}" />
            </listitem>
        </listbox>
        <separator />
        <div align="center">
            <button label="Ok" onCreate="self.setFocus(true)"
                onClick="modalDialog.detach()" />
        </div>
    </window>
</zk>




Step 3:


Demo.Zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
    <window id="win" title ="Person" width="420px" height="150px" border="normal"
        minimizable="false" mode="modal" maximizable="false" closable="true"
        apply="MyDomain.DemoComposer" action="show: slideDown;hide: slideUp">

        <grid width="400px">
            <rows>
                <row>
                    First Name:
                    <textbox id="fname"/>
                </row>
                <row>
                    Last Name:
                    <textbox id="lname"/>
                </row>
            </rows>
        </grid>
        <separator />
        <div align="center">
            <button id="Submit" label="Submit" />
        </div>
    </window>
</zk>


Step 4:


DemoComposer.Java

package MyDomain;

import java.util.HashMap;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
import java.util.ArrayList;
import java.util.List;

public class DemoComposer extends GenericForwardComposer {

    private Textbox fname;
    private Textbox lname;

    public void onClick$Submit(Event event) {
        if (IsValidInput())
            alert("All are valid. Now you can Save into DB");

    }

    public boolean IsValidInput() {

        List<ValidationMessage> vList = new ArrayList<ValidationMessage>();

        ValidationMessage v1 = new ValidationMessage();

        if (fname.getValue() == "") {
            v1.setMessage("First Name Cannot be Empty");
            vList.add(v1);
        }

        if (lname.getValue() == "") {
            v1 = new ValidationMessage();
            v1.setMessage("Last Name Cannot be Empty");
            vList.add(v1);
        }

        if (vList.size() > 0) 
        {
            final HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("vList", vList);
            Executions.createComponents("ValidateWindow.zul", null, map);
            return false;
        }
        else
            return true;
        
    }

}


Step 5:


Run the demo.zul and without entering any value , click on submit button as shown

image

Download the source as war file