Querying objectify for a single entity by key or id - google-app-engine

Given a key or an id, I want to query objectify for a single entity. How might I do that? I am using the following method which I find cumbersome. Is there a one-liner alternative? Here is my method so far:
public static Dog getDog(String id) {

 log.info(TAG+": getDog");
Key<Dog> key = Key.create(Dog.class, id);

 Map<Key<Dog>, Dog> result = OfyService.ofy().load().keys(key);

 return (Dog) result.values().toArray()[0];

 }

Assuming your entity has no ancestor, you want:
ofy().load().type(Dog.class).id(dogId).now();
If you have an existing key:
ofy().load().key(dogKey).now();
Note also the static import of ofy
You can substitute now() for safe() if you'd rather catch an exception than check for a null return value.
The docs give a very good overview of Basic Operations.
edit
You say your entity does have an ancestor, so you need to specify the parent, like this:
Dog otherDog; // this is your ancestor
ofy().load().type(Dog.class).parent(otherDog).id(dogId).now();

Related

Objectify filter does not return the expected results

I have an existing datastore entity as below:
#Data
#Entity
public class Data
{
#Id #Index long id;
boolean expired;
}
I am in need to filter the data based on expired field, so I have to change the entity to have the filed expired now indexed. The modified entity is as below:
#Data
#Entity
public class Data
{
#Id #Index long id;
#Index boolean expired;
}
Below is the existing data in the datastore before the Index created:
Column : Data
id : 1
expired : true
id : 2
expired : false
id : 3
expired : false
My intention is to fetch the data using objectify with a filter on expired, so I have my code modified to use the below objectify quering:
return (List<Data>) ofy.load().type( Data.class ).filter( "expired = ", false ).list();
It is supposed to return two records, however it does return nothing.
BTW, after Index created, I added a new record into the entity as below
id : 4
expired : false
If I query back, I now see one result and that is with id = 4. Seems the filter works only on the newly added records and the index dint apply on all the old records? How to resolve this problem?
The reason the existing entities are not being returned is because they have not been indexed since you modified your entity class.The Objectify documentation states that:
Single property indexes are created/updated when you save an entity.
To get the existing existing entity instances to appear in your queries you will have to resave them, which will consequently force the Datastore to create their indexes.
You have to do the following for each existing entity:
Retrieve (load) the existing entity from the Datastore
Write (save) the existing entity back to the Datastore

Objectify query in transaction with Ancestor and a filter on Key at the same time returns 0 elements

Hi I am using Objectify and I have the following:
public static final Key<A> TopParent = new Key<A>(A.class,1)
class A {
}
class B {
#Parent
Key parent;
Key referenceKeyToC
}
class C {
#Parent
Key parent;
}
I am then trying to get ALL B-objects in an TRANSACTION with Ancestor(TopParent) and some Reference Key C - but it keep returning 0 elements.
This is my query:
List> bKeys = oft.query(B.class).ancestor(TopParent).filter("referenceKeyToC", new Key(C.class), b.referenceKeyToC).listKeys();
When I SAVE B it has BOTH parent and referenceKeyToC set correctly ..
IF I run the Query without the Key Filter like:
List> bKeys = oft.query(B.class).ancestor(TopParent).listKeys();
It returns all the B-objects - and those B-objects all Contains their referenceKeyToC
Any ideas??
Jesper
This is almost certainly an indexing issue. In order for that query to work, you must define two indexes:
A single-property index on referenceKeyToC
A multi-property index on {ancestor, referenceKeyToC}
In Objectify 3.x, properties have single-property indexes by default, but if you have added #Unindexed to the class B then you need to put #Indexed on referenceKeyToC.
The multi-property index is defined in datastore-indexes.xml. If you run this query in dev mode, the environment should provide you with the snippet of xml needed.

Importing SQL Server's CONTAINS() as a model defined function

I am trying to import SQL Server's CONTAINS() function in my Entity Framework model so that I can use it in my LINQ queries.
I have added this to my EDM:
<Function Name="FullTextSearch" ReturnType="Edm.Boolean">
<Parameter Name="Filter" Type="Edm.String" />
<DefiningExpression>
CONTAINS(*, Filter)
</DefiningExpression>
</Function>
Add created my method stub:
[EdmFunction("MyModelNamespace", "FullTextSearch")]
public static bool FullTextSearch(string filter)
{
throw new NotSupportedException("This function is only for L2E query.");
}
I try to call the function like this:
from product in Products
where MyModel.FullTextSearch("FORMSOF(INFLECTIONAL, robe)")
select product
The following exception is raised:
The query syntax is not valid. Near term '*'
I realize that the function I defined is not directly linked to the entity set being queried so that could also be a problem.
Is there any way to pull this off?
The function you have defined above uses Entity SQL, not Transact SQL, so I think the first step is to figure out whether CONTAINS(*,'text') can be expressed in Entity SQL.
Entity SQL doesn't support the * operator as described here: http://msdn.microsoft.com/en-us/library/bb738573.aspx and if I try
entities.CreateQuery<TABLE_NAME>("select value t from TABLE_NAME as t where CONTAINS(*, 'text')");
I get the same error you got above. If I try to explicitly pass the column it works:
entities.CreateQuery<TABLE_NAME>("select value t from TABLE_NAME as t where CONTAINS(t.COLUMN_NAME, 'text')");
But when I look at the SQL it translated it to a LIKE expression.
ADO.NET:Execute Reader "SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[TABLE_NAME] AS [Extent1]
WHERE (CASE WHEN ([Extent1].[COLUMN_NAME] LIKE '%text%') THEN cast(1 as bit) WHEN ( NOT ([Extent1].[COLUMN_NAME] LIKE '%text%')) THEN cast(0 as bit) END) = 1
) AS [GroupBy1]"
If you cannot express the query using Entity SQL you'll have to use a Stored Procedure or other mechanism to use Transact SQL directly.
This is way beyond me but could you try
from product in Products where MyModel.FullTextSearch(product, "FORMSOF(INFLECTIONAL, robe)") select product
My reasoning is that in SQL Server it is expecting two parameters.
I inserted a little function into my code, in a class which inherits from the Context class, which points to my SQL function supporting Full Text searching, my solution is a little more closed ended to yours (not allowing the specification of the type of text search), it returns an IEnumerable, essentially a list of primary keys matching the searching criteria, something like this;
public class myContext : DataContext
{
protected class series_identity
{
public int seriesID;
series_identity() { }
};
[Function(Name = "dbo.fnSeriesFreeTextSearchInflectional", IsComposable = true)]
protected IQueryable<series_identity> SynopsisSearch([Parameter(DbType = "NVarChar")] string value)
{
return this.CreateMethodCallQuery<series_identity>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), value);
}
public IEnumerable<int> Search(string value)
{
var a = from t1 in SynopsisSearch(value)
select t1.seriesID;
return a;
}
};
usage is something like;
myContext context = new myContext();
IEnumerable<int> series_identities = (from t1 in context.Search("some term")
select t1).Distinct();

What if you don't need a parameter when querying with Dapper?

I have one query that does a count/group by where I don't need a parameter (there is no where clause).
What is the syntax to run a parameterless query with dapper?
var _results = _conn.Query<strongType>("Select Count(columnA) as aCount, ColumnB, ColumnC from mytable group by ColumnB, ColumnC");
does not work.
I've tried it a few different ways but I still keep getting "ArgumentNullException was unhandled by user code".
Tried to figure it out myself, searched all over and I'm giving up. Thanks in advance.
Edit: Below is the line of code from SqlMapper.cs that throws the error. It's line 1334
il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
The error details: Value cannot be null. Parameter name: con
Mapping a single result back works just fine:
var a = cnn.Query<int>("select 1").Single()
// a is 1
You may face trouble if somehow your query returns no results, for example:
select count(Id) from
(
select top 0 1 as Id, 2 as Title
) as X
group by Title
return 0 results, so doing a Single on an empty result set is not going to work.
try
var _results = _conn.Query("Select columnB, Count(columnA) C from mytable group by columnB");
int ColumnB = ((int)_results[0].ColumnB);
int C = ((int)_results[0].C);
Value cannot be null. Parameter name: con
This is error is thrown by several dynamic ORMs including Dappper, PetaPoco and Massive but it's usually the same problem: Make sure you're using the [Ignore] attribute on the properties you don't want to include. This includes properties inherited from base classes. The error is useless but that's what it means.
This error can occur because a property you're trying to set in your return object is get-only. Dapper, of course, requires being able to set all properties. You might consider having a separate database DTO object that then gets converted to your properly immutable domain object after reading from the database.
Change this:
public string MyProperty { get; }
to this:
public string MyProperty { get; set; }

Hierarchical Hibernate, how many queries are executed?

So I've been dealing with a home brew DB framework that has some seriously flaws, the justification for use being that not using an ORM will save on the number of queries executed.
If I'm selecting all possibile records from the top level of a joinable object hierarchy, how many separate calls to the DB will be made when using an ORM (such as Hibernate)?
I feel like calling bullshit on this, as joinable entities should be brought down in one query , right? Am I missing something here?
note: lazy initialization doesn't matter in this scenario as all records will be used.
Hibernate will almost always retrieve object hierarchies using a single query; I don't recall seeing it do otherwise. It's easy to test, anyway. With this very simple mapping:
#Entity
public static class Person {
#Id
public String name;
}
#Entity
public static class Student extends Person {
public float averageGrade;
}
#Entity
public static class Teacher extends Person {
public float salary;
}
Then Hibernate gives me the following results for a very simple browse query (sessionFactory.openSession().createCriteria(Person.class).list();).
With #Inheritance(strategy = InheritanceType.SINGLE_TABLE) on the parent:
select this_.name as name0_0_, this_.averageGrade as averageG3_0_0_,
this_.salary as salary0_0_, this_.DTYPE as DTYPE0_0_ from HibernateTest$Person this_
With #Inheritance(strategy = InheritanceType.JOINED) on the parent:
select this_.name as name0_0_, this_1_.averageGrade as averageG1_1_0_,
this_2_.salary as salary2_0_, case when this_1_.name is not null then 1
when this_2_.name is not null then 2 when this_.name is not null then 0
end as clazz_0_ from HibernateTest$Person this_ left outer
join HibernateTest$Student this_1_ on this_.name=this_1_.name left outer join
HibernateTest$Teacher this_2_ on this_.name=this_2_.name
With #Inheritance(strategy = InheritanceType.JOINED) on the parent:
select this_.name as name0_0_, this_.averageGrade as averageG1_1_0_,
this_.salary as salary2_0_, this_.clazz_ as clazz_0_ from
( select null as averageGrade, name, null as salary, 0 as clazz_
from HibernateTest$Person union select averageGrade, name, null as salary,
1 as clazz_ from HibernateTest$Student union select null as averageGrade,
name, salary, 2 as clazz_ from HibernateTest$Teacher ) this_
As you can see, each is one query, with JOINs or UNIONs as appropriate depending on the mapping type.
Bobah is right,
You should give hibernate a try in order to see how many request will be sent to the database, however, in hibernate you can also specify and tune specific request by using HQL.
In addition with hibernate tools, you could also use P6spy driver, so you'll be able to see all the request that hibernate send to your database, with the value for each filter of the request.

Resources