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)
<?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)
Document.java
under net.viralpatel.docmanager.model
package and copy following code into it. File: /src/main/java/net/viralpatel/docmanager/model/Document.java package 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. @Entity
which tells Hibernate that this class represents an object that we can persist.@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
.@GeneratedValue
annotation says that this value will be determined by the datasource, not by the code.@Column(name = "filename")
annotation is used to map this property to the FILENAME column in the DOCUMENTS table.package 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: @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 example <?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.properties The 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. hibernate.connection.SetBigStringTryClob
and hibernate.jdbc.batch_size
. These are used to configure BLOB / CLOB settings in hibernate.maxUploadSize
with value 10000000. This is the maximum limit of filesize which can be uploaded in our example.<?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)
package 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. @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. response.setHeader()
method to set "Content-Disposition"
. This will raise a Save As dialog box in browser whenever user tries to download a document. <%@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)
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
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
[code language="java"]
public ModelAndView addProduct(HttpServletRequest request,
HttpServletResponse response, Product product) throws Exception
{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("product");
System.out.println("Product Name:" + product.getName());
System.out.println("Description:" + product.getDescription());
System.out.println("Price:" + product.getPrice());
System.out.println("Image:" +product.getImage()+"\n");
try {
product.setName(product.getName());
System.out.println("Name = "+product.getName());
product.setDescription(product.getDescription());
System.out.println("Description = "+product.getDescription());
product.setPrice(product.getPrice());
System.out.println("Price = "+product.getPrice());
Blob blob = Hibernate.createBlob(multipartFile.getInputStream());
product.setImage(blob);
System.out.println("Image = "+product.getImage());
}
catch (IOException e) {
e.printStackTrace();
}
try {
productDAO.saveOrUpdateProduct(product);
} catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("redirect:productlist.htm");
}
[/code]
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