In this tutorial we will learn about how to delete data from a database table.
JSF Delete Data From Database Table
In this tutorial we will learn about how to delete data from a database table.
Here I am trying to delete a record from the database table. For this we should have a record to delete that is a table in the database which contains some data. So I have created a table into the database as follows :
CREATE TABLE `user1` ( `userId` bigint(10) NOT NULL, `name` varchar(15) NOT NULL, `address` varchar(255) NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 ROW_FORMAT=DYNAMIC
Then inserted some data to the table according to the fields as follows :
INSERT INTO user1(userId, name, address, created_date) VALUES(1,'Deepak','Delhi','2012-10-14') INSERT INTO user1(userId, name, address, created_date) VALUES(2,'Sandeep','Delhi','2012-10-15') INSERT INTO user1(userId, name, address, created_date) VALUES(3,'Rajesh','Mumbai','2012-10-16') INSERT INTO user1(userId, name, address, created_date) VALUES(4,'Chitrasen','Chennai','2012-10-17') INSERT INTO user1(userId, name, address, created_date) VALUES(5,'Ankit','Kolkata','2012-10-18')
So in the database table 'user1' you will see the records are inserted and are displaying like below :
Now you can delete the records from the table. Here I am giving example which will demonstrate you about how to delete a record from the database table. For this I have created two Java files named User.java and the UserBean.java. In the User.java file I have taken some data members and created their setter getter methods and in addition this class contains the delete() method which is further called into the UserBean.java. In the delete() method I have written code for deleting a record. In the UserBean.java file I have created a method named getUserList() which returns the list of record of User. And to delete the record I have called the delete() method of User.java class that deleted the record on taking the action. Then I have created an XHTML file where I have used the <h:dataTable> tag of JSF HTML tag library to display the data into a table and a <h:commandButton> tag inside the <h:form> tag. The <h:command> button is used to perform an action. Here it is used for deleting the record. I have assigned a method to this tag an action for deleting the record from database table.
Directory Structure
Code is given here
User.java
package com.dev.user.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name="user") @RequestScoped public class User { private long userID; private String name; private String address; private Date created_date; public long getUserID() { return userID; } public void setUserID(long userID) { this.userID = userID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getCreated_date() { return created_date; } public void setCreated_date(Date created_date) { this.created_date = created_date; } public void delete(long userID) { PreparedStatement ps = null; Connection con = null; if(userID !=0) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/record", "root", "root"); String sql = "DELETE FROM user1 WHERE userId="+userID; ps= con.prepareStatement(sql); int i = ps.executeUpdate(); if(i >0) { System.out.println("Row deleted successfully"); } } catch(Exception e) { e.printStackTrace(); } finally { try { con.close(); ps.close(); } catch(Exception e) { e.printStackTrace(); } } } } }
UserBean.java
package com.dev.user.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import com.dev.user.model.User; @ManagedBean(name = "userBean") @SessionScoped public class UserBean { List<User> list; PreparedStatement ps = null; Connection con = null; ResultSet rs = null; public List<User> getList() { return list; } public List<User> getUserList() { list = new ArrayList<User>(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/record", "root", "root"); String sql = "select * from user1"; ps= con.prepareStatement(sql); rs= ps.executeQuery(); while (rs.next()) { User usr = new User(); usr.setUserID(rs.getLong("userId")); usr.setName(rs.getString("name")); usr.setAddress(rs.getString("address")); usr.setCreated_date(rs.getDate("created_date")); list.add(usr); Map<Long, Boolean> checked = new HashMap<Long, Boolean>(); List<User> checkedItems = new ArrayList<User>(); for (User item : list) { if (checked.get(item.getUserID())!= null) { checkedItems.add(item); usr.delete(usr.getUserID()); } } } } catch(Exception e) { e.printStackTrace(); } finally { try { con.close(); ps.close(); } catch(Exception e) { e.printStackTrace(); } } return list; } }
index.html
<?xml version="1.0" encoding="UTF-8"?> <!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"> <h:head> <title>index.xhtml</title> </h:head> <h:body> <h1>JSF Delete Data From The Database Table Example</h1> <h:form id="form1"> <h:dataTable value="#{userBean.getUserList()}" var="u" border="1"> <h:column> <f:facet name="header"> User ID </f:facet> #{u.userID} </h:column> <h:column> <f:facet name="header"> Name </f:facet> #{u.name} </h:column> <h:column> <f:facet name="header"> Address </f:facet> #{u.address} </h:column> <h:column> <f:facet name="header"> Created Date </f:facet> #{u.created_date} </h:column> <h:column> <h:commandButton value="DELETE" action="#{user.delete(u.userID)}" /> </h:column> </h:dataTable> </h:form> </h:body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jsfJdbcDelete</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>/faces/*</url-pattern> <url-pattern>*.jsf</url-pattern> <url-pattern>*.xhtml</url-pattern> <url-pattern>*.jsp</url-pattern> </servlet-mapping> <context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> </web-app>
Output
When you will execute the above example you will see the home page as follows :
When you will click on the delete button of respective row it will deleted the record of particular row and then the output will be as follows :
Here I am deleting the 5th row record
[ 0 ] Comments