• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

How to read/write Blob images using Hibernate

 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I have a web application where I'm trying to store and retrieve user images in a MySQL database. I'm using Spring and Hibernate, but I don't know how to handle blob or binary datatypes.

I would I appreciate it if someone that show my how to configure my hibernate.cfg.xml and how to convert the byte from HTML to the blog datatype.

Here's what I have so far:




I'm clueless...Please Help!
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need a type that will handle blob to byte array conversion. I use the one the Spring Framework provides: http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/orm/hibernate/support/BlobByteArrayType.html but if you don't use Spring I'm sure there are other implementations out there. Just Google it: http://www.google.com/search?ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=hibernate+blob+byte+array or copy the Spring implementation in your project.
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Nina,

i hope, below code would be helpful for you...

File save: by usin Blob object

JSP:

<html:file tabindex="3" property="myRequestFile" accept="text"/>

FORM:

private FormFile myRequestFile=null;

ACTION CLASS:

if("FILE".equalsIgnoreCase(objectRegistrationForm.getObjectType()))
{


// In Case of File Save
file=objectRegistrationForm.getMyRequestFile();

fileObjectDTO.setFileName(file.getFileName());
fileObjectDTO.setIpStream(file.getInputStream());
fileObjectDTO.setObjectType(objectRegistrationForm.getObjectType());
fileObjectDTO.setObjectDesc(objectRegistrationForm.getDescription());
fileObjectDTO.setObjSrchString(objectRegistrationForm.getObjectSearchString());

String resulttest = registrationDelegator.saveFile(fileObjectDTO, loginform.getLoginid(),objectRegistrationForm.getProductModule(), daoBase.getDataSource());
if(resulttest.equalsIgnoreCase("1"))
{
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("objectRegistrationInformation.SaveFile.failure"));
return mapping.findForward(Constants.FAILURE);
}
else
{
err="0";
}
}


DELEGATOR CLASS

public String saveFile(FileObjectDTO fileObjectDTO, String loginId,String productName ,DataSource dataSource) throws RegistrationException
{
ObjectRegistrationDAO objectRegistrationDAO = new ObjectRegistrationDAO(dataSource);
InputStream input = null;
String result = "";
try{
input = fileObjectDTO.getIpStream();
if (input.available() <= 0)
{
result="1";
throw new RegistrationException("BAD_FILE");
}
else{
result = objectRegistrationDAO.saveFile(fileObjectDTO,loginId,productName);
return result;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}

DTO CLASS:

private static final String BLOB_INSERT_SQL="INSERT INTO XX_OBJECT_MASTER" +
" (OBJECT_ID,PRODUCT_ID,OBJECT_NAME,OBJECT_TYPE, " +
" OBJECT_DESCRIPTION,OBJECT_SEARCH_STRING,CREATION_DATE,CREATED_BY, "+
" LAST_UPDATE_DATE,LAST_UPDATE_BY,FILE_CONTENTS ) " +
" VALUES(?,?,?,?,?,?,to_timestamp(?),?,to_timestamp(?),?,EMPTY_BLOB())";

private static final String BLOB_SELECT_SQL = "SELECT FILE_CONTENTS FROM XX_OBJECT_MASTER"+
" WHERE OBJECT_ID = ? FOR UPDATE";

private static final String NEXT_KEY_SELECT_SQL ="SELECT XX_OBJECT_ID_SEQ.NEXTVAL FROM DUAL";

/**
* saveFile
* @throws java.io.IOException
* @return String
* @param productName
* @param loginId
* @param fileObjectDTO
*/
public String saveFile(FileObjectDTO fileObjectDTO, String loginId,String productName) throws RegistrationException,IOException
{
ResultSet rset = null;
Connection conn = null;
BLOB blob=null;
File file ;
OutputStream os = null;
PreparedStatement pstmt = null;
long objectId = 0;
long productId=0;
String test="2";

try
{
conn = dataSource.getConnection();
objectId = getObjectId(conn);
productId= getProductId(conn,productName);


//INSERT QUERY
pstmt = conn.prepareStatement(BLOB_INSERT_SQL);


// INSERT VALUE IN QUERY
prepareBlobInsertStatement(pstmt, objectId, productId,fileObjectDTO, loginId);
pstmt.execute();

conn.setAutoCommit(false);
pstmt = conn.prepareStatement(BLOB_SELECT_SQL);

//SELECT RESULTSET(BLOB) FOR PARTICULAR OBJECT_ID
prepareBlobSelectStatement(pstmt, objectId);

rset = pstmt.executeQuery();
rset.next();

// GET BLOB FROM XX_OBJECT_MASTER TABLE
blob = ((OracleResultSet)rset).getBLOB("FILE_CONTENTS");


os = blob.getBinaryOutputStream();
byte[] chunk = new byte[blob.getChunkSize()];

int i=-1;
while((i = fileObjectDTO.getIpStream().read(chunk))!=-1)
{
os.write(chunk,0,i);
}
}
catch(SQLException sqlexp)
{

sqlexp.printStackTrace();
throw new RegistrationException("objectRegistration.error.database");
}
catch(Exception exp)
{
exp.printStackTrace();
throw new RegistrationException("GENERAL_ERROR");
}
finally
{
os.flush();
os.close();
cleanup(rset,pstmt,conn);
}
return test;
}


/**
* getObjectId
* @throws java.sql.SQLException
* @return long
* @param connection
*/
private long getObjectId(Connection connection) throws SQLException
{
Statement statement = null;
ResultSet resultSet = null;
try
{
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT xx_object_id_seq.NEXTVAL AS OBJECT_ID FROM DUAL");
if (resultSet.next())
{
return resultSet.getLong("OBJECT_ID");
}
throw new SQLException("Unable to generate sequence for OBJECT_ID");
}
finally
{
cleanup(resultSet, statement, null);
}
}


/**
* getProductId
* @throws java.sql.SQLException
* @return long
* @param productName
* @param connection
*/
private long getProductId(Connection connection, String productName) throws SQLException
{
Statement statement = null;
ResultSet resultSet = null;
String query = "";
try
{
statement = connection.createStatement();
query = "SELECT product_id FROM xx_product_master WHERE product_name='" +productName +"'";
resultSet = statement.executeQuery(query);
if (resultSet.next())
{
return resultSet.getLong("product_id");
}
throw new SQLException("Unable to generate product_id");
}
finally
{
cleanup(resultSet, statement, null);
}
}


/**
* prepareBlobInsertStatement
* @throws java.sql.SQLException
* @param loginId
* @param fileObjectDTO
* @param productId
* @param objectId
* @param statement
*/
private void prepareBlobInsertStatement(PreparedStatement statement,long objectId, long productId, FileObjectDTO fileObjectDTO, String loginId) throws SQLException
{

long sysdate = System.currentTimeMillis();
Timestamp dt=new Timestamp(sysdate);

statement.setLong(1, objectId);
statement.setLong(2, productId);
statement.setString(3, fileObjectDTO.getFileName());
statement.setString(4, fileObjectDTO.getObjectType());
statement.setString(5, fileObjectDTO.getObjectDesc());
statement.setString(6, fileObjectDTO.getObjSrchString());
statement.setTimestamp(7,dt);
statement.setString(8,loginId);
statement.setTimestamp(9,dt);
statement.setString(10,loginId);
}


/**
* prepareBlobSelectStatement
* @throws java.sql.SQLException
* @param objectId
* @param statement
*/
private void prepareBlobSelectStatement(PreparedStatement statement, long objectId) throws SQLException
{
statement.setLong(1, objectId);
}
 
You don't like waffles? Well, do you like this tiny ad?
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!