Invalid column name error - grails

I am trying to sort by transient property but fails with SQL Error: Invalid column name error .
Pls find below my code :
In domain class declared :
static transients = ['sortCandidateLastName']
Query which I am trying to execute:
When I am trying to run the below query in Oracle :It runs fine
( select * from ( select row_.* ,rownum rownum_ from ( select * from booking b where b.marked_deleted='N' order by (select c.cand_id from candidate c where b.cand_id = c.cand_id) asc ) row_ where rownum <= 15 ) where rownum > 0)
GSP code:
<g:sortableColumn property="sortCandidateLastName" title="Sort By Candidate Last Name" />
But when Hibernate is trying to read it ,it throws Invalid column name : ResultSet.getInt(clazz_)

Transient properties are not persisted so it's impossible to write a query which sorts by a transient property. If you retrieve a list of objects from a query and want to sort them by a transient property, you'll have to do it in Groovy code, e.g.
// an example domain class with a transient property
class Book {
private static Long SEQUENCE_GENERATOR = 0
String isbn
String title
Long sequence = ++SEQUENCE_GENERATOR
static transients = ['sequence']
}
// get a list of books from the DB and sort by the transient property
def books = Book.list()
books.sort { it.sequence }

You cant sort on transient field. There is no actual database column for a transient field! So your sql would always throw an error!

I tried using jdbcTemplate and gives me the required functionality.
Code snippet:
GSP Layer:
<g:sortable property="sortCandidateLastName">
<g:message code="booking.alphabetical.label" default="Alphabetical(A-Z)" />
</g:sortable>
Domain layer:
just defined a transient property :
static transients = ['sortCandidateLastName']
Reason for adding the transient field : SO that it doesn't throw me any exception like missing property.
Controller layer :
if(params.sort == "sortCandidateLastName" )
{
bookingCandList= bookingService.orderByCandidateLastName(params.max, params.order,params.offset.toInteger())//Booking.getSortCandidateLastName(params.max, params.order,params.offset.toInteger()) //
}
Service layer :
def jdbcTemplate
public List orderByCandidateLastName(Integer max, String sortOrder,Integer offset) {
println "Inside the getcandidateLastName ${max} :: offset ${offset}"
def sortedList
int minRow = offset
int maxRow = offset+max
String queryStr = " select * from " +
" ( "+
" select row_.* " +
" ,rownum rownum_ " +
" from " +
" ( " +
" select * from booking b where b.item_id= 426 and b.marked_deleted='N' order by " +
" (select c.cand_id from candidate c where b.cand_id = c.cand_id) ${sortOrder} "+
" ) row_ "+
"where rownum <= ${maxRow} " +
") " +
"where rownum > ${minRow}"
return jdbcTemplate.queryForList(queryStr)
}
Configuration of JDBC template :
// Place your Spring DSL code here
import org.springframework.jdbc.core.JdbcTemplate
beans = {
..........
jdbcTemplate(JdbcTemplate) {
dataSource = ref('dataSource')
}
}
Hope it helps to ..
Cheers

Related

WIQL query to get all item under a workitem

I am looking for a query where i can return all work items and their relation from a area path.
for example : project 1
i need all Featured all Userstories mapped to it all workitem and Bug mapped to userstories,
in short if i took a bug from the object i need somthing like parent id where i can match with the userstory.
string query1 = " SELECT * FROM WorkItemLinks " +
" WHERE ( [System.IterationPath] Under 'iteration1' )" +
" AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' )" +
" ORDER BY [Microsoft.VSTS.Scheduling.StartDate]";
which throwing an error like below
An exception of type 'Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException' occurred in Microsoft.TeamFoundation.WorkItemTracking.Client.dll but was not handled in user code
Additional information: TF51005: The query references a field that does not exist. The error is caused by «[System.IterationPath]».
when i checked the dll's are refereed correctly and when i re wrote the query like this the query is working fine
string query = " SELECT * FROM WorkItems"+
" WHERE ( [System.IterationPath] Under 'iteration1' )" +
//" AND ([System.State] = 'Active' OR [System.State] = 'Assessed' ) "+
//" AND ( [Microsoft.VSTS.Scheduling.StartDate] <= '09/13/2017' AND [Microsoft.VSTS.Scheduling.FinishDate] >= '09/13/2017' )"+
" ORDER BY [Microsoft.VSTS.Scheduling.StartDate]";
but this query result does not give the relation ship that if a work item mapped as a child to other i need parent id in the work item object. how to get that. Thanks in advance.
You can try below query:
Install Nuget Package Microsoft.TeamFoundationServer.ExtendedClient for the project.
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
namespace _0925_WIQL
{
class Program
{
static void Main(string[] args)
{
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
new Uri("http://server:8080/tfs/CollectionLC"));
WorkItemStore workItemStore = (WorkItemStore)tpc.GetService(typeof(WorkItemStore));
string query1= " SELECT * FROM WorkItemLinks " +
" WHERE ( Source.[System.IterationPath] Under 'TeamProject\\Iteration 1' )" +
" AND ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' )" +
" ORDER BY [Microsoft.VSTS.Scheduling.StartDate]";
Query query = new Query(workItemStore, query1);
WorkItemLinkInfo[] witLinkInfos = query.RunLinkQuery();
foreach (WorkItemLinkInfo witinfo in witLinkInfos)
{
.......
}
Besides, you can also use Wiql Editor. If you want to get all the parent workitems (IDs) from a specific child work item (ID), you can use below WIQL:
SELECT
[System.Id],
[System.WorkItemType],
[System.Title],
[System.AssignedTo],
[System.State]
FROM workitemLinks
WHERE ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward')
AND ([Target].[System.Id] = 25)
ORDER BY [System.Id]
MODE (Recursive, ReturnMatchingChildren)

java.lang.IllegalStateException: No primary SDN label exists .. (i.e one with starting with _)

I'm trying to create nodes using SDN 3.0.2 and Neo4j 2.0.1
Here is how I'm doing :
query = "MATCH (root:Date) " +
"CREATE UNIQUE (root)<-[:`"+year+"`]-(y:Year {value:'"+year+"Y"+"'})" +
"<-[:`"+month+"`]-(m:Month {value:'"+year+"Y"+month+"M"+"'})" +
"<-[:`"+day+"`]-(d:Day {value:'"+year+"Y"+month+"M"+day+"D"+"'}) " +
"RETURN d";
Iterable<Day> days = template.query(query, map).to(Day.class);
Transaction tx = template.getGraphDatabaseService().beginTx();
Set<Day> result = IteratorUtil.asSet(days);
tx.close();
Executing this way, I'm getting java.lang.IllegalStateException: No primary SDN label exists .. (i.e one with starting with _) For the Set<Day> result = IteratorUtil.asSet(days)
While It works fine if I delete Set<Day> result = IteratorUtil.asSet(days)
But I actually need to return the result which is a unique Day entity.
Am I missing something?
Here's the Day POJO:
#NodeEntity
#TypeAlias(value="Day")
public class Day implements Serializable {
private static final long serialVersionUID = 1L;
#GraphId
private Long nodeId;
#Indexed(unique=true)
private String id;
//#Indexed(indexType=IndexType.FULLTEXT, indexName = "days")
private String value;
#RelatedTo(type="NEXT_DAY", direction = Direction.BOTH)
private Day next;
private Month month;
//Other relationships to different entities
//Getters & setters
//Empty & with params constructors
}
I had to add _Label in the cypher query:
query = "MATCH (root:Date) " +
"CREATE UNIQUE (root)<-[:`"+year+"`]-(y:Year:_Year {value:'"+year+"Y"+"'})" +
"<-[:`"+month+"`]-(m:Month:_Month {value:'"+year+"Y"+month+"M"+"'})" +
"<-[:`"+day+"`]-(d:Day:_Day {value:'"+year+"Y"+month+"M"+day+"D"+"'}) " +
"RETURN d";

Querying values from a Map Property in a Grails Domain Class

I found the solution Burt Beckwith offered in this question: add user define properties to a domain class and think this could be a viable option for us in some situations. In testing this, I have a domain with a Map property as described in the referenced question. Here is a simplified version (I have more non-map properties, but they are not relevant to this question):
class Space {
String spaceDescription
String spaceType
Map dynForm
String toString() {
return (!spaceType)?id:spaceType + " (" + spaceDescription + ")"
}
}
I have some instances of space saved with some arbitrary data in the dynForm Map like 'Test1':'abc' and 'Test2':'xyz'.
I am trying to query this data and have succesfully used HQL to filter doing the following:
String className = "Space"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def res = clazz.executeQuery("select distinct space.id, space.spaceDescription from Space as space where space.dynForm['Test1'] = 'abc' " )
log.debug "" + res
I want to know if there is a way to select an individual item from the Map dynForm in a select statement. Somehting like this:
def res = clazz.executeQuery("select distinct space.id, elements(space.dynForm['Test1']) from Space as space where space.dynForm['Test1'] = 'abc' " )
I can select the entire map like this:
def res = clazz.executeQuery("select distinct elements(space.dynForm) from Space as space where space.dynForm['Test1'] = 'abc' " )
But I just want to get a specific instance based on the string idx.
how about to use Criteria, but i don't have any sql server so i haven't tested yet.
def results = Space.createCriteria().list {
dynForm{
like('Test1', 'abc')
}
}

Grails calculated field in SQL

I have a domain
class InvoiceLine {
String itemName
BigDecimal unitCost
Integer quantity
}
}
I would like to come up with a grails closure using .withCriteria that does an aggregation of the (unitCost * quantity) so that I end up with sql
select item_name, sum(unit_cost * quantity) from invoice_line group by item_name;
For now, the best I could come up with is
def result = InvoiceLine.withCriteria {
projections {
groupProperty('itemName')
sum ('quantity * unitCost')
}
}
Unfortunately, grails chokes up when I run the code above. Anyone have any idea how I could achieve my objective? Any help is highly appreciated.
Does it need to be a criteria query? HQL works great here:
def result = InvoiceLine.executeQuery(
"select itemName, sum(unitCost * quantity) " +
"from InvoiceLine " +
"group by itemName")
The results will be a List of Object[] where the 1st element is a String (the name) and the 2nd is a number (the sum), so for example you could iterate with something like
results.each { row ->
println "Total for ${row[0]} is ${row[1]}"
}

Groovy/Grails - How to examine relations in Domain class?

I'm writing a tag that essentially needs to dump an arbitrary domain class for the fields requested via parameters to the tag. This works fine if the field is a normal attribute. But, if it's a "hasMany" relationship, what are my options?
In other words, how do I check if a string passed as a parameter to the tag corresponds to a "hasMany" relationship, and get the corresponding domain name?
Note that I can instantiate the domain class and do a getClass on it - maybe it's in the properties? I'll check, but any input is much appreciated.
To be more specific, in the following code, I need to check in if any of the names is a "hasMany" relationship as opposed to an attribute, access that domain, and print all the instances of it.
Here's the code as it exists nos:
/*
* Tag to ouput domain level information
*
*/
def get_domain_info = { attrs, body ->
// get the domain name for lookup on the Misc Fields XML table
def id = attrs['id']
def domainName = attrs['domain_name']
// get the domainInstance
def domainInstance = grailsApplication.getArtefact("Domain",domainName)?.
getClazz()?.get(id)
def dataNames = attrs['data_names']
def dataNameArray = dataNames.split(",")
out << "<div class=\"dialog\">"
for(dataName in dataNameArray) {
out << "<tr class=\"prop\">"
out << "<td valign=\"top\" class=\"name\">" + dataName + "</td>"
def dataValue = domainInstance[dataName.trim()]
if (dataValue == null){
dataValue = ""
}
def valueLine
if ( dataValue.class == java.sql.Timestamp){
valueLine = "<td valign=\"top\" class=\"value\">" +
dataValue.format("d MMM yyyy") + "</td>"
}
else {
valueLine = "<td valign=\"top\" class=\"value\">" + dataValue + "</td>"
}
out << valueLine
out << "</tr>"
}
The domain class should always have a Set or List property defined for the hasMany, e.g.,:
class Author {
static hasMany = [books:Book]
List books
}
So in that case, domainInstance[dataName] will return a List of Books. All you really need to do is see if the property is a Collection:
if(dataValue instanceof Collection) {
// handle hasMany
}
Is some weird cases, a hasMany can also be a Map. See http://www.grails.org/GORM+-+Collection+Types

Resources