|
Jython is a dynamic interpreted language Python writen in Java. It allows to automate tasks for management and
administration of JDO aware applications using scripts. Jython provides a command line interface that allows you
to persist or query databases using JPOX.
To run Jython you must first install it. It can be downloaded from Jython. After
installing Jython, you have to update its classpath to include JPOX jars, JPOX dependencies,
the JDBC driver jars, the persistent classes and metadata files. The classpath can be set in the environment variable CLASSPATH.
Start Jython by lauching jython.bat under Windows or jython.sh under Linux.
D:\jython2_2alpha1>jython
Jython 2.2a1 on java1.5.0_06 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>>
Jython interpreter evaluates instructions either interactively or in batch mode. In interactive mode, Jython will evaluate every
command at the time it is provided. In batch mode, Jython will load a file (.py) and interprete all commands.
To start Jython in batch mode, you run the jython command followed by the script file name (sample.py), and to start in interactive
mode, you simply run the jython command.
The below script exemplifies the persistence of two objects and query for printing to the console.
#imports
from java.io import File
from javax.jdo import JDOHelper
#create a PMF and obtain a PersistenceManager
props = File("/home/PMFProperties.properties")
pmf = JDOHelper.getPersistenceManagerFactory(props)
pm = pmf.getPersistenceManager()
#create some persistent objects
from org.jpox.samples.company import Person
erik = Person(1,'Erik','Bengtson','erik@jpox.org')
andy = Person(2,'Andy','Jefferson','andy@jpox.org')
pm.currentTransaction().begin()
pm.makePersistent(erik)
pm.makePersistent(andy)
pm.currentTransaction().commit()
#query persistent objects
pm.currentTransaction().begin()
q = pm.newQuery(Person)
q.setResult("firstName,lastName")
result = q.execute()
#loop though results
print "First loop"
for r in result:
print "first name:", r[0], "last name:", r[1]
#loop though results (another form)
from java.lang import System
System.out.println("Second loop")
for r in result:
System.out.println("first name: "+r[0]+" last name: "+r[1])
#release resources
pm.currentTransaction().commit()
pm.close()
pmf.close()
The console have the below ouput after running the above script.
First loop
first name: Andy last name: Jefferson
first name: Erik last name: Bengtson
Second loop
first name: Andy last name: Jefferson
first name: Erik last name: Bengtson
|