Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Sunday, 14 April 2013

ZK MVVM Form Binding CRUD with Spring and Hibernate - Part 11

Posted on 03:52 by Unknown

Storing Image in the Database

        


Left hugMy Sincere thanks to Joshi who helped me in this article

In the last article, we have successfully integrated jQuery plugin with ZK. Now we will see how to upload a image file and store in the database and display back to the UI.

Step 1:
First we will add one more column in the mysql table userprofile. The column name will be “userPhoto” and type will be longblob. Here is the structure.
image
Step 2:
Next we need to modify our bean UserProfile. Here is the modified file UserProfile.java in which we have added the new column.

package zkexample.domain;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.NamedQuery;

@Entity
@Table(name = "userprofile")
@NamedQuery(name = "UserProfile.findUserByUserID", query = "SELECT usr FROM UserProfile as usr WHERE usr.userLoginID = ?")
public class UserProfile implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

private String firstName;
private String lastName;
private String middleName;
private String userAccountNumber;
private String SSN;
private String address1;
private String address2;
private String city;
private String State;
private String zipCode;
private String email;
private String userLoginID;
private String password;
private Integer system;
private String theme;

@Column(name = "userPhoto")
@Lob
private byte[] userPhoto;

@Temporal(TemporalType.DATE)
private Date DOB;

public long getId() {
return id;
}

public void setId(long 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 getMiddleName() {
return middleName;
}

public void setMiddleName(String middleName) {
this.middleName = middleName;
}

public String getUserAccountNumber() {
return userAccountNumber;
}

public void setUserAccountNumber(String userAccountNumber) {
this.userAccountNumber = userAccountNumber;
}

public Date getDOB() {
return DOB;
}

public void setDOB(Date dOB) {
DOB = dOB;
}

public String getSSN() {
return SSN;
}

public void setSSN(String sSN) {
SSN = sSN;
}

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) {
State = state;
}

public String getZipCode() {
return zipCode;
}

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

public String getEmail() {
return email;
}

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

public String getUserLoginID() {
return userLoginID;
}

public void setUserLoginID(String userLoginID) {
this.userLoginID = userLoginID;
}

public String getPassword() {
return password;
}

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

public Integer getSystem() {
return system;
}

public void setSystem(Integer system) {
this.system = system;
}

public String getTheme() {
return theme;
}

public void setTheme(String theme) {
this.theme = theme;
}

public byte[] getUserPhoto() {
return userPhoto;
}

public void setUserPhoto(byte[] userPhoto) {
this.userPhoto = userPhoto;
}

}



Step 3:
Next we will modify our zul file such as it will have one image file and two buttons(one button is to add image and other button is to remove the image if need). In the UserCRUD.zul file, next heading “Personel Information” , add the following lines.
You can also get the complete source at the bottom link provided.


	<div>
<image content="@bind(vm.myImage)" width="150px"
style="overflow:auto;z-index:999;position:absolute;right:30px;top:56px;width:150px;height:140px;background-color:#ff99cc;" />
<button Label="Add" sclass="mybutton button theme small"
width="40px" upload="true,maxsize=300"
visible="@load(not vm.makeAsReadOnly)"
style="position:absolute;right:115px;top:200px;"
onUpload="@command('upload', upEvent=event)" mold="trendy" />
<button Label="Del" sclass="mybutton button theme small"
visible="@load(not vm.makeAsReadOnly)" width="40px"
style="position:absolute;right:30px;top:200px;"
onClick="@command('removeImage')" mold="trendy" />
</div>



Step 3:
Next in the images folder, add image male.png. You can download the source at the bottom and use that image.

image
Step 4:
Next we need to modify the VM. Open the UserCRUDVM.java and do the changes
Change : 1



Add the following two new methods.


@Command
@NotifyChange("myImage")
public void removeImage() {

myImage = null;
}

@Command
@NotifyChange("myImage")
public void upload(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {

UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
Media media = upEvent.getMedia();
int lengthofImage = media.getByteData().length;
if (media instanceof Image) {
if (lengthofImage > 500 * 1024) {
Messagebox
.show("Please Select a Image of size less than 500Kb.");
return;
} else {
myImage = (AImage) media;// Initialize the bind object to
// show image in zul page and
// Notify it also
}
} else {
Messagebox.show("The selected File is not an image.");
}
}
}


Change 2:
Change the Method initSetup as follows


@AfterCompose
@NotifyChange("myImage")
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedRecord") UserProfile userProfile,
@ExecutionArgParam("recordMode") String recordMode,
@ExecutionArgParam("centerArea") Center centerArea)
throws IOException {

Selectors.wireComponents(view, this, false);
setRecordMode(recordMode);
CRUDService = (CRUDService) SpringUtil.getBean("CRUDService");
this.centerArea = centerArea;

Themes.register("bluetheme", ThemeOrigin.FOLDER);
Themes.register("greentheme", ThemeOrigin.FOLDER);
Themes.register("browntheme", ThemeOrigin.FOLDER);
Themes.register("purpletheme", ThemeOrigin.FOLDER);
Themes.register("redtheme", ThemeOrigin.FOLDER);



String[] themes = Themes.getThemes();
themes = Arrays.copyOf(themes, themes.length + 1);

// Attempting to switch to a theme that is not registered
// will switch to the default theme (i.e. breeze)
themes[themes.length - 1] = "unknown";
_themes = new ListModelList<String>(themes);

currentTheme = Themes.getCurrentTheme();
myImage = new AImage(Executions.getCurrent().getDesktop().getWebApp().getRealPath("/images") +"/male.png" );
if (recordMode.equals("NEW")) {
this.selectedRecord = new UserProfile();
this.selectedRecord.setSystem(0);
}

if (recordMode.equals("EDIT")) {
this.selectedRecord = userProfile;
if (this.selectedRecord.getUserPhoto() != null)
myImage = new AImage("userPhoto",
this.selectedRecord.getUserPhoto());
}

if (recordMode == "READ") {
setMakeAsReadOnly(true);
this.selectedRecord = userProfile;
if (this.selectedRecord.getUserPhoto() != null)
myImage = new AImage("userPhoto",
this.selectedRecord.getUserPhoto());
}
}


Change 3:
Change the Savethis Method as follows


	@Command
public void saveThis(@BindingParam("action") Integer action) {
if (myImage != null) {
byte[] bFile = myImage.getByteData();
this.selectedRecord.setUserPhoto(bFile);
} else
this.selectedRecord.setUserPhoto(null);
CRUDService.Save(this.selectedRecord);
if (action == 0) {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}
if (action == 1) {
this.selectedRecord = new UserProfile();
BindUtils.postNotifyChange(null, null, UserCRUDVM.this,
"selectedRecord");

}
}

Step 5:
Now you can run the application, login and Click Add new and you can see the following output.
image

Step 6:
Finally, we will one more option such after each DB operation such as New/Edit/Delete, we will show the confirmation message. In the MyLib.java file, add the below function



	public static void showSuccessmessage() {
Clients.showNotification("Operation Completed Successfully",
Clients.NOTIFICATION_TYPE_INFO, null, "top_center", 4100);
}

Now call this Function in the UserListVM.Java after delete as follows":


@Override
public void onConfirmClick(String code, int button) {
if (code.equals("deleteFirstConfirm") && button == Messagebox.YES) {
MyLib.confirm(
"deleteSecondConfirm",
"The Selected user \""
+ selectedItem.getUserLoginID()
+ "\" will be permanently deleted and the action cannot be undone..?",
"Confirmation", this);
}
if (code.equals("deleteSecondConfirm") && button == Messagebox.YES) {

CRUDService.delete(selectedItem);

allReordsInDB.remove(allReordsInDB.indexOf(selectedItem));
BindUtils.postNotifyChange(null, null, UserListVM.this, "dataSet");
MyLib.showSuccessmessage();

}
}

Similarly, call this in SaveThis in UserCRUDVM.Java as follows


@Command
public void saveThis(@BindingParam("action") Integer action) {
if (myImage != null) {
byte[] bFile = myImage.getByteData();
this.selectedRecord.setUserPhoto(bFile);
} else
this.selectedRecord.setUserPhoto(null);
CRUDService.Save(this.selectedRecord);
MyLib.showSuccessmessage();
if (action == 0) {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}
if (action == 1) {
this.selectedRecord = new UserProfile();
BindUtils.postNotifyChange(null, null, UserCRUDVM.this,
"selectedRecord");

}
}


You can control the look and feel of the notification message. Add the below lines in Style.css


/* ----------------------------------------------------------------------------------------------------------------------- */
/* Start: Auto Close Notification message box
/* ----------------------------------------------------------------------------------------------------------------------- */
.z-notification .z-notification-cl,.z-notification .z-notification-cnt {
height: 30px;
width: 250px;
}

.z-notification-info .z-notification-cl {
background-color: #ADD8E6;
}

.z-notification .z-notification-cl {
color: white;
}

.z-notification .z-notification-cnt {
background: none repeat scroll 0 center transparent;
font-size: 14px;
font-weight: normal;
margin: 0 !important;
overflow: hidden;
}

In Next Part 12, we will see how to validate user inputs using hibernate validator


You can download the source from here.

You can see the demo here :  user id wing and password is wing



        

Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • EDI 5010 Documentation 837 Professional - Loop 2010BB Payer Name
    2010BB Payer Name          In this loop, all the information will be taken from Insurance master screen. Take a look of our sample screen...
  • EDI 5010 Documentation–837 - BHT - Beginning of Hierarchical Transaction
    BHT – Beginning of Hierarchical Transaction Loop Seg ID Segment Name Format Length Ref# Req Value   BHT Beginning of Hier...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...
  • ZK Passing Parameter between two files using MVVM–Part 1
    Overview This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern .This article will fo...
  • MVVM Command annotation and Notify change example
    Here is an example, how to pass parameter on a zul through MVVM Command binding annotation. ZK URL http://books.zkoss.org/wiki/ZK%20Develo...
  • History of Present Illness
    HPI - One of the main component of Clinical History. What is an HPI ? The history of present illness (HPI) is a chronological description...
  • Patient Demographics
    Patient browse (search) is the key element for any EMR / PMS Software. In my past 15 years experience, i involved more than 5 times in desig...
  • ViewModel Class Java Annotation @Init, @NotifyChange, @Command
    In following sections we'll list all syntaxes that can be used in implementing a ViewModel and applying ZK bind annotation. The ZK binde...
  • Good Website Design Links
    Form Design Label Placement in Forms International Address Fields in Web Forms 40 Eye-Catching Registration Pages blog-comment-form-...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ▼  2013 (105)
    • ►  December (3)
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ▼  April (14)
      • EDI 270–5010 Documentation - ISA – Interchange Con...
      • EDI 270 - 5010 Health Care Eligibility/Benefit Inq...
      • ZK MVVM Form Binding CRUD with Spring and Hibernate
      • ZK MVVM Form Binding CRUD with Spring and Hibernat...
      • Login form CSS
      • ZK MVVM Form Binding CRUD with Spring and Hibernat...
      • ZK MVVM Form Binding CRUD with Spring and Hibernat...
      • ZK MVVM Form Binding CRUD with Spring and Hibernat...
      • ZK MVVM Form Binding CRUD with Spring and Hibernat...
      • ZK + Spring Security Custom Login form
      • ZK + Spring Security Login form–Part 5
      • ZK MVC CRUD With Spring 3 + JPA + Hibernate 4 Enti...
      • Medical Billing Process in detail
      • Clearing House
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ►  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ►  August (26)
    • ►  July (6)
    • ►  June (37)
    • ►  May (30)
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile