I made a custom maven Archetype and based on the Maven Documentation, added the file archetype-post-generate.groovy to the src/main/resources/META-INF folder.
In this groovy script I want to connect to a database and take some actions according to the data.
The script is as follow:
import groovy.sql.Sql
Sql.withInstance(
'jdbc:sqlserver://localhost:1433;databaseName=db;',
'sa',
'pass',
'com.microsoft.sqlserver.jdbc.SQLServerDriver') { sql ->
List rows = sql.rows('SELECT top 5 id, description FROM Project')
for(row in rows) {
println row.getProperty("id")
println row.getProperty("description")
println "/*************\\"
}
}
After installing the archetype when I generate a module with it, once the script is executed, the following error is raised:
Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.2.0:generate (default-cli) on project standalone-pom: startup failed:
Script1.groovy: 1: unable to resolve class groovy.sql.Sql
@ line 1, column 1.
import groovy.sql.Sql
^
1 error
Is there any solution to resolve this problem?
CodePudding user response:
According to @emilles's guidance and Groovy documentation, we can add any library to the classpath of script using the @Grab
annotation.
For example:
@Grab('org.codehaus.groovy:groovy-sql:2.4.16')
@Grab('com.microsoft.sqlserver:mssql-jdbc:8.4.1.jre8')