Blob example in java

How to manipulate a blob in java?

A BLOB (Binary Large Object) is a collection of binary data stored as a single entity in a database management system. Manipulating BLOB data in Java can be a challenge, but it is essential for certain applications that require the storage and retrieval of binary data such as images, videos, and audio files. In this article, we will look at different methods for manipulating BLOB data in Java.

Method 1: Using JDBC

Using JDBC to manipulate a BLOB in Java

String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; Connection connection = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO mytable (id, image) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(sql);
File file = new File("image.png"); FileInputStream inputStream = new FileInputStream(file);
statement.setInt(1, 1); statement.setBinaryStream(2, inputStream, (int) file.length());
String sql = "SELECT image FROM mytable WHERE >; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, 1); ResultSet result = statement.executeQuery(); if (result.next())  InputStream inputStream = result.getBinaryStream("image"); // do something with the BLOB data >
inputStream.close(); statement.close(); connection.close();

This is how you can manipulate a BLOB in Java using JDBC. By following these steps, you can insert and retrieve BLOB data from a database.

Method 2: Using Hibernate

Here are the steps to manipulate a BLOB using Hibernate:

  1. First, create a Java class to represent the BLOB data. This class should have a byte array field to hold the binary data.
public class BlobData  private byte[] data; public BlobData() > public BlobData(byte[] data)  this.data = data; > public byte[] getData()  return data; > public void setData(byte[] data)  this.data = data; > >
  1. Next, create a Hibernate entity class to map the BLOB data to a database table. This class should have a field of type BlobData annotated with @Lob to indicate that it should be stored as a BLOB in the database.
@Entity @Table(name = "my_table") public class MyEntity  @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Lob @Column(name = "blob_data") private BlobData blobData; public Long getId()  return id; > public void setId(Long id)  this.id = id; > public BlobData getBlobData()  return blobData; > public void setBlobData(BlobData blobData)  this.blobData = blobData; > >
  1. To save a BLOB to the database using Hibernate, create an instance of the MyEntity class and set its blobData field to a new BlobData object containing the binary data. Then, use the EntityManager to persist the entity to the database.
byte[] binaryData = //get binary data from some source BlobData blobData = new BlobData(binaryData); MyEntity entity = new MyEntity(); entity.setBlobData(blobData); entityManager.persist(entity);
  1. To retrieve a BLOB from the database using Hibernate, first load the entity from the database using its ID. Then, get the BlobData object from the blobData field of the entity.
MyEntity entity = entityManager.find(MyEntity.class, entityId); BlobData blobData = entity.getBlobData(); byte[] binaryData = blobData.getData();
  1. To update a BLOB in the database using Hibernate, load the entity from the database using its ID, set the blobData field to a new BlobData object containing the updated binary data, and then use the EntityManager to merge the entity back into the database.
byte[] newBinaryData = //get updated binary data from some source BlobData newBlobData = new BlobData(newBinaryData); MyEntity entity = entityManager.find(MyEntity.class, entityId); entity.setBlobData(newBlobData); entityManager.merge(entity);

That’s it! With these steps, you can manipulate BLOB data using Hibernate in Java.

Method 3: Using Spring JPA

To manipulate a BLOB in Java using Spring JPA, you can follow these steps:

@Entity public class MyEntity  @Id private Long id; @Lob private byte[] blobData; // getters and setters >
@Repository public interface MyEntityRepository extends JpaRepositoryMyEntity, Long>  >
@Service public class MyService  @Autowired private MyEntityRepository repository; public void saveBlobData(byte[] data)  MyEntity entity = new MyEntity(); entity.setBlobData(data); repository.save(entity); > public byte[] getBlobData(Long id)  OptionalMyEntity> optionalEntity = repository.findById(id); if (optionalEntity.isPresent())  return optionalEntity.get().getBlobData(); > else  return null; > > >

In the above code, the saveBlobData method saves the BLOB data to the database by creating a new MyEntity object and setting its blobData field. The getBlobData method retrieves the BLOB data from the database by calling the findById method of the repository and returning the blobData field of the resulting entity.

Note that the @Lob annotation is used to indicate that the field should be stored as a large object in the database. Also, the byte[] type is used to represent the BLOB data in Java.

That’s it! With these simple steps, you can manipulate BLOB data in Java using Spring JPA.

Method 4: Using Apache Commons IO

How to manipulate a BLOB in Java using Apache Commons IO

Step 1: Import the necessary libraries

import org.apache.commons.io.IOUtils; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob;

Step 2: Retrieve the BLOB from the database

// Assume that the BLOB is stored in a column named "blob_column" in a table named "my_table" // and that the database connection is stored in a variable named "connection" String sql = "SELECT blob_column FROM my_table WHERE >; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, id); ResultSet resultSet = statement.executeQuery(); resultSet.next(); Blob blob = resultSet.getBlob("blob_column");

Step 3: Read the contents of the BLOB into a byte array

InputStream inputStream = blob.getBinaryStream(); byte[] bytes = IOUtils.toByteArray(inputStream);

Step 4: Manipulate the byte array as needed

// For example, you could convert the byte array to a string String string = new String(bytes);

Step 5: Write the modified byte array back to the BLOB

// Assume that the modified byte array is stored in a variable named "modifiedBytes" OutputStream outputStream = blob.setBinaryStream(0); IOUtils.write(modifiedBytes, outputStream); outputStream.close();

That’s it! You have successfully manipulated a BLOB in Java using Apache Commons IO.

Источник

Java Blob tutorial with examples

The representation (mapping) in the Java programming language of an SQL BLOB value.

Introduction

The representation (mapping) in the Java programming language of an SQL BLOB value.

An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table.

By default drivers implement Blob using an SQL locator(BLOB), which means that a Blob object contains a logical pointer to the SQL BLOB data rather than the data itself.

A Blob object is valid for the duration of the transaction in which is was created.

Methods in the interfaces *ResultSet*, *CallableStatement*, and *PreparedStatement*, such as *getBlob* and *setBlob* allow a programmer to access an SQL *BLOB* value.

The Blob interface provides methods for getting the length of an SQL BLOB (Binary Large Object) value, for materializing a BLOB value on the client, and for determining the position of a pattern of bytes within a BLOB value.

In addition, this interface has methods for updating a BLOB value.

All methods on the Blob interface must be fully implemented if the JDBC driver supports the data type.

Example

The following code shows how to use Blob from java.sql.

import java.io.ObjectInputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.ImageIcon; public class Main < public static void main(String[] args) throws Exception < ImageIcon image;// w w w. d e m o 2 s .c o m Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/c:\\employee"); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select photo from employee where name = 'Duke'"); if (rs.next()) < Blob photo = rs.getBlob(1); ObjectInputStream ois = null; ois = new ObjectInputStream(photo.getBinaryStream()); image = (ImageIcon) ois.readObject(); > s.close(); > >
import java.io.ObjectInputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.ImageIcon; public class Main < public static void main(String[] args) throws Exception < ImageIcon image;/*w w w. d e m o 2 s .c o m */ Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/c:\\employee"); Statement s = con.createStatement(); ResultSet rs = s.executeQuery("select photo from employee where name = 'Duke'"); if (rs.next()) < Blob photo = rs.getBlob(1); ObjectInputStream ois = null; ois = new ObjectInputStream(photo.getBinaryStream()); image = (ImageIcon) ois.readObject(); > s.close(); > >
import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Main < public static void main(String[] argv) throws Exception < String driverName = "com.jnetdirect.jsql.JSQLDriver"; Class.forName(driverName); String serverName = "127.0.0.1"; String portNumber = "1433"; String mydatabase = serverName + ":" + portNumber; String url = "jdbc:JSQLConnect://" + mydatabase; String username = "username"; String password = "password"; Connection connection = DriverManager.getConnection(url, username, password); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT col_blob FROM mysql_all_table"); if (rs.next()) < Blob blob = rs.getBlob("col_blob"); long blobLength = blob.length(); int pos = 1; // position is 1-based int len = 10; byte[] bytes = blob.getBytes(pos, len); InputStream is = blob.getBinaryStream(); int b = is.read(); >/*w w w. d e mo 2 s . c o m */ > >

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Читайте также:  Context Path Example
Оцените статью