db4o querying subobject - db4o

I've just started with db4o and I stumbled on to a problem.
I have an object with a subobject (it is probably not the correct word but I hope you get what I mean).
The subobject contains two dates, one start date and one end date.
I would like to show the main object if it has at least one sub object where DateTime.Now is inbetween the start and end date.
I have to use native query or SODA (linq isn't working in the project).
Thanks in advance!
/Fredrik

I would try something like this:
IQuery query = db.Query();
query.Constrain(typeof(YourObjectType));
IConstraint constr1 = query.Descend("enddate")
.Constrain(DateTime.Now).Greater();
IConstraint constr2 = query.Descend("startdate")
.Constrain(DateTime.Now).Smaller();
query.Constrain(constr1).And(constr2);
IObjectSet result = query.Execute();

Related

ABAP: how to compare three internal tables

I've recently started an apprenticeship and I've received a small project to help checking tables.
The request is that I am supposed to write a report that compares a table to our profit center's standard hierarchy and tells you which entries are the same and which ones are not.
Now, I've only started getting into ABAP and while I've had SQL prior, i'm not exactly good in it. My colleagues are nice but I fear that I'd look like an idiot if I kept asking them how to do this.
What i've done so far is giving the table some records to check in our development system, selecting all records in it and also selecting everything I need from SETLEAF and SETNODE.
SELECT * FROM Y_TABLE
INTO TABLE #DATA(lt_compare).
SELECTION-SCREEN BEGIN OF BLOCK set_leaf.
CONSTANTS:
SET_CLASS TYPE SETLEAF-SETCLASS VALUE '0102',
SUB_CLASS TYPE SETLEAF-SUBCLASS VALUE 'D100'.
PARAMETERS:
lv_pcnr TYPE SETLEAF-VALFROM,
setname TYPE SETLEAF-SETNAME.
SELECTION-SCREEN END OF BLOCK set_leaf.
TYPES:
BEGIN OF lt_ausgabe,
SETCLASS TYPE SETLEAF-SETCLASS,
SUBCLASS TYPE SETLEAF-SUBCLASS,
VALFROM TYPE SETLEAF-VALFROM,
SETNAME TYPE SETLEAF-SETNAME,
END OF lt_ausgabe.
DATA:
gt_setleaf TYPE STANDARD TABLE OF lt_ausgabe,
gt_setnode TYPE STANDARD TABLE OF lt_ausgabe.
SETNODE-SUBSETNAME = SETLEAF-SETNAME.
SETNODE-SETNAME = SETNODE-SUBSETNAME.
FORM build_table_setleaf.
SELECT *
FROM SETLEAF
INTO CORRESPONDING FIELDS OF TABLE #gt_setleaf
WHERE SETCLASS = #set_class AND SUBCLASS = #sub_class AND VALFROM = #lv_pcnr AND SETNAME = #setname.
ENDFORM.
FORM build_table_setnode.
SELECT *
FROM SETNODE
INTO CORRESPONDING FIELDS OF TABLE #gt_setnode
WHERE SETCLASS = #set_class AND SUBCLASS = #sub_class AND SUBSETNAME = #setname.
ENDFORM.
I've changed the table name and the constant values because I don't know how much of them I can share.
Now I want to compare these tables and well, do what the request asked for. But I don't really understand how to do this. The code above may not be the way to solve this at all..
I'm sorry in advance if any of this sounds off, I would ask in my own language if.. my people weren't known for being unhelpful and rude when asking code-related stuff.
Thank you in advance.

Avoiding subqueries in HQL using Grails

I have two object, a room type and a reservation. Simplified they are:
class Room {
String description
int quantity
}
class Reservation {
String who
Room room
}
I want to query for all rooms along with the number of rooms available for each type. In SQL this does what I want:
select id, quantity, occupied, quantity-coalesce(occupied, 0) as available
from room left join(select room_id, count(room_id) as occupied from reservation)
on id = room_id;
I'm not getting anywhere trying to work out how to do this with HQL.
I'd appreciate any pointers since it seems like I'm missing something fairly fundamental in either HQL or GORM.
The problem here is your trying to represent fields that are not your domain classes like available and occupied. Trying to get HQL\GORM to do this can be a bit a little frustrating, but not impossible. I think you have a couple options here...
1.) Build your domain classes so that there easier to use. Maybe your Room needs to know about it's Reservations via a mapping table or, perhaps write what you want the code to look like and then adjust the design.
For example. Maybe you want your code to look like this...
RoomReservation.queryAllByRoomAndDateBetween(room, arrivalDate, departureDate);
Then you would implement it like this...
class RoomReservation{
...
def queryAllByRoomAndDateBetween(def room, Date arrivalDate, Date departureDate){
return RoomReservation.withCriteria {
eq('room', room)
and {
between('departureDate', arrivalDate, departureDate)
}
}
}
2.) My second thought is... It's okay to use the database for what it's good for. Sometimes using sql in you code is simply the most effective way to do something. Just do it in moderation and keep it centralized and unit tested. I don't suggest you use this approach because you query isn't that complex, but it is an option. I use stored procedures for things like 'dashboard view's' that query millions of objects for summary data.
class Room{
...
def queryReservations(){
def sql = new Sql(dataSoruce);
return sql.call("{call GetReservations(?)}", [this.id]) //<-- stored procedure.
}
}
I'm not sure how you can describe a left join with a subquery in HQL. INn any case you can easily execute raw SQL in grails too, if HQL is not expressive enough:
in your service, inject the dataSource and create a groovy.sql.Sql instance
def dataSource
[...]
def sql= new Sql(dataSource)
sql.eachRow("...."){row->
[...]
}
I know it's very annoying when people try to patronize you into their way of thinking when you ask a question, instead of answering your question or just shut up, but in my opinion, this query is sufficiently complex that I would create a concept for this number in my data structure, perhaps an Availability table associated to the Room, which would keep count not only of the quantity but also of the occupied value.
This is instead of computing it every time you need it.
Just my $.02 just ignore it if it annoys you.

using WHERE clause in Rails 3 active record query

I'm new to rails and I'm trying to use the where method to retrieve a record from my data table. However, using it doesn't seem to return any results.
employee = Employee.where("first_name = ?", "bill") #doesn't work
employee = Employee.where(:first_name => "bill") #doesn't work
employee = Employee.find_by_first_name("bill") #works
I'm testing the results by printing employee.first_name and like I said the first two don't return anything whereas the third one returns "bill". What's going on here?
The first two will return an array (all employees with that name). Employee.find_by_first_name will only return the first result -- Employee.find_all_by_first_name should return an array like the first two queries.
See if this does what you expect:
Employee.where("first_name = ?", "bill").first
(for completeness, what Employee.where actually returns is a chainable scope object that acts like an array)
what happens for the first two when you run employee.first_name? It looks to me like you should be getting an no method exception since Array does not have a method first_name.
Using the where clause will not automatically return the first employee model object found, it will return an ActiveRecord::Relation which will then be automatically evaluated into an array by rails when you try to access it. The where clause will give you back all employees with a first_name == "bill"
The find_by_first_name will only return a single instance of the Employee class, even if there are multiple employees with the name "bill".
If you were to try employee.first.fist_name after running the first two, I believe you would find that you get "bill" if everything in the database is correct and there is an employee with the first name of "bill".

grails find first

I know this is simple question but taking more time
How to find first record from table in grails .
I need to get only the first record with out knowing the id number .
Is there any method like find :first in grails ?
thanks in advance .
Updating to Grails 2.1.1 or later adds two new methods (first and last) for GORM to address this needed feature.
From the docs:
class Person {
String firstName
String lastName
Integer age
}
// retrieve the first person ordered by the identifier
def p = Person.first()
// retrieve the first person ordered by the lastName property
p = Person.first(sort: 'lastName')
// retrieve the first person ordered by the lastName property
p = Person.first('lastName')
Well, you have to define by what measure this record is supposed to be the "first".
Assuming that you mean the record with the earliest creation timestamp, the easiest and most robust approach would be to add a dateCreated property to your domain class and then querying for the entity with the lowest such date. In fact you don't even have to set the creation date manually, because Grails does this for you (as long as you name the property dateCreated) - see Automatic timestamping in the Grails Documentation.
The HQL query would be something like:
def firstObject = YourClass.find("FROM YourClass ORDER BY dateCreated")
Check out hibernate criteria and projections, e.g:
def location = Location.createCriteria()
def firstRecord = location.list{
maxResults(1)
order("id","asc")//assuming auto increment just to make sure
}[0]
http://grails.org/doc/1.0.3/ref/Domain%20Classes/createCriteria.html
If timestamp doesn't matter, you could try if Daniel's answer without ORDER BY works, i.e.
def firstObject = YourClass.find("FROM YourClass")
You can use the grails findBy methods to return the first result of a query.
-> From the 1.3.7 docs
findBy*
Purpose
Dynamic method that uses the properties of the domain class to allow
the creation of Grails query method expressions that return the first
result of the query
-> from the latest docs
findBy* Purpose
Dynamic method that uses the properties of the domain class to execute
a query returning the first matching result.

How to order by more than one field in Grails?

Is there a way to get a list ordered by two fields, say last and first names?
I know .listOrderByLastAndFirst and .list(sort:'last, first') won't work.
Hates_ criteria answer didn't seem to work for me; putting "last,first" in order will only cause exceptions saying, "Property 'last,first' not found". To order on two fields, you can do the following:
def c = MyDomain.createCriteria()
def results = c.list {
and{
order('last','desc')
order('first','desc')
}
}
This is quite old but helped me in finding a suitable solution. A "cleaner" code example by using withCriteria shortcut:
def c = MyDomain.withCriteria {
and {
order('last', 'desc')
order('first', 'desc')
}
}
This old solution no longer works. Please see mattlary's answer below
You may have to write a custom finder in HQL or use the Criteria Builder.
MyDomain.find("from Domain as d order by last,first desc")
Or
def c = MyDomain.createCriteria()
def results = c.list {
order("last,first", "desc")
}
More complicated ordering criteria, (tested in Grails 2.1.0)
def c = MyDomain.withCriteria {
property {
order('last', 'desc')
}
order('first', 'desc')
}
sorts first by MyDomain.property.last then by MyDomain.first
MyDomain.findAll(sort: ['first': 'desc','last':'desc'])
works with grails-datastore-gorm:6.0.3
I think a criteria is the best bet, but you did the right thing by attempting a finder first. When retrieving domain objects from GORM, the right order to make the attempt is: dynamic finder, criteria, HQL.
This query is working on the basis of first field. When the first field is blank then it is shorted by the second field.
order('last','desc')
order('first','desc')
you can do this
def results=MyDomain.findAll([sort:"last",order:'desc'],[sort:"first",order:'desc']);
this line of code will first sort results from domain class "MyDomain" first by last name and then by first name of the person .
If you were sorting lists on the contents of their items, you would need to implement a comparator which would have some smarts to enable to you decide the sort order based on multiple properties.
Some examples of Groovy-style comparators are shown here
However if the list you are sorting is being returned from a database query, you would be better off sorting it using a CrteriaQuery and sorts on that
I has the same problem.
Since my list is not so big, I use groovy sort, as I want to sort on fields of linked domain:
CalendarData -> Attraction
def listCalendar (Calendar calendar) {
respond CalendarData.where {
calendar == calendar
}.list().sort{ "$it.attraction.type?:' '$it.attraction.name" }
}

Resources