Search code examples
javapostgresqlruby-on-rails-4jruby

rails store java object to postgres


I am running rails4 using jruby and postgres as the db. I have a jar file that I call to create an instance of a java object. The java object is a bridge to a backend calculation engine on a different machine. It queries the calculation engine and stores the return values as instance variables. I need to keep a unique instance of this object per session. Is it possible to store instances of the java object in postgres? I really have no idea where to start on this and looking on google hasn't helped so any advice is appreciated. Thanks.


Solution

  • Is it possible to store instances of the java object in postgres?

    Yes, but it's usually a bad idea.

    If you must...

    If you really want to do this, you can use Java's serialization framework to get a byte[] representation of the object, which can then be stored in a bytea field in the PostgreSQL database via PgJDBC. I'm sure Rails has some mechanism to work with binary data too, so look that up if you'd prefer to do it via Rails.

    Better ways for objects that're just data containers

    If this object doesn't have any logic, if it's just a bunch of instance variables with no interesting methods to act on them, you should map the object to fields in a relation, so you save each instance variable as a field. Then provide a constructor to do the reverse.

    An alternative is to instead serialize it to a standard-ish format like json and store that in the database. Give your object toJson and fromJson methods to do this manually, or use JAXB to serialize/deserialize it. (JAXB usually uses XML, and you can use that, or you can add JSON support with plugins).

    Better for true objects with logic

    If the object is a "business object", i.e. it manages its data and has logic and rules, then you might want to consider remote access instead.

    In the conventional Java world you'd instead do this using remoting, where you do remote procedure calls to the instance running on the main machine, probably by wrapping the instance in an EJB3 and generating an EJB3 client stub to transparently talk to it.

    A more modern (IMO) and simpler to write (though more verbose to use) approach is to use JAX-RS to provide a simple web service interface you can use to talk to the object remotely.