Defining Database Queries Inside Velocity Templates

I look at various libraries that can be used as templates in my project, and now Apache Velocity looks like a good candidate. I have the following doubts regarding its use:

Is it possible to specify the SQL database query in the template and use the return value of the query to populate the parameter ?. I found the following example in the Velocity user guide:

Hello, #set( $result = $query.criteria("name") ) Your username is $result. 

However, the manual explains little SQL query execution. Is it possible to define a SQL SELECT query that returns a value and assigns this value to a variable in the template? I am wondering if something like the example below is possible?

 Hello, #set( $result = $executeQuery("SELECT name FROM user") ) Your username is $result. 

It would be appreciated if you could shed some light on this. Is anyone enough to provide an example, or point me to a place where I can find additional documentation about this?

+5
java velocity
source share
3 answers

I would recommend something like http://velosurf.sourceforge.net/ instead of directly embedding requests.

+3
source share

Velocity is a very light templating mechanism, it has very little functionality. It works to interpolate variables defined by (you) in the context into a template file. By default, the context is empty , which means that there are no variables for the template used. Velocity does not allow you to create new objects of custom classes, all that allows you to use string and number literals, as well as maps and lists:

 #set ($n = 5) #set ($s = 'Hello New World!') #set ($m = {'four' : 4, 'five' : $n}) #set ($a = ['x', 'y', 'z']) 

You are responsible for creating smart Velocity by populating the context with useful objects prior to interpolation. You can use some Velocity Tools as a starting point. You can add your own tools, such as the SQL tool, which allows you to run queries. Or you can use a higher level structure that uses speed and which already offers the rich set of tools available in the templates.

So, to answer your question, you can execute any SQL query that you want, as long as you add an object to the context that can execute such statements. You should learn more about how to use Velocity correctly in your developer guide .

+2
source share

This is for HQL (you can try with others using this as an example)

A general example showing how to display the first 5 results of a given query:

 #set($hql = "<query here>") #set($results = $xwiki.searchDocuments($hql, 5, 0)) #foreach ($item in $results) * $item #end 

The examples below will show the various HQL queries you can write. Simple request

Displays all documents created by XWiki.JohnDoe

 #set($hql = "where doc.creator='XWiki.JohnDoe'") 

Additional Information

you can look at link

0
source share

All Articles