Working with BLOB / CLOB data types in database is sometime a trivial task. I found particularly when working with Hibernate 3 to store and retrieve BLOB objects we need certain things to be taken care of. Let us see a tutorial where we will using Spring 3 MVC and Hibernate 3 to store and retrieve blob objects in database.
Our Goal
Our goal is to create a Document Manager application in Spring 3 MVC and Hibernate. Following is the functionality.- A form is displayed on main page with fields such as Document name, description and browse button to select document from file system.
- User can select any document from local drive and upload the same using Save document functionality.
- All the documents saved are added in a database table.
- List of all the documents present in database is displayed on the main page.
- Each document in the list have two buttons: Delete and Download.
- Any document can be downloaded by clicking on download button.
- Any document can be deleted by clicking on delete button.
Step 1: Create Database Table
For Document Manager application, we will use MySQL database. Create a table documents in MySQL database docdb. This is very preliminary example and thus we have minimum columns to represent a document. Feel free to extend this example and create a more complex application.CREATE DATABASE `docdb`;
USE `docdb`;
CREATE TABLE `documents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`description` text NOT NULL,
`filename` varchar(200) NOT NULL,
`content` mediumblob NOT NULL, /* for ORACLE enter BLOB*/
`content_type` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
Code language: SQL (Structured Query Language) (sql)
Step 2: Create Maven Project in Eclipse
The document manager application will use Maven for build and dependency management. For this we will use the Maven Dynamic Web Project in Eclipse as the base architecture of our application. Or directly download the below source code: Maven Dynamic Web Project (6.7 KB) Once you have imported / created the Maven web project in Eclipse. Copy following content into Maven’s pom.xml file. These are the dependencies we will use in our Document manager application. File: /pom.xml<?xml version="1.0" encoding="UTF-8"?><project>
<modelVersion>4.0.0</modelVersion>
<groupId>MavenWeb</groupId>
<artifactId>MavenWeb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<description></description>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.2.ga</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<properties>
<org.springframework.version>3.0.2.RELEASE</org.springframework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Code language: HTML, XML (xml)
Unzip the source code to your hard drive and import the project in Eclipse. Once the project is imported in Eclipse, we will create package structure for Java source. First rename the project to DocumentManager and create following packages under src/main/java folder.- net.viralpatel.docmanager.controller – This package will contain Spring Controller classes for Document Manager application.
- net.viralpatel.docmanager.model – This package will contain form object for Document manager application. Document model will be a simple POJO class with different attributes such as document name, description, filename etc.
- net.viralpatel.docmanager.dao – This is the DAO layer of Document manager application. It consists of DocumentDao class which will use Hibernate API to interact with database.
- The src/main/resources folder will have hibernate configuration file: hibernate.cfg.xml.
- The WEB-INF folder will have jsp/documents.jsp file to render document list and add form and jdbc.properties file containing database connection configuration. Also it contains spring-servlet.xml which will define all the Controller class and web.xml which contain spring configuration.
Entity class – The Hibernate model class
Let us start with the coding of Document manager application. First we will create a model object or hibernate POJO class to store document information. Also this class will be an Entity class and will be linked with DOCUMENTS table in database. Create a java classDocument.java
under net.viralpatel.docmanager.model
package and copy following code into it. File: /src/main/java/net/viralpatel/docmanager/model/Document.javapackage net.viralpatel.docmanager.model;
import java.sql.Blob;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name="documents")
public class Document {
@Id
@GeneratedValue
@Column(name="id")
private Integer id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="filename")
private String filename;
@Column(name="content")
@Lob
private Blob content;
@Column(name="content_type")
private String contentType;
@Column(name="created")
private Date created;
//Getter and Setter methods
}
Code language: Java (java)
The first thing you’ll notice is that the import statements import from javax.persistence rather than a Hibernate or Spring package. Using Hibernate with Spring, the standard JPA annotations work just as well and that’s what I’m using here.- First we’ve annotated the class with
@Entity
which tells Hibernate that this class represents an object that we can persist. - The
@Table(name = "documents")
annotation tells Hibernate which table to map properties in this class to documents table. The first property in this class on line 20 is our object ID which will be unique for all events persisted. This is why we’ve annotated it with@Id
. - The
@GeneratedValue
annotation says that this value will be determined by the datasource, not by the code. - The
@Column(name = "filename")
annotation is used to map this property to the FILENAME column in the DOCUMENTS table.
The Data Access (DAO) Layer
The DAO layer of Document Manager application consist of a class DocumentDAO. Ideal solution will be to create an interface (DocumentDAO) and its corresponding implementation class DocumentDAOImpl. But for sake of simplicity we will create just normal DAO class DocumentDAO.java. File: src/main/java/net/viralpatel/docmanager/dao/DocumentDAO.javapackage net.viralpatel.docmanager.dao;
import java.util.List;
import net.viralpatel.docmanager.model.Document;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public class DocumentDAO {
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void save(Document document) {
Session session = sessionFactory.getCurrentSession();
session.save(document);
}
@Transactional
public List<Document> list() {
Session session = sessionFactory.getCurrentSession();
List<Document> documents = null;
try {
documents = (List<Document>)session.createQuery("from Document").list();
} catch (HibernateException e) {
e.printStackTrace();
}
return documents;
}
@Transactional
public Document get(Integer id) {
Session session = sessionFactory.getCurrentSession();
return (Document)session.get(Document.class, id);
}
@Transactional
public void remove(Integer id) {
Session session = sessionFactory.getCurrentSession();
Document document = (Document)session.get(Document.class, id);
session.delete(document);
}
}
Code language: Java (java)
Methods:- list() Method – This method gets the list of all documents stored in documents table and return a List of Document objects.
- save() Method – This method is used to store a new document (including BLOB) into database.
- get() Method – This method returns Document entry for a given ID from database. Used in download functionality to download a stored document from database.
- remove() Method – This method is used to delete a document with specific ID from database.
@Repository
and @Autowired
. Classes marked with annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning. The @Component
annotation is the main stereotype that indicates that an annotated class is a “component”. The @Repository
annotation is yet another stereotype that was introduced in Spring 2.0. This annotation is used to indicate that a class functions as a repository and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring’s DataAccessException hierarchy, even when using plain JPA in the DAO classes. Another annotation used in DocumentDAO is @Autowired
. This is used to autowire the dependency of the DocumentDAO on the SessionFactory. Also note that we have used @Transactional annotation on each method. Ideally the DAO layer is access from a Service layer and transaction management needs to be specified at Service layer. But again for sake of simplicity we will not include service layer in our example and directly call the DAO layer from Spring Controller. Again, feel free to change this implementation and add your own service layer in between. For more information about A layered application with Services in Spring MVC and Hibernate read this tutorial. Spring MVC Hibernate Maven exampleAdding Spring MVC Support to Webapplication
Let us add Spring MVC support to our web application. Update the web.xml file and add servlet mapping for org.springframework.web.servlet.DispatcherServlet. Also note that we have mapped url / with springServlet so all the request are handled by spring. File: /src/webapp/WEB-INF/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>DocumentManager</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Code language: HTML, XML (xml)
Once the web.xml is configured, let us add spring-servlet.xml and jdbc.properties files in /src/main/webapp/WEB-INF folder. File: /src/main/webapp/WEB-INF/jdbc.propertiesThe jdbc.properties file contains database connection information such as database url, username, password, driver class. You may want to edit the driverclass and dialect to other DB if you are not using MySQL. File: /src/main/webapp/WEB-INF/spring-servlet.xmlCode language: HTML, XML (xml)jdbc.driverClassName= com.mysql.jdbc.Driver jdbc.dialect=org.hibernate.dialect.MySQLDialect jdbc.databaseurl=jdbc:mysql://localhost:3306/docdb jdbc.username=root jdbc.password=password
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.docmanager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.SetBigStringTryClob">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Code language: HTML, XML (xml)
The spring-servlet.xml file contains different spring mappings such as transaction manager, hibernate session factory bean, data source etc.- jspViewResolver bean – This bean defined view resolver for spring mvc. For this bean we also set prefix as “/WEB-INF/jsp/” and suffix as “.jsp”. Thus spring automatically resolves the JSP from WEB-INF/jsp folder and assigned suffix .jsp to it.
- propertyConfigurer bean – This bean is used to load database property file jdbc.properties. The database connection details are stored in this file which is used in hibernate connection settings.
- dataSource bean – This is the java datasource used to connect to document manager database. We provide jdbc driver class, username, password etc in configuration.
- sessionFactory bean – This is Hibernate configuration where we define different hibernate settings. hibernate.cfg.xml is set a config file which contains entity class mappings. Also note that in sessionFactory we have specified few hibernate properties such as
hibernate.connection.SetBigStringTryClob
andhibernate.jdbc.batch_size
. These are used to configure BLOB / CLOB settings in hibernate. - multipartResolver bean – We use Spring MVCs CommonsMultipartResolver. This resolver will resolve multipart form data such as file uploads from the request and make available File object to spring controller. Note that we have specified property
maxUploadSize
with value 10000000. This is the maximum limit of filesize which can be uploaded in our example. - transactionManager bean – We use hibernate transaction manager to manage the transactions of our document manager application.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="net.viralpatel.docmanager.model.Document" />
</session-factory>
</hibernate-configuration>
Code language: HTML, XML (xml)
The Controller – Spring MVC controller class
We are almost done with our application. Just add following Spring controller class DocumentController.java to net.viralpatel.docmanager.controller package. File: /src/main/java/net/viralpatel/docmanager/controller/DocumentController.javapackage net.viralpatel.docmanager.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.viralpatel.docmanager.dao.DocumentDAO;
import net.viralpatel.docmanager.model.Document;
import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class DocumentController {
@Autowired
private DocumentDAO documentDao;
@RequestMapping("/index")
public String index(Map<String, Object> map) {
try {
map.put("document", new Document());
map.put("documentList", documentDao.list());
}catch(Exception e) {
e.printStackTrace();
}
return "documents";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
@ModelAttribute("document") Document document,
@RequestParam("file") MultipartFile file) {
System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
try {
Blob blob = Hibernate.createBlob(file.getInputStream());
document.setFilename(file.getOriginalFilename());
document.setContent(blob);
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}
try {
documentDao.save(document);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/index.html";
}
@RequestMapping("/download/{documentId}")
public String download(@PathVariable("documentId")
Integer documentId, HttpServletResponse response) {
Document doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "inline;filename=\"" +doc.getFilename()+ "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(doc.getContent().getBinaryStream(), out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("/remove/{documentId}")
public String remove(@PathVariable("documentId")
Integer documentId) {
documentDao.remove(documentId);
return "redirect:/index.html";
}
}
Code language: Java (java)
The spring controller defines four methods to manipulate document manager application.- index method – This method uses list() method of DocumentDAO to fetch the list of all documents from database. Note that we have mapped request “/index” to this method. Thus Spring will automatically calls this method whenever it encounters this url in request.
- save method – This method adds a new document to document list. The document details are fetched in Document object using
@ModelAttribute
annotation. Also note that the request “/save” is mapped with this method. The request method should also be POST. Once the document is added in document list, we redirect to /index.html page which in turn calls index() method to display document list to user. One more thing to note here is@RequestParam
. We are mapping MultipartFile object using @RequestParam(“file”) annotation. Spring automatically detects “file” data from request and map it with MultipartFile object. This object is later converted to BLOB object and set in the Document content.
Related: Forms in Spring MVC - download method – This method is used to download a selected testcase. Note that we are fetching the document content from database using DAO class and thn set the Data stream in Response. Also note that we are using
response.setHeader()
method to set"Content-Disposition"
. This will raise a Save As dialog box in browser whenever user tries to download a document. - remove method – This methods removes a document from the document list. Similar to save() this method also redirects user to /index.html page once the document is removed. One thing to note in this method is the way we have mapped request url using @RequestMapping annotation. The url “/remove/{documentId}” is mapped thus whenever user send a request /remove/12.html, the remove method will try to delete document with ID:12.
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Document Manager - viralpatel.net</title>
</head>
<body>
<h2>Document Manager</h2>
<h3>Add new document</h3>
<form:form method="post" action="save.html" commandName="document" enctype="multipart/form-data">
<form:errors path="*" cssClass="error"/>
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="description">Description</form:label></td>
<td><form:textarea path="description" /></td>
</tr>
<tr>
<td><form:label path="content">Document</form:label></td>
<td><input type="file" name="file" id="file"></input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Document"/>
</td>
</tr>
</table>
</form:form>
<br/>
<h3>Document List</h3>
<c:if test="${!empty documentList}">
<table class="data">
<tr>
<th>Name</th>
<th>Description</th>
<th> </th>
</tr>
<c:forEach items="${documentList}" var="document">
<tr>
<td width="100px">${document.name}</td>
<td width="250px">${document.description}</td>
<td width="20px">
<a href="${pageContext.request.contextPath}/download/${document.id}.html"><img
src="${pageContext.request.contextPath}/img/save_icon.gif" border="0"
title="Download this document"/></a>
<a href="${pageContext.request.contextPath}/remove/${document.id}.html"
onclick="return confirm('Are you sure you want to delete this document?')"><img
src="${pageContext.request.contextPath}/img/delete_icon.gif" border="0"
title="Delete this document"/></a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Code language: HTML, XML (xml)
MySQL BLOB type field has a capacity of only about 65.535 bytes ~ 65KB.
To resolve this only need to modify the column type MEDIUMBLOB a type which has a capacity of 16,777,215 bytes ~ 16.5Mb
@g000026 – Thanks for the information. I have updated the “create table” script and added MEDIUMBLOB as type.
Hi, this example can run on Tomcat? or It need of a Application Server with JBoss ??
@Domenico – this example can be executed in Tomcat. The above screenshot are from Tomcat only.
Hi, Nice tutorial. I am facing error while running the example. I can see from console that value for ID is not being generated, record is not getting stored becuase of that.
I have copied your example, most of things are same except hibernate-entitymanager. I am not able to get 3.3.2.GA , so shifted to 3.3.1.GA.
any clue..
Sudhir
@Sudhir: Check if you have created table with ID field AUTOINCREMENT. I can guess from your error that ID field is not autoincrement and thus the default value stored is null.
Hi Viral,
Thanks for the reply, It seems issue with hibernate version and dependency resources in the repo.
I could fix the error by changing hibernate dependencies to the following
hibernate
hibernate-entitymanager
3.4.0.GA
and adding dependency for cglib with following.
cglib
cglib
2.2
I could run all functionality of the app with the above said two changes.
-Sudhir
Hi Sudhir can you please show me your solution for this error :
SEVERE: No value specified for parameter 7
Hibernate: insert into documents (content, content_type, created, description, filename, name, id) values (?, ?, ?, ?, ?, ?, ?)
com.mysql.jdbc.JDBC4PreparedStatement@d8fd1a: insert into documents (content, content_type, created, description, filename, name, id) values (** STREAM DATA **, ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’, null, ‘MedAptus’, ‘cover.docx’, ‘MedAptus’, ** NOT SPECIFIED **)
org.hibernate.exception.SQLGrammarException: could not insert: [net.viralpatel.docmanager.model.Document]
Thanks
Hi viral,
I am use the xml mapping in the hibernate and I am use the MultiActioncontroller.
My code is addproduct
I got the error on this line=====>
Blob blob = Hibernate.createBlob(file.getInputStream());
please help me.
To start with,
Viral,
Its definitely an great example, thanks for all the efforts and time you are putting in. And its helping us out a lot to get used with Concepts. Thanks for that.
Then coming to example above :
I am facing the same issue as Sudhir did, and then i tired to implement the way he said. But i am not out of the error. Could some one who had success please list the version of the ide, jars, maven and java used.
Also i tried to run it as plane spring application removing Maven dependencies, then i am running into Servlet loading issue.
Appreciate all your help.
Thanks,
Naveen
Hi Viral,
All your tutorials a nice and easy to follow, please I follow all the steps, but all my source code has errors, I did not see lib (jars) in WEB-INF .
Can you please help ?
thanks
Kamal
Hi Kamal,
Seems your Maven dependencies are not resolved. Check if Eclipse has m2eclipse plugin installed. Also you can try running command
mvn eclipse:eclipse
in your projects directory. Hope this works.Hi,
when filled the form and pressed the button I got this error :
Name:cover.docx
Desc:My cover letter
File:file
ContentType:application/vnd.openxmlformats-officedocument.wordprocessingml.document
Hibernate: insert into documents (content, content_type, created, description, filename, name, id) values (?, ?, ?, ?, ?, ?, ?)
com.mysql.jdbc.JDBC4PreparedStatement@2b7bd9: insert into documents (content, content_type, created, description, filename, name, id) values (** STREAM DATA **, ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’, null, ‘My cover letter’, ‘cover.docx’, ‘cover.docx’, ** NOT SPECIFIED **)
Nov 28, 2011 2:40:59 PM org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 0, SQLState: 07001
Nov 28, 2011 2:40:59 PM org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: No value specified for parameter 7
org.hibernate.exception.SQLGrammarException: could not insert: [net.viralpatel.docmanager.model.Document]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
Thanks, your help is appreciated.
If you try to upload a file of size 10000000 bytes, won’t you get out of memory exception? If I don’t have control on heap size, then how to handle this error?
Hi viral i am getting this exception while i am running the server,can u please help to solve my problem.
Could not autowire field: private net.viralpatel.docmanager.dao.DocumentDAO net.viralpatel.docmanager.controller.DocumentController.documentDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/SpringSecurity-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/dom4j/DocumentException
i too havethis error
Hi,
this example run great using Oracle10g with ojdbc14.jar, i can upload and download big files (over 70MB) with no memory problems (real streaming). Under mysql5.0.47 with mysql-connector-java-5.1.18-bin.jar the file goes in memory!!! Why?
I use Hibernate 3.3.2, Spring 2.5.6, Tomcat 6.0.35.
Please help.
II’m getting this erro ron Oracle,
java.lang.ClassCastException: $Proxy142 cannot be cast to oracle.sql.BLOB
I’m using also ojdbc14.jar file.
ojdbc
ojdbc
14
jar
compile
Database String Connection properties
app.jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
app.jdbc.url=jdbc:oracle:thin:@192.168.2.200:1521:oracle
app.jdbc.username=test
app.jdbc.password=test
app.jdbc.dialect=org.hibernate.dialect.Oracle10gDialect
do you have any idea why this happened?
I got an error in document.jsp in this section:
the following error are: javax.servlet.jsp.PageContext cannot resolver to a type and javax.servlet.jsp.JspException cannot resolver to a type.
any idea on how to fix those issues?
Great tutorial and instructions. i’m recenly using Spring framework and trying your application using Sprint Tool Suite. But I can’t even run the jsp page. After following all of your instructions above, I try to run the documents.jsp to the Tomcat 7 server and get the following error: java.lang.ClassNotFoundException: org.springframework.context.ApplicationListener
Can anybody please tell me what special configurations and/or jar files I need to include in my build path to run this application? Alternatively, please advise on this error and what I can do to run this application correctly. THANK YOU!
is required in spring-servlet.xml
Hi i need to display all images which is fetched from database like a gallery … please help me out in this
Hi Viral,
This article was indeed helpful. But for my requirement, I need to store the uploaded images on the file system and only the URL/reference in the database. i.e. each row displayed on jsp page may have 1 or 2 images. I want to store only the reference in the database and not actual image. Can you help pls?
……………………………………………………………………..
z
…………………………………………………………………….
public class Table1 implements java.io.Serializable {
private Integer table1Idp;
private String table1Name;
private Set table2s = new HashSet(0);
public Table1() {
}
public Table1(Integer table1Idp, String table1Name) {
this.table1Idp = table1Idp;
this.table1Name = table1Name;
}
public Table1(Integer table1Idp, String table1Name, Set table2s) {
this.table1Idp = table1Idp;
this.table1Name = table1Name;
this.table2s = table2s;
}
public Integer getTable1Idp() {
return this.table1Idp;
}
public void setTable1Idp(Integer table1Idp) {
this.table1Idp = table1Idp;
}
public String getTable1Name() {
return this.table1Name;
}
public void setTable1Name(String table1Name) {
this.table1Name = table1Name;
}
public Set getTable2s() {
return this.table2s;
}
public void setTable2s(Set table2s) {
this.table2s = table2s;
}
}
…………………………………………………………….
…………………………………………………………………
public class Table2 implements java.io.Serializable {
private Integer table2Idp;
private Table1 table1;
private String table2Name;
private Long table1id;
public Long getTable1id() {
return table1id;
}
public void setTable1id(Long table1id) {
this.table1id = table1id;
}
public Table2() {
}
public Table2(Integer table2Idp, Table1 table1, String table2Name) {
this.table2Idp = table2Idp;
this.table1 = table1;
this.table2Name = table2Name;
}
public Integer getTable2Idp() {
return this.table2Idp;
}
public void setTable2Idp(Integer table2Idp) {
this.table2Idp = table2Idp;
}
public Table1 getTable1() {
return this.table1;
}
public void setTable1(Table1 table1) {
this.table1 = table1;
}
public String getTable2Name() {
return this.table2Name;
}
public void setTable2Name(String table2Name) {
this.table2Name = table2Name;
}
}
……………………………………………………….
public class selectbox extends SimpleFormController {
public selectbox() {
setCommandClass(Table2.class);
setCommandName(“frmNew”);
setSuccessView(“pgeSelectBox”);
setFormView(“pgeSelectBox”);
}
@Override
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws Exception {
ModelAndView mv = new ModelAndView();
Table2 Modelobj = (Table2) command;
Table1 tab1=new Table1();
try {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(Modelobj);
session.getTransaction().commit();
mv = new ModelAndView(new RedirectView(“pgeSelectBox.htm”));
} catch (Exception e)
{
}
return mv;
}
@Override
protected Map referenceData(HttpServletRequest request) throws Exception
{ Map referenceData = new HashMap();
// Map dataMap = new HashMap();
try {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List result = session.createQuery(“from Table1”).list();//database name is actually class name.but display by using actual table name to html page
referenceData.put(“UnderGroups”,result);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
return referenceData;
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
// binder.registerCustomEditor(Table1.class, “rules”, new CustomCollectionEditor(Table1.class)
binder.registerCustomEditor(Table1.class,”rules”, new CustomCollectionEditor(Table1.class)
{
@Override
protected Object convertElement(Object element)
{
String table1Idp = “”;
if (element instanceof String)
table1Idp = (String) element;
return table1Idp;// != null ? new Table2(table1Idp) : null
}
});
}
}
…………………………………………………………………..
my jsp >>
form : select path =”table1?
form : options items=”${UnderGroups}” itemValue=”table1Idp” itemLabel=”table1Name”
/////////////////////////////////////////////////////////////////////
HELP PLZ URGENT :- I AM USING SPRING MVC 2.5 WITH HIBERNATE :
i am geting error while saving id from <form:select to database . help me what modification has to done in the above code ?? i dont know anything about property editor or initBinder . i just started this framework …. plz help i am sitting with this error for more than one week :(
Dear Viral,
Great blog. God bless you for your effort and teaching for all learners.
All,
If anyone come across following error, pls added the following entry in pom.xml file.
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
Which is covered in detail:- http://www.tuanleaded.com/blog/2012/07/using-maven-with-spring-3-hibernate/
Solution to add in pom.xml
jboss
javassist
3.4.ga
Also,
org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
Solution to add in pom.xml
cglib
cglib
2.2
Regards
Balamurugan S
All worked fine from your example until I decided to use JPA and Spring Data approach.
Then org.hibernate.Hibernate class (which is now hosted in spring-orm artifact) hasn’t the createBlob() method and I am not more able to upload my files.
Any suggestion?
Thanks
Excellent worked perfectly with few tweaks to the pom.xml.
Hi Vijay,
What tweaks you have made in your pom file. Please let me know I am getting some exceptions like, Error creating bean with name ‘documentController’: Injection of autowired dependencies failed
HI !
Can you please mail me or post Article about Upload image from jsp(using spring tag lib), store in database with hibernate, Display the image on jsp page ?
all i want to know is how binding takes place in jsp to pojo annotated-spring hibernate?
Superb article, thanks
Can u please tell how to run it on eclipse?
hi when i want to retrieve the BLOB i get “Caused by: org.postgresql.util.PSQLException: This connection has been closed.” i’ve described my problem at
http://stackoverflow.com/questions/13645865/hibernate-blob-getbinarystream
can anybody help whats wrong?
Good one to understand the one complete flow of Spring 3 mvc .Thanx a lot..
Hi Viral Patel,
I’m using the same code to upload and download files into DB2 database. But I’m getting Error when uploading files(such as PDF, JPEG, BMP, etc.,) other than .TXT files.
Error code:
============
DB2 SQL ERROR SQLCODE: -302 SQLSTATE= 22001
But I’m not getting any error while uploading .TXT files. Is there any solution for this?
hello viral,
i am getting an error on this line
Blob blob = Hibernate.createBlob(multipartFile.getInputStream());
help me.
HI there… I had the same error and fixed it by making this change to the pom.xml file
org.hibernate
hibernate-entitymanager
3.4.0.GA
cglib
cglib
2.2
Its not working ray
have solution without hibernate-entitymanager ? because i use hibernate-core.
HTTP Status 500 – Request processing failed; nested exception is org.hibernate.exception.DataException: could not insert: [com.ogs.domain.Complaint]
Why you give that much preference to maven ? while it so typical to configure the maven plugin in eclipse. What are the advantages of Maven to use it in our project?
Getting this error when I run the application:
Error creating bean with name ‘documentController’: Injection of autowired dependencies failed;
Any help would be greatly appreciated…
Hi Viral,
Nice to see your website with so many solutions. I would like to thank you for helping us! I am very much new to this Java/J2EE world.. Please help me..
My query is, I need to do the same application with normal MVC app with Aceess 2010 as a database. Please do let me know if this is possible and would be greatly appreciated if you provide the hint or code like how to do it…..
Thanks in advance
Shruthi
Hi
I am getting error saying current request is not multipart request.. please help me soon
Hi,
I am using the spring hibernate newly but I am faceing the problem to display the data on the userside the exception is:
org.hibernate.hql.ast.QuerySyntaxException: dlcdetail is not mapped [from dlcdetail]
Hi Viral thnx for the post
Hi Viral! thanks a lot for this greats tuts!!! just fantastic!
all tutorials are running without any errors! amazing!
I have just one litte problem:
I cant access my css and image files from the jsp’s…i added the images to the root, to the resource folder etc…but none of this helps
i’ve also tried a lot of things like:
<script type="text/javascript" src="”>
in the spring-servlet.xml
mvc:resources mapping=”/resources/**” location=”/resources/” />
nothing solves the problem…
have anybody an idea?
thanks in advance!
hendrik
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/upload.jsp at line 17
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:567)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘document’ available as request attribute
org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.22 logs.
help me
thanks advance
sir, i copied code as it is and got lot of erros.tell me whether any modification in code has to b done n any libraries to b imported.iam wrking in myeclipse6.0
Hi viral i am getting the javax.servlet.jsp.pageContext can not resolved to a type in jsp.
please give the solution
For resolve to error: javax.servlet.jsp.pageContext
You need add in your pom.xml
javax.servlet
jsp-api
2.0
provided
Please reply me how to configure the code in the above web page without using maven in eclipse ASAP.
Hello Viral,
Thanks for the blog,it really helped me to come with the solution really fast.
But I got stuck while I run the application.
Status:-
> Able to run the application and it displayed the 1st page
> while inserting the values into db I am getting errors.
( I have configured db2 as the db for this application )
ERROR:-
Hibernate: insert into documents (id, content, content_type, created, description, filename, name) values (default, ?, ?, ?, ?, ?, ?)
Jul 4, 2014 9:20:49 PM org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: -407, SQLState: 23502
Jul 4, 2014 9:20:49 PM org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: DB2 SQL Error: SQLCODE=-407, SQLSTATE=23502, SQLERRMC=TBSPACEID=2, TABLEID=15, COLNO=0, DRIVER=4.9.78
org.hibernate.exception.ConstraintViolationException: could not insert: [net.viralpatel.docmanager.model.Document]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2163)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2643)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:51)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
hello all of my friend everyone know about spring but does someone know about SPRINGBOOT
SO PLEASE SHARE SPRING BOOT MVC EXAMPLE …………….
sir i got this error while running the application
org.apache.jasper.JasperException: An exception occurred processing JSP page /documents.jsp at line 18
15:
16:
17:
18: Name
19:
20:
21:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘document’ available as request attribute
org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
can any one help me this is urgent requirements
HI.
How can I convert a saved Blob file to previous version of file. In my case, I convert xlxs file to Blob and save it. Later on I need to convert it back to xlsx.
How can I acheive this ?
I am not able to send the File from JSP to Spring Controller. I greately appreciated any help.
The request data is sending by using below logic in JSP
$.post(“optin”, {
sharing : shareString,
consentDate : $(‘#datepicker’).val()
}, function(data, textStatus) {
}).complete(function() {
});
Now I want to add functionality of fileupload to this JSP. I tried by adding
and retrieving in SpringController using MultipartFile but I didn’t get success. Any help is greatelt appreciated.
The existing Controller logic is
@RequestMapping(value={“optin”}, method=RequestMethod.POST)
public @ResponseBody boolean optInMember(@PathVariable String encryptedMemberId, Model model, @RequestParam String sharing, @RequestParam Date consentDate, @ModelAttribute(“user”) IHHUser user) throws IHHException{}
Here some of the code is not with in a form and I have to write JSP logic out side of the form. SO I created a new form
I followed everything you explained without any error but at the end when entering the address
http://localhost:8080/DocumentManager/index.html ,i get the errors
HTTP Status 404 – /MavenWeb%2D0.0.1%2DSNAPSHOT/
type Status report
message /MavenWeb%2D0.0.1%2DSNAPSHOT/
description The requested resource is not available.
Apache Tomcat/6.0.41
Hi viral…
i have created pages like you… but i am using hibernate 4.1.
Now i have error this line
document.setFilename(file.getOriginalFilename())
pls help me to find the solution
I am using Spring Mvc 3 with hibernate. I followed your given example for storing and retrieving all types of files perfectly. But now am stuck in uploading more than one file. if only one file am adding its working fine. but my requirement is to add more than one file. Please suggest me how can i store files and how to retrieve it if i upload more than one file.
http://stackoverflow.com/questions/27011076/manage-multiple-uploading-files-to-mysql-db?noredirect=1#comment42549161_27011076
Please suggest some suggestion regarding my issue
Hi viral,
am able to save and download multiple files. i used different url to download different files. but now my issue is to show image for a profile of a customer. i used your above code to save image. but am unable to view that image on jsp… please help me out
createBlob is deprecated, your code doesnt work with current Hibernate, either option is to use getLobCreator which requires session, so code needs to be moved in DAO, or use bytea.
Use this in current code
sir you have any tutorial to add the vedio in the project
you have any code for video regard retrive………..and save in the datea base if you have plz send my mail…..i have to need for this code …..pls help me
Thanks, nice tips
I am unable to download file from using Hibernate,JPA & using JBoss and also i am not getting any error.I don’t know why. can any one help. even though i am writing blob in buffer but stii there is no use.
Hi viral,
i am trying this program in dynamic web project,some errors are receiving(Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/spring-servlet.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor),pls help me
Please provide jars with source code
unable to run this program….Showing error on all pages as(The import org.hibernate.Hibernate cannot be resolved) on packages
No index.html file
No value specified for parameter 7