Tag: Unique key
JSF 2.0 + JDBC integration example
Here’s a guide to show you how to integrate JSF 2.0 with database via JDBC. In this example, we are using MySQL database and Tomcat web container.
Directory structure of this example
1. Table Structure
Create a “customer” table and insert five dummy records. Later, display it via JSF h:dataTable
.
SQL commands
DROP TABLE IF EXISTS `mkyongdb`.`customer`; CREATE TABLE `mkyongdb`.`customer` ( `CUSTOMER_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(45) NOT NULL, `ADDRESS` VARCHAR(255) NOT NULL, `CREATED_DATE` datetime NOT NULL, PRIMARY KEY (`CUSTOMER_ID`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(1, 'mkyong1', 'address1', now()); INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(2, 'mkyong2', 'address2', now()); INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(3, 'mkyong3', 'address3', now()); INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(4, 'mkyong4', 'address4', now()); INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(5, 'mkyong5', 'address5', now());
2. MySQL DataSource
Configure a MySQL datasource named “jdbc/mkyongdb“, follow this article – How to configure MySQL DataSource in Tomcat 6
3. Model Class
Create a “Customer” model class to store the table records.
File : Customer.java
package com.mkyong.customer.model; import java.util.Date; public class Customer{ public long customerID; public String name; public String address; public Date created_date; //getter and setter methods }
4. JDBC Example
A JSF 2.0 managed bean, inject datasource “jdbc/mkyongdb” via @Resource
, and uses normal JDBC API to retrieve all the customer records from database and store it into a List.
File : CustomerBean.java
package com.mkyong; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import com.mkyong.customer.model.Customer; @ManagedBean(name="customer") @SessionScoped public class CustomerBean implements Serializable{ //resource injection @Resource(name="jdbc/mkyongdb") private DataSource ds; //if resource injection is not support, you still can get it manually. /*public CustomerBean(){ try { Context ctx = new InitialContext(); ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mkyongdb"); } catch (NamingException e) { e.printStackTrace(); } }*/ //connect to DB and get customer list public List getCustomerList() throws SQLException{ if(ds==null) throw new SQLException("Can't get data source"); //get database connection Connection con = ds.getConnection(); if(con==null) throw new SQLException("Can't get database connection"); PreparedStatement ps = con.prepareStatement( "select customer_id, name, address, created_date from customer"); //get customer data from database ResultSet result = ps.executeQuery(); List list = new ArrayList(); while(result.next()){ Customer cust = new Customer(); cust.setCustomerID(result.getLong("customer_id")); cust.setName(result.getString("name")); cust.setAddress(result.getString("address")); cust.setCreated_date(result.getDate("created_date")); //store all data into a List list.add(cust); } return list; } }
5. JSF Page dataTable
A JSF 2.0 xhtml page, uses h:dataTable
to display all the customer records in table layout format.
<?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> <h:outputStylesheet library="css" name="table-style.css" /> </h:head> <h:body> <h1>JSF 2.0 + JDBC Example</h1> <h:dataTable value="#{customer.getCustomerList()}" var="c" styleClass="order-table" headerClass="order-table-header" rowClasses="order-table-odd-row,order-table-even-row" > <h:column> <f:facet name="header"> Customer ID </f:facet> #{c.customerID} </h:column> <h:column> <f:facet name="header"> Name </f:facet> #{c.name} </h:column> <h:column> <f:facet name="header"> Address </f:facet> #{c.address} </h:column> <h:column> <f:facet name="header"> Created Date </f:facet> #{c.created_date} </h:column> </h:dataTable> </h:body> </html>
6. Demo
Run it, see output
Download Source Code
Insert Image into Mysql Database through Simple Java Code
Reference Rose India.
This is detailed simple java code that how save image into mysql database. Before running this java code you need to create data base and table to save image in same database. In the example given below we have used database ‘mahendra’ and table ‘save_image’.
Structure of table ‘save_image’
First create database named ‘mahendra’ by query given below:
mysql> create database mahendra; |
and create table by query given below:
CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name varchar(25) default NULL, city varchar(20) default NULL, image blob, Phone varchar(15) default NULL, PRIMARY KEY (`id`) ); |
Save table ‘save_image‘ in database ‘mahendra‘. Before running this java code you need mysql connector jar in the jdk1.6.0_01./lib.
SaveImageToDatabase java file provides full code for uploading image in database.
SaveImageToDatabase.java
import java.sql.*; import java.io.*; class SaveImageToDatabase { public static void main(String[] args) throws SQLException { // declare a connection by using Connection interface Connection connection = null; /* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is mahendra. */ String connectionURL = "jdbc:mysql://localhost:3306/mahendra"; /*declare a resultSet that works as a table resulted by execute a specified sql query. */ ResultSet rs = null; // Declare prepare statement. PreparedStatement psmnt = null; // declare FileInputStream object to store binary stream of given image. FileInputStream fis; try { // Load JDBC driver "com.mysql.jdbc.Driver" Class.forName("com.mysql.jdbc.Driver").newInstance(); /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */ connection = DriverManager.getConnection(connectionURL, "root", "root"); // create a file object for image by specifying full path of image as parameter. File image = new File("C:/image.jpg"); /* prepareStatement() is used for create statement object that is used for sending sql statements to the specified database. */ psmnt = connection.prepareStatement ("insert into save_image(name, city, image, Phone) "+ "values(?,?,?,?)"); psmnt.setString(1,"mahendra"); psmnt.setString(2,"Delhi"); psmnt.setString(4,"123456"); fis = new FileInputStream(image); psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length())); /* executeUpdate() method execute specified sql query. Here this query insert data and image from specified address. */ int s = psmnt.executeUpdate(); if(s>0) { System.out.println("Uploaded successfully !"); } else { System.out.println("unsucessfull to upload image."); } } // catch if found any exception during rum time. catch (Exception ex) { System.out.println("Found some error : "+ex); } finally { // close all the connections. connection.close(); psmnt.close(); } } }
Output of the program:
Related articles
- Basic Java SQL DB interface (staysmarter.wordpress.com)
- JDBC in Java (clean-clouds.com)
- JDBC MySQL Error – java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/… (yahawana.wordpress.com)
- jdbc connection socketexception error (stackoverflow.com)
JSF 2.0 + Spring + Hibernate integration example
Here’s a long article to show you how to integrate JSF 2.0, Spring and Hibernate together. At the end of the article, you will create a page which display a list of the existing customer from database and a “add customer” function to allow user to add a new customer into database.
P.S In this example, we are using MySQL database and deploy to Tomcat 6 web container.
1. Project Structure
Directory structure of this example
2. Table Script
Create a customer table and insert 2 dummy records.
DROP TABLE IF EXISTS `mkyongdb`.`customer`; CREATE TABLE `mkyongdb`.`customer` ( `CUSTOMER_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(45) NOT NULL, `ADDRESS` VARCHAR(255) NOT NULL, `CREATED_DATE` datetime NOT NULL, PRIMARY KEY (`CUSTOMER_ID`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(1, 'mkyong1', 'address1', now()); INSERT INTO mkyongdb.customer(customer_id, name, address, created_date) VALUES(2, 'mkyong2', 'address2', now());
3. Hibernate Stuff
A model class and Hibernate mapping file for customer table.
File : Customer.java
package com.mkyong.customer.model; import java.util.Date; public class Customer{ public long customerId; public String name; public String address; public Date createdDate; //getter and setter methods }
File : Customer.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.mkyong.customer.model.Customer" table="customer" catalog="mkyongdb"> <id name="customerId" type="long"> <column name="CUSTOMER_ID" /> <generator class="identity" /> </id> <property name="name" type="string"> <column name="NAME" length="45" not-null="true" /> </property> <property name="address" type="string"> <column name="ADDRESS" not-null="true" /> </property> <property name="createdDate" type="timestamp"> <column name="CREATED_DATE" length="19" not-null="true" /> </property> </class> </hibernate-mapping>
4. Spring Stuff
Spring’s BO and DAO classes for business logic and database interaction.
File : CustomerBo.java
package com.mkyong.customer.bo; import java.util.List; import com.mkyong.customer.model.Customer; public interface CustomerBo{ void addCustomer(Customer customer); List<Customer> findAllCustomer(); }
File : CustomerBoImpl.java
package com.mkyong.customer.bo.impl; import java.util.List; import com.mkyong.customer.bo.CustomerBo; import com.mkyong.customer.dao.CustomerDao; import com.mkyong.customer.model.Customer; public class CustomerBoImpl implements CustomerBo{ CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } public void addCustomer(Customer customer){ customerDao.addCustomer(customer); } public List<Customer> findAllCustomer(){ return customerDao.findAllCustomer(); } }
File : CustomerDao.java
package com.mkyong.customer.dao; import java.util.List; import com.mkyong.customer.model.Customer; public interface CustomerDao{ void addCustomer(Customer customer); List<Customer> findAllCustomer(); }
File : CustomerDaoImpl.java
package com.mkyong.customer.dao.impl; import java.util.Date; import java.util.List; import com.mkyong.customer.dao.CustomerDao; import com.mkyong.customer.model.Customer; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao{ public void addCustomer(Customer customer){ customer.setCreatedDate(new Date()); getHibernateTemplate().save(customer); } public List<Customer> findAllCustomer(){ return getHibernateTemplate().find("from Customer"); } }
File : CustomerBean.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" > <property name="customerDao" ref="customerDao" /> </bean> <bean id="customerDao" class="com.mkyong.customer.dao.impl.CustomerDaoImpl" > <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
5. Spring + Database
Configure database detail in Spring.
File : db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mkyongdb jdbc.username=root jdbc.password=password
File : DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>WEB-INF/classes/config/database/db.properties</value> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> </beans>
6. Spring + Hibernate
Integrate Hibernate and Spring via LocalSessionFactoryBean
.
File : HibernateSessionFactory.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Hibernate session factory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value> </list> </property> </bean> </beans>
7. JSF 2.0
JSF managed bean to call Spring’s BO to add or get customer’s records from database.
File : CustomerBean.java
package com.mkyong; import java.io.Serializable; import java.util.List; import com.mkyong.customer.bo.CustomerBo; import com.mkyong.customer.model.Customer; public class CustomerBean implements Serializable{ //DI via Spring CustomerBo customerBo; public String name; public String address; //getter and setter methods public void setCustomerBo(CustomerBo customerBo) { this.customerBo = customerBo; } //get all customer data from database public List<Customer> getCustomerList(){ return customerBo.findAllCustomer(); } //add a new customer data into database public String addCustomer(){ Customer cust = new Customer(); cust.setName(getName()); cust.setAddress(getAddress()); customerBo.addCustomer(cust); clearForm(); return ""; } //clear form values private void clearForm(){ setName(""); setAddress(""); } }
A JSF page to display existing customer records via h:dataTable
and a few text components to allow user to insert new customer record into database.
File : default.xhtml
<?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> <h:outputStylesheet library="css" name="table-style.css" /> </h:head> <h:body> <h1>JSF 2.0 + Spring + Hibernate Example</h1> <h:dataTable value="#{customer.getCustomerList()}" var="c" styleClass="order-table" headerClass="order-table-header" rowClasses="order-table-odd-row,order-table-even-row" > <h:column> <f:facet name="header"> Customer ID </f:facet> #{c.customerId} </h:column> <h:column> <f:facet name="header"> Name </f:facet> #{c.name} </h:column> <h:column> <f:facet name="header"> Address </f:facet> #{c.address} </h:column> <h:column> <f:facet name="header"> Created Date </f:facet> #{c.createdDate} </h:column> </h:dataTable> <h2>Add New Customer</h2> <h:form> <h:panelGrid columns="3"> Name : <h:inputText id="name" value="#{customer.name}" size="20" required="true" label="Name" > </h:inputText> <h:message for="name" style="color:red" /> Address : <h:inputTextarea id="address" value="#{customer.address}" cols="30" rows="10" required="true" label="Address" > </h:inputTextarea> <h:message for="address" style="color:red" /> </h:panelGrid> <h:commandButton value="Submit" action="#{customer.addCustomer()}" /> </h:form> </h:body> </html>
8. JSF 2.0 + Spring
Integrate JSF 2.0 with Spring, see detail explanation here – JSF 2.0 + Spring integration example
File : applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Database Configuration --> <import resource="classes/config/spring/beans/DataSource.xml"/> <import resource="classes/config/spring/beans/HibernateSessionFactory.xml"/> <!-- Beans Declaration --> <import resource="classes/com/mkyong/customer/spring/CustomerBean.xml"/> </beans>
File : faces-config.xml
<?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <application> <el-resolver> org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application> <managed-bean> <managed-bean-name>customer</managed-bean-name> <managed-bean-class>com.mkyong.CustomerBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>customerBo</property-name> <value>#{customerBo}</value> </managed-property> </managed-bean> </faces-config>
File : 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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>JavaServerFaces</display-name> <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <!-- Change to "Production" when you are ready to deploy --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <!-- Welcome page --> <welcome-file-list> <welcome-file>faces/default.xhtml</welcome-file> </welcome-file-list> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map these files with JSF --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping></web-app>
9. Demo
Run it, fill in the customer data and click on the “submit” button.
Download Source Code
Related articles
- Spring Framework Architecture (shanisk.wordpress.com)
- com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException in hibernate (stackoverflow.com)