Java Reference
In-Depth Information
The annotations provide the driver, so the Sql class can be used normally.
Because a member of a class can only have a single instance of a particular annotation,
the @Grapes annotation is used to combine multiple @Grab annotations. The next listing
computes complex values and stores them in a database table.
Listing 5.13. Using Apache Commons Math and a database driver together
@GrabConfig(systemClassLoader=true)
@Grapes([
@Grab('org.apache.commons:commons-math3:3.0'),
@Grab(group='com.h2database', module='h2', version='1.2.140')
])
import static java.lang.Math.*
import org.apache.commons.math3.complex.Complex
import org.apache.commons.math3.complex.ComplexUtils
import groovy.sql.Sql
S ql sql = Sql.newInstance(url:'jdbc:h2:mem:',driver:'org.h2.Driver')
sql.execute '''
create table coordinates (
id bigint generated by default as identity,
angle double not null,
x double not null,
y double not null,
primary key (id)
)
'''
int n = 20
def delta = 2*PI/n
(0..<n). each { num ->
Complex c = ComplexUtils.polar2Complex(1, num*delta)
sql.execute """
insert into coordinates(id,angle,x,y)
values(null, ${i*delta}, $c.real, $c.imaginary)
"""
}
sql.rows('select * from coordinates'). each { row ->
println "$row.id, $row.angle, $row.x, $row.y"
}
The script creates a table to hold x and y coordinates at 20 points along a circle. The Com-
plexUtils.polar2Complex method takes a radius (here using one for simplicity)
Search WWH ::




Custom Search