Rectangle 27 0

Create/Alter book table

CREATE TABLE book (
   id     integer PRIMARY KEY,
   name   varchar(50)
);
Alter table book add image bytea;
Alter table book add xml text;
Rectangle 27 0

Run Client to access EJB

Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file.

Verify the following output in Netbeans console.

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: learn testing
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. learn testing
image bytes: [
0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 ]
<book><name>learn testing</name></book>
BUILD SUCCESSFUL (total time: 20 seconds)
Rectangle 27 0

Example Application

Let us create a test EJB application to test blob/clob support in EJB 3.0.

StepDescription
Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand clob/blob objects in ejb concepts.Create LibraryPersistentBean.java under package com.tutorialspoint.stateless. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged.
Clean and Build the application to make sure business logic is working as per the requirements.Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
Rectangle 27 0

LibraryPersistentBeanRemote.java

package com.tutorialspoint.stateless;

import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Remote;

@Remote
public interface LibraryPersistentBeanRemote {

   void addBook(Book bookName);

   List<Book> getBooks();
    
}
Rectangle 27 0

Oracle JDBC drivers before Oracle 11 had a 4k LOB size limit, so the only way to write lobs is to insert and empty lob, and the select the lobs back and writing into them. This is what you are seeing.

For Oracle 11g you should use "Oracle11", this platform will not use the locator, as it should no longer be required in Oracle 11g. You may need to be on the latest version (2.4) for this. Using "Oracle" as your target will also not use the locator.

You can also disable the locator usage in your platform with a customizer,

platform.setShouldUseLocatorForLOBWrite(false);

ejb 3.0 - EclipseLink/JPA persisting large(blob) entity, performance i...

jpa ejb-3.0 eclipselink
Rectangle 27 0

You may be inadvertently using an old PostgreSQL JDBC driver. You can test this by injecting a DataSource somewhere (e.g. an EJB) and executing the following on it:

System.out.println(ds.getConnection().getMetaData().getDriverVersion());

In my case, it was 8.3 which was unexpected since I was deploying with 9.1 drivers.

To find out where this was coming from:

System.out.println(Class.forName("org.postgresql.Driver").getProtectionDomain().getCodeSource().getLocation());

As it turned out for me, it was in the lib directory of my GlassFish domain. I'm not sure how it got there - GlassFish certainly doesn't ship that way - so I just removed it and the problem went away.

java - Getting nearly double the length when reading byte[] from postg...

java postgresql jpa blob eclipselink
Rectangle 27 0

Book.java

package com.tutorialspoint.entity;

import com.tutorialspoint.callback.BookCallbackListener;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name="book")
public class Book implements Serializable{
    
   private int id;
   private String name;    
   private byte[] image;   
   private String xml;

   public Book(){        
   }

   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Lob @Basic(fetch= FetchType.EAGER)
   public byte[] getImage() {
      return image;
   }

   public void setImage(byte[] image) {
      this.image = image;
   }

   @Lob @Basic(fetch= FetchType.EAGER)
   public String getXml() {
      return xml;
   }

   public void setXml(String xml) {
      this.xml = xml;
   }
}
Rectangle 27 0

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
Rectangle 27 0

@Lob annotation can be applied to a Serializable object. You could then declare :

@Lob
private MySmartLOB data;

and

public class MySmartLOB implements Serializable
    {
         private void writeObject(java.io.ObjectOutputStream out)
           throws IOException{
           // tranfer data from local storage to 'out'
         }
         private void readObject(java.io.ObjectInputStream in)
            throws IOException, ClassNotFoundException{
           // tranfer data from 'in' to local storage
         }
     }

jpa - Save blob using a stream from EJB to database (in a memory effic...

jpa ejb blob java-ee-6 jboss7.x
Rectangle 27 0

EJB - Blobs/Clobs

EJB 3.0 provides support for Blob and Clob types using @Lob annotation. Following java types can be mapped using @Lob annotation.

@Entity
@Table(name="books")
@EntityListeners(BookCallbackListener.class)
public class Book implements Serializable{
   ...
   private byte[] image;    

   @Lob @Basic(fetch= FetchType.EAGER)
   public byte[] getImage() {
      return image;
   }
   ...
}
Rectangle 27 0

Example Application

Let us create a test EJB application to test blob/clob support in EJB 3.0.

StepDescription
Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand clob/blob objects in ejb concepts.Create Book.java under package com.tutorialspoint.entity. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged.
Clean and Build the application to make sure business logic is working as per the requirements.Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
Rectangle 27 0

LibraryPersistentBean.java

package com.tutorialspoint.stateless;

import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
    
   public LibraryPersistentBean(){
   }

   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;         

   public void addBook(Book book) {
      entityManager.persist(book);
   }    

   public List<Book> getBooks() {
      return entityManager.createQuery("From Book").getResultList();
   }
}
Rectangle 27 0

EJBTester.java

package com.tutorialspoint.test;
   
import com.tutorialspoint.stateful.LibraryBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBTester {

   BufferedReader brConsoleReader = null; 
   Properties props;
   InitialContext ctx;
   {
      props = new Properties();
      try {
         props.load(new FileInputStream("jndi.properties"));
      } catch (IOException ex) {
         ex.printStackTrace();
      }
      try {
         ctx = new InitialContext(props);            
      } catch (NamingException ex) {
         ex.printStackTrace();
      }
      brConsoleReader = 
      new BufferedReader(new InputStreamReader(System.in));
   }
   
   public static void main(String[] args) {

      EJBTester ejbTester = new EJBTester();

      ejbTester.testBlobClob();
   }
   
   private void showGUI(){
      System.out.println("**********************");
      System.out.println("Welcome to Book Store");
      System.out.println("**********************");
      System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
   }
   
   private void testBlobClob(){

      try {
         int choice = 1; 

         LibraryPersistentBeanRemote libraryBean = 
        (LibraryPersistentBeanRemote)
         ctx.lookup("LibraryPersistentBean/remote");

         while (choice != 2) {
            String bookName;
            String publisherName;
            String publisherAddress;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               String xml = "<book><name>"+bookName+"</name></book>";
               Book book = new Book();
               book.setName(bookName);                                        
               byte[] imageBytes = {0x32, 0x32,0x32, 0x32,0x32,
               0x32,0x32, 0x32,
               0x32, 0x32,0x32, 0x32,0x32, 0x32,0x32, 0x32,
               0x32, 0x32,0x32, 0x32,0x32, 0x32,0x32, 0x32
               };
               book.setImage(imageBytes);
               book.setXml(xml);

               libraryBean.addBook(book);          
            } else if (choice == 2) {
               break;
            }
         }

         List<Book> booksList = libraryBean.getBooks();

         System.out.println("Book(s) entered so far: " + booksList.size());
         int i = 0;
         for (Book book:booksList) {
            System.out.println((i+1)+". " + book.getName());
            byte[] imageByts = book.getImage();
            if(imageByts != null){
               System.out.print("image bytes: [");
               for(int j = 0; j < imageByts.length ; j++){
                  System.out.print("0x" 
                  + String.format("%x", imageByts[j]) +" ");
               }            
               System.out.println("]");
            }        
            System.out.println(book.getXml());
            i++;
         }           
      } catch (Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }finally {
         try {
            if(brConsoleReader !=null){
               brConsoleReader.close();
            }
         } catch (IOException ex) {
            System.out.println(ex.getMessage());
         }
      }
   }
}

EJBTester is doing the following tasks.

Rectangle 27 0

CREATE TABLE EJB__TIMER__TBL (
        `CREATIONTIMERAW`      BIGINT        NOT NULL,
        `BLOB`                 BLOB,
        `TIMERID`              VARCHAR(255)  NOT NULL,
        `CONTAINERID`          BIGINT        NOT NULL,
        `OWNERID`              VARCHAR(255)  NULL,
        `STATE`                INTEGER       NOT NULL,
        `PKHASHCODE`           INTEGER       NOT NULL,
        `INTERVALDURATION`     BIGINT        NOT NULL,
        `INITIALEXPIRATIONRAW` BIGINT        NOT NULL,
        `LASTEXPIRATIONRAW`    BIGINT        NOT NULL,
        `SCHEDULE`             VARCHAR(255)  NULL,
        `APPLICATIONID`        BIGINT        NOT NULL,
        CONSTRAINT `PK_EJB__TIMER__TBL` PRIMARY KEY (`TIMERID`)
    );
http://localhost:4848
  • Then fill out Timer Datasource: with your JDBC Resource eg. [mysql-pu]
...
INFO: [TimerBeanContainer] Created  TimerBeanContainer: TimerBean
INFO: EJB5181:Portable JNDI names for EJB TimerBean: [java:global/ejb-timer-service-app/TimerBean, java:global/ejb-timer-service-app/TimerBean!com.sun.ejb.containers.TimerLocal]
INFO: WEB0671: Loading application [ejb-timer-service-app] at [/ejb-timer-service-app]
INFO: EJB5109:EJB Timer Service started successfully for data source [mysql-pu]
INFO: Setting DBReadBeforeTimeout to false
INFO: ==> Restoring Timers ... 
INFO: There are no EJB Timers owned by this server
INFO: <== ... Timers Restored.
...

java - Set/configure the EJB Timer Service’s DataSource - Stack Overfl...

java java-ee glassfish ejb-3.1
Rectangle 27 0

JBoss Application server log output

...
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
...
Rectangle 27 0

The problem with this error is that the operating system cannot allocate more memory for the threadstack so it fails to instantiate a new thread. Probably it's not a JBoss issue. You have to reduce the amount of memory each thread uses. A fine size for JBoss threads is 128k or 256k.

You can look at this articles from JBoss documentation

To reduce this memory amount, in linux I found the command:

ulimit -s 256

java - JPA persist large blob - Stack Overflow

java jpa ejb blob
Rectangle 27 0

You may be inadvertently using an old PostgreSQL JDBC driver. You can test this by injecting a DataSource somewhere (e.g. an EJB) and executing the following on it:

System.out.println(ds.getConnection().getMetaData().getDriverVersion());

In my case, it was 8.3 which was unexpected since I was deploying with 9.1 drivers.

To find out where this was coming from:

System.out.println(Class.forName("org.postgresql.Driver").getProtectionDomain().getCodeSource().getLocation());

As it turned out for me, it was in the lib directory of my GlassFish domain. I'm not sure how it got there - GlassFish certainly doesn't ship that way - so I just removed it and the problem went away.

java - Getting nearly double the length when reading byte[] from postg...

java postgresql jpa blob eclipselink
Rectangle 27 0

You may be inadvertently using an old PostgreSQL JDBC driver. You can test this by injecting a DataSource somewhere (e.g. an EJB) and executing the following on it:

System.out.println(ds.getConnection().getMetaData().getDriverVersion());

In my case, it was 8.3 which was unexpected since I was deploying with 9.1 drivers.

To find out where this was coming from:

System.out.println(Class.forName("org.postgresql.Driver").getProtectionDomain().getCodeSource().getLocation());

As it turned out for me, it was in the lib directory of my GlassFish domain. I'm not sure how it got there - GlassFish certainly doesn't ship that way - so I just removed it and the problem went away.

java - Getting nearly double the length when reading byte[] from postg...

java postgresql jpa blob eclipselink