Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lightweight Groovy persistence

What are some lightweight options for persistence in Groovy? I've considered serialization and XML so far but I want something a bit more robust than those, at least so I don't have to rewrite the entire file every time. Ideally, it would:

  • Require no JARs in classpath, using Grapes instead
  • Require no external processes, administration, or authentication (so all embedded)
  • Support locking

I plan on using it to cache some information between runs of a standalone Groovy script. I imagine responses will focus around SQL and NoSQL databases. Links to pages demonstrating this usage would be appreciated. Thanks!

like image 579
dromodel Avatar asked Jul 05 '12 13:07

dromodel


1 Answers

Full SQL Database

The h2 in-process SQL database is very easy to use. This is the same database engine grails uses by default, but it's simple to use in a groovy script as well:

@GrabConfig(systemClassLoader=true)
@Grab(group='com.h2database', module='h2', version='1.3.167')

import groovy.sql.Sql

def sql = Sql.newInstance("jdbc:h2:hello", "sa", "sa", "org.h2.Driver")
sql.execute("create table test (id int, value text)")
sql.execute("insert into test values(:id, :value)", [id: 1, value: 'hello'])
println sql.rows("select * from test")

In this case the database will be saved to a file called hello.h2.db.

Simple Persistent Maps

Another alternative is jdbm, which provides disk-backed persistent maps. Internally, it uses Java's serialization. The programming interface is much simpler, but it's also much less powerful than a full-blown SQL db. There's no support for concurrent access, but it is synchronized and thread safe, which may be enough depending on your locking requirements. Here's a simple example:

@Grab(group='org.fusesource.jdbm', module='jdbm', version='2.0.1')

import jdbm.*

def recMan = RecordManagerFactory.createRecordManager('hello')
def treeMap = recMan.treeMap("test")
treeMap[1] = 'hello'
treeMap[100] = 'goodbye'
recMan.commit()
println treeMap

This will save the map to a set of files.

like image 198
ataylor Avatar answered Oct 19 '22 02:10

ataylor