-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: Use Hibernate to save a file
PostPosted: Fri Mar 12, 2004 5:21 pm 
Beginner
Beginner

Joined: Fri Mar 12, 2004 5:18 pm
Posts: 44
Hi,

I would like to save/retrieve a file to a Database using Hibernate.

Is there an example regarding doing that?

Can someone please help me ?

Thank you.


Top
 Profile  
 
 Post subject: blob help
PostPosted: Fri Mar 12, 2004 10:48 pm 
Beginner
Beginner

Joined: Thu Sep 04, 2003 2:50 pm
Posts: 45
Location: US: New York NY
its in the docs.
http://www.hibernate.org/hib_docs/refer ... ation-s5-3
http://www.hibernate.org/73.html

I know its there in other places... here is some jsp that I have used....


<HTML>
<HEAD><META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>Ad Save Page</TITLE>
<%@ page import="net.sf.hibernate.Session, net.sf.hibernate.SessionFactory, net.sf.hibernate.Transaction, net.sf.hibernate.Hibernate, net.sf.hibernate.cfg.*,com.cttech.adsys.*,com.jspsmart.upload.*, java.util.*, java.io.*" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
String statusMessage = "";
boolean failure = false;
HibernateSession.closeSession();
Session sess = HibernateSession.currentSession();
Transaction tx = sess.beginTransaction();
try {

//*********************************/
// Initialization
mySmartUpload.initialize(pageContext);
// Upload the data
mySmartUpload.upload();
// get the one and only file we're loading up.
com.jspsmart.upload.File theFile = null;
try {
if (mySmartUpload.getFiles() != null)
theFile = mySmartUpload.getFiles().getFile(0);
} catch (Exception e) {}
String fileType = null;
String filename = null;
InputStream data = null;
int FileLength = 0;
java.sql.Blob fileData = null;

if (theFile != null && !theFile.isMissing()) {
fileType = theFile.getContentType();
filename = theFile.getFileName();
FileLength = theFile.getSize();
// create a uniuque name
java.io.File tempfile = java.io.File.createTempFile("" + Math.random(),null);
//tempfile = theAsset.getTempFilePath() + Math.random();
// save the file so that we can create an input stream with it.
theFile.saveAs(tempfile.getAbsolutePath());

fileData = Hibernate.createBlob(new FileInputStream(tempfile),FileLength);
}
com.cttech.adsys.Ad obj_ad = new com.cttech.adsys.Ad();
// get variables for edit page.

Long AdId = ( mySmartUpload.getRequest().getParameter("ad_id") == null ) ? new Long("0") : new Long(mySmartUpload.getRequest().getParameter("ad_id").trim());
Long ListId = ( mySmartUpload.getRequest().getParameter("list_id") == null ) ? null : new Long(mySmartUpload.getRequest().getParameter("list_id").trim());
Long FrameId = ( mySmartUpload.getRequest().getParameter("frame_id") == null ) ? null : new Long(mySmartUpload.getRequest().getParameter("frame_id").trim());
if (AdId.longValue()!=0) {
// then this is an edit. get the existing object
obj_ad = new com.cttech.adsys.Ad();
sess.load(obj_ad,AdId);
sess.flush();
}


String Name = mySmartUpload.getRequest().getParameter("name");
String Path = mySmartUpload.getRequest().getParameter("path");
String BackgroundColor = mySmartUpload.getRequest().getParameter("bg_color");
String MetaInfo = mySmartUpload.getRequest().getParameter("meta_info");
Short DispDuration = ( mySmartUpload.getRequest().getParameter("disp_duration") == null || mySmartUpload.getRequest().getParameter("disp_duration").equals("") ) ? new Short("0") : new Short(mySmartUpload.getRequest().getParameter("disp_duration").trim());
String Copywrite = mySmartUpload.getRequest().getParameter("copywrite");
Date CopySdate = null;
Date CopyEdate = null;
if (mySmartUpload.getRequest().getParameter("copy_sdate")!=null && !mySmartUpload.getRequest().getParameter("copy_sdate").equals("")) {
CopySdate = Data.STRING_TO_DATE(mySmartUpload.getRequest().getParameter("copy_sdate"),"MM/dd/yyyy").getTime();
}
if (mySmartUpload.getRequest().getParameter("copy_edate")!=null && !mySmartUpload.getRequest().getParameter("copy_edate").equals("")) {
CopyEdate = Data.STRING_TO_DATE(mySmartUpload.getRequest().getParameter("copy_edate"),"MM/dd/yyyy").getTime();
}
Date ShowSdate = null;
Date ShowEdate = null;
if (mySmartUpload.getRequest().getParameter("show_sdate")!=null && !mySmartUpload.getRequest().getParameter("show_sdate").equals("")) {
ShowSdate = Data.STRING_TO_DATE(mySmartUpload.getRequest().getParameter("show_sdate"),"MM/dd/yyyy").getTime();
}
if (mySmartUpload.getRequest().getParameter("show_edate")!=null && !mySmartUpload.getRequest().getParameter("show_edate").equals("")) {
ShowEdate = Data.STRING_TO_DATE(mySmartUpload.getRequest().getParameter("show_edate"),"MM/dd/yyyy").getTime();
}
com.cttech.adsys.Status status = null;
if (mySmartUpload.getRequest().getParameter("status_id")!=null && !mySmartUpload.getRequest().getParameter("status_id").equals("null")) {
if (obj_ad.getStatus()==null ||
!obj_ad.getStatus().getStatusId().toString().equals(mySmartUpload.getRequest().getParameter("status_id"))) {
status = (Status)(sess.find("select status from Status status where status_id = ?",mySmartUpload.getRequest().getParameter("status_id"),Hibernate.STRING)).get(0);
}
}
com.cttech.adsys.Advertiser advertiser = null;
if (mySmartUpload.getRequest().getParameter("advert_id")!=null && !mySmartUpload.getRequest().getParameter("advert_id").equals("null")) {
if (obj_ad.getAdvertiser()==null ||
!obj_ad.getAdvertiser().getAdvertId().toString().equals(mySmartUpload.getRequest().getParameter("advert_id"))) {
advertiser = (Advertiser)(sess.find("select advert from Advertiser advert where advert_id = ?",mySmartUpload.getRequest().getParameter("advert_id"),Hibernate.STRING)).get(0);
}
}

// DETERMINE THE BEST ACTION
if (AdId.longValue() != 0) {
// then this is an edit, update the object
if (mySmartUpload.getRequest().getParameter("delete") != null && mySmartUpload.getRequest().getParameter("delete").equals("1")) {
sess.delete(obj_ad);
sess.flush();
tx.commit();
if (ListId==null) {
%><META CONTENT="1;URL=index.jsp" HTTP-EQUIV="refresh"><%
} else {
%><META CONTENT="1;URL=listAds.jsp?list_id=<%=ListId.toString()%>" HTTP-EQUIV="refresh"><%
}

} else {

try {
if (status != null)
obj_ad.setStatus(status);
if (advertiser != null)
obj_ad.setAdvertiser(advertiser);
obj_ad.setName(Name);
obj_ad.setPath(Path);
obj_ad.setBackgroundColor(BackgroundColor);
obj_ad.setMetaInfo(MetaInfo);
obj_ad.setDispDuration(DispDuration);
obj_ad.setShowSdate(ShowSdate);
obj_ad.setShowEdate(ShowEdate);
obj_ad.setCopySdate(CopySdate);
obj_ad.setCopyEdate(CopyEdate);
obj_ad.setCopywrite(Copywrite);


if (fileData!=null) {
obj_ad.setFileData(fileData);
obj_ad.setFileType(fileType);
obj_ad.setFileName(filename);
obj_ad.setFileLength(new Long(FileLength));
}

sess.saveOrUpdate(obj_ad);
sess.flush();
tx.commit();
if (ListId==null) {
%><META CONTENT="1;URL=editAd.jsp?ad_id=<%=AdId.toString()%>" HTTP-EQUIV="refresh"><%
} else {
%><META CONTENT="1;URL=editAd.jsp?ad_id=<%=AdId.toString()%>&list_id=<%=ListId.toString()%><% if (FrameId != null && FrameId.longValue()>0) {%>&frame_id=<%=FrameId.toString()%><%}%>" HTTP-EQUIV="refresh"><%
}

} catch (Exception e) {
statusMessage = "There was an error updating the existing Ad. ERROR: " + e.toString();
failure = true;
tx.rollback();
}
}
} else {

try {
if (status != null)
obj_ad.setStatus(status);
if (advertiser != null)
obj_ad.setAdvertiser(advertiser);
obj_ad.setName(Name);
obj_ad.setPath(Path);
obj_ad.setBackgroundColor(BackgroundColor);
obj_ad.setMetaInfo(MetaInfo);
obj_ad.setDispDuration(DispDuration);
obj_ad.setShowSdate(ShowSdate);
obj_ad.setShowEdate(ShowEdate);
obj_ad.setCopySdate(CopySdate);
obj_ad.setCopyEdate(CopyEdate);
obj_ad.setCopywrite(Copywrite);
if (fileData!=null) {
obj_ad.setFileData(fileData);
obj_ad.setFileType(fileType);
obj_ad.setFileName(filename);
obj_ad.setFileLength(new Long(FileLength));
obj_ad.setFileLastModified(new java.util.Date());
}
sess.save(obj_ad);
sess.flush();
tx.commit();

if (ListId==null) {
%><META CONTENT="1;URL=editAd.jsp?ad_id=<%=obj_ad.getAdId().toString()%>" HTTP-EQUIV="refresh"><%
} else {
%><META CONTENT="1;URL=editAd.jsp?ad_id=<%=obj_ad.getAdId().toString()%>&list_id=<%=ListId.toString()%><% if (FrameId != null && FrameId.longValue()>0) {%>&frame_id=<%=FrameId.toString()%><%}%>" HTTP-EQUIV="refresh"><%
}
} catch (Exception e) {
statusMessage = "There was an error creating a new Ad. ERROR: " + e.toString();
failure = true;
tx.rollback();
}
}
tx.commit();
} catch (Exception oe) {
out.write("ERROR: " + oe.toString());
tx.rollback();
}
finally {
HibernateSession.closeSession();
}
%>
<link rel="stylesheet" href="css/sitestyle.css" type="text/css">
</HEAD>
<BODY>
<p CLASS="breadcrumb">
<a href="index.jsp">start point</a>
</p>
<P>
<H3>Ad Save Page
</H3>
</P>
<%
if (failure) {
out.write(statusMessage);
} else {
%> The action was a success!

<%
}
%>
</BODY>
</HTML>



output a blob



Session sess = HibernateSession.currentSession();
Transaction tx = sess.beginTransaction();

sess.load(ad, new Long(req.getParameter("id")));
// set our headers.
res.setContentLength((int)ad.getFileLength().longValue());
res.setContentType(ad.getFileType());
res.addHeader("Content-Disposition", "inline; filename=\"" + ad.getFileName() + "\";");

// get an OutputStream
ServletOutputStream out = res.getOutputStream();

// write the file to the OutputStream.

BufferedInputStream is = new BufferedInputStream(ad.getFileData().getBinaryStream() );
int ch = 0;
byte[] chars = new byte[2048];
while ((ch = is.read(chars,0,2048)) !=-1) {
out.write(chars,0,ch);
}
is.close();

out.flush();
out.close();
ad = null;
HibernateSession.closeSession();


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 15, 2004 5:52 pm 
Beginner
Beginner

Joined: Fri Mar 12, 2004 5:18 pm
Posts: 44
Thank you.

Sorry, I am a newbie in this area.
Could you please tell me how to create database which stores BLOB?

Thank you again.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 15, 2004 8:17 pm 
Beginner
Beginner

Joined: Thu Sep 04, 2003 2:50 pm
Posts: 45
Location: US: New York NY
depends on the database. With postgresql, i use oid, which is PostgreSQL blob. You can use bytea, but it limits the amount of data you can have in your blob. Again, check the db vendor docs, as I am going off of memory here.

create table a(int a_id not null primary key, oid filefield null);


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.