public static UserDetail UserDetail.findUserDetail(Long id) {
if (id == null) return null;
return entityManager().find(UserDetail.class, id);
}
We are using spring Roo. Above is Roo generated finder method. Partial stack trace is as follows:
Caused by: org.hibernate.WrongClassException: Object with id: 1501237 was not of the specified subclass: com.***.***.user.UserDetail (Discriminator: FacebookUserDetail)
Has anyone come across this exception?
EDIT
This question and following questions are related to same issue.
Java class file truncated
I have two projects. My one project (say project2) depends on another project(project2). Both projects are maven project and project1 is listed in dependancies of project2. When I compile project2, all the class files from project1 should be copied to project2 (I imagine). But, I see that the file size of one of the class files in project1 is different than file size of class file for the same class in project2. If I decompile the files I get following results.
Decompiled FacebookUserDetail.class from project1:
package com.***.domain.user.external;
import com.***.domain.user.UserDetailType;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.TypedQuery;
import org.aspectj.lang.JoinPoint;
import org.aspectj.runtime.internal.CFlowCounter;
import org.aspectj.runtime.reflect.Factory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.aspectj.AbstractDependencyInjectionAspect;
import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect;
import org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl;
#Configurable
#Entity
public class FacebookUserDetail extends ExternalUserDetail
{
public FacebookUserDetail()
{
JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this); if ((!AnnotationBeanConfigurerAspect.ajc$if$bb0((Configurable)getClass().getAnnotation(Configurable.class))) && (AbstractDependencyInjectionAspect.ajc$if$6f1(localJoinPoint))) AnnotationBeanConfigurerAspect.aspectOf().ajc$afterReturning$org_springframework_beans_factory_aspectj_AbstractDependencyInjectionAspect$2$1ea6722c(this);
}
public static FacebookUserDetail findFacebookUserDetailByFacebookId(String facebookId)
{
String str = facebookId; JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_0, null, null, str); if ((AnnotationDrivenStaticEntityMockingControl.ajc$cflowCounter$1.isValid()) && (AnnotationDrivenStaticEntityMockingControl.hasAspect())) return (FacebookUserDetail)findFacebookUserDetailByFacebookId_aroundBody1$advice(str, localJoinPoint, AnnotationDrivenStaticEntityMockingControl.aspectOf(), null, ajc$tjp_0, localJoinPoint); return findFacebookUserDetailByFacebookId_aroundBody0(str, localJoinPoint);
}
public UserDetailType getExternalUserDetailType()
{
return UserDetailType.FACEBOOK;
}
static
{
ajc$preClinit(); }
public static long countFacebookUserDetails() { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$countFacebookUserDetails(); }
public static List<FacebookUserDetail> findAllFacebookUserDetails() { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findAllFacebookUserDetails(); }
public static FacebookUserDetail findFacebookUserDetail(Long paramLong) { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetail(paramLong); }
public static List<FacebookUserDetail> findFacebookUserDetailEntries(int paramInt1, int paramInt2) { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetailEntries(paramInt1, paramInt2); }
public static TypedQuery<FacebookUserDetail> findFacebookUserDetailsByUserIdEquals(String paramString) { return FacebookUserDetail_Roo_Finder.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Finder$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetailsByUserIdEquals(paramString); }
public String toString() { return FacebookUserDetail_Roo_ToString.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_ToString$com_nim_domain_user_external_FacebookUserDetail$toString(this); }
}
Decompiled FacebookUserDetail.class from project2
package com.***.domain.user.external;
import com.***.domain.user.UserDetailType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.runtime.internal.CFlowCounter;
import org.aspectj.runtime.reflect.Factory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.aspectj.AbstractDependencyInjectionAspect;
import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect;
import org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl;
public class FacebookUserDetail extends ExternalUserDetail
{
public FacebookUserDetail()
{
JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this); if ((!AnnotationBeanConfigurerAspect.ajc$if$bb0((Configurable)getClass().getAnnotation(Configurable.class))) && (AbstractDependencyInjectionAspect.ajc$if$6f1(localJoinPoint))) AnnotationBeanConfigurerAspect.aspectOf().ajc$afterReturning$org_springframework_beans_factory_aspectj_AbstractDependencyInjectionAspect$2$1ea6722c(this);
}
public static FacebookUserDetail findFacebookUserDetailByFacebookId(String facebookId)
{
String str = facebookId; JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_0, null, null, str); if ((AnnotationDrivenStaticEntityMockingControl.ajc$cflowCounter$1.isValid()) && (AnnotationDrivenStaticEntityMockingControl.hasAspect())) return (FacebookUserDetail)findFacebookUserDetailByFacebookId_aroundBody1$advice(str, localJoinPoint, AnnotationDrivenStaticEntityMockingControl.aspectOf(), null, ajc$tjp_0, localJoinPoint); return findFacebookUserDetailByFacebookId_aroundBody0(str, localJoinPoint);
}
public UserDetailType getExternalUserDetailType()
{
return UserDetailType.FACEBOOK;
}
static
{
ajc$preClinit();
}
}
My question is: What are possible reasons for truncated class file in project2?
As far as I understand from the error you have the following scenario:
you request an entity of type UserDetail with that ID (which should have the DTYPE/discriminator column value equal to FacebookUserDetail or other that extend UserDetail), but in your DB the DTYPE is another. You have to correct your DB for that.
Or it could also be, that FacebookUserDetail is not recognized as being a DTYPE of the same hierarchy. Try debugging a bit, e.g testing what is returned if you search for a FacebookUserDetail instance of the same ID.
It looks like your super class and subclasse didn't share the same id in the database for the requested record 1501237
It is obvious you have an inheritance problem, take a look at http://en.wikibooks.org/wiki/Java_Persistence/Inheritance
Related
With the following Java code:
public class Bean{
private String value;
public Bean(#NonNull String value) {
//Usually fail-fast validation can be added here if it is needed
this.value = value;
}
public String getValue() {return this.value;}
}
Is it possible to check the constructor argument value by means of the annotation, #NonNull at run time other than compile time? Personally I still did not find any checker-framework, which can do validation checking at run time. However, is it possible to implement an Annotation processor to do run time checking?
You should take a look at #NotNull from javax.validation.constraints.
I use it in my models and it throw a Constraint exception when I try to save a model with a null #NotNull value.
The import is import javax.validation.constraints.NotNull;
If you are using Spring and mongodb, you'll have to configure it so it works, I have found a piece of code somewhere on the Internet (can't remember where), you may use it:
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
#Configuration
public class CustomRepositoryRestConfigurerAdapter {
#Bean
public LocalValidatorFactoryBean localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
#Bean
public ValidatingMongoEventListener validatingMongoEventListener(
#Qualifier("localValidatorFactoryBean") LocalValidatorFactoryBean lfb
) {
return new ValidatingMongoEventListener(lfb);
}
}
Yes. Lombok's #NonNull is a runtime check which just inserts an if-statement with a throw:
With Lombok
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(#NonNull Person person) {
super("Hello");
this.name = person.getName();
}
}
Vanilla Java
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(#NonNull Person person) {
super("Hello");
if (person == null) {
throw new NullPointerException("person is marked #NonNull but is null");
}
this.name = person.getName();
}
}
Misconception at your end: there is no single answer to your question.
Some annotations, when used on source code like this are mainly targeting compile time. Like some static analysis tool that analyses the data flow to tell you that you are violating "annotated" contracts here or there.
But some annotations are also "meant" to be used at runtime, for example to be used with "beans". Such objects might come in as parameter of a HTTP request, and then you have some framework checking if the content received as JSON for example is actually valid, according to the rules specified via annotations. See this tutorial for some examples.
I am new to Spring Jpa and Hibernate. I am trying to fetch data using a custom function from an Oracle db. I could define an entity along with its related service, implementation and repository. In addition, I created a new custom Oracle dialect by using registerFunction as you will see below.
So I have two questions:
1) In my Oracle db, the function sits under a different schema. Do I need to specify its schema? If so how? Or will hibernate find it automatically?
I will be asking my second question at the end of this post after providing my full stacktrace...
Here is my full stack trace:
MyOracle10gDialect
package blog;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.function.StandardSQLFunction;
public class MyOracle10gDialect extends Oracle10gDialect {
public MyOracle10gDialect() {
super();
registerFunction("my_function", new StandardSQLFunction("my_function"));
}
}
application.properties
...
spring.jpa.database-platform=blog.MyOracle10gDialect
...
Entity:
package blog.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "item", schema = "WOS_SOURCE")
public class WosItem {
#Id
#Column(nullable = false)
private String UT;
#Column(nullable = false)
private String TI;
public String getUT() {
return UT;
}
public void setUT(String UT) {
this.UT = UT;
}
public String getTI() {
return TI;
}
public void setTI(String TI) {
this.TI = TI;
}
public WosItem(String UT, String TI) {
this.UT = UT;
this.TI = TI;
}
public WosItem() { }
#Override
public String toString() {
return "WosItem{" +
"UT='" + UT + '\'' +
", TI='" + TI + '\'' +
'}';
}
}
Service:
package blog.services;
import blog.models.WosItem;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public interface WosItemService {
List<WosItem> findAll();
WosItem findById(String id);
String find_ut(Long ut_seq);
}
Implementation:
package blog.services;
import blog.models.WosItem;
import blog.repositories.WosItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class WosItemServiceJpaImpl implements WosItemService {
#Autowired
private WosItemRepository wosItemRepository;
#Override
public List<WosItem> findAll() {
return this.wosItemRepository.findAll();
}
#Override
public WosItem findById(String id) {
return this.wosItemRepository.findOne(id);
}
#Override
public String find_ut(Long ut_seq) {
return this.wosItemRepository.find_ut();
}
}
Repository:
package blog.repositories;
import blog.models.WosItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface WosItemRepository extends JpaRepository<WosItem, String> {
#Query("SELECT function('my_function', input) FROM WosItem wos");
String find_ut();
}
So in my Oracle db I can use this function as shown below:
select other_schema.my_function(aa.input) from my_schema.TABLE aa;
For ex. say aa.input is 332708100009 then it returns 000332708100009
As for my second question:
2) How can I carry out this process in jpa? I am aware that my repository is not correct at all. I get an error like "Annotations are not allowed here". I could not find a way to remedy this.
Thanks in advance.
EDIT ON THROWN EXCEPTION:
Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: 'function (my_function)'
+-[METHOD_NAME] IdentNode: 'my_function' {originalText=my_function}
\-[EXPR_LIST] SqlNode: 'exprList'
\-[NAMED_PARAM] ParameterNode: '?' {name=ut_seq, expectedType=null}
Unfortunately if you want to use the JPA 2.1 feature of the custom function call in your Select statement then you will need to perform some additional actions before you can use it.
When you use it in your where statement then it works without any additional actions, but as i wanted to use it for one of my projects inside the select just as you did then you would need to:
1) Extend the hibernate dialect and register your function(s):
package com.mypkg.dialect;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StringType;
public class CustomOracle10gDialect extends Oracle10gDialect {
public CustomOracle10gDialect() {
super();
registerFunction("my_function"
, new StandardSQLFunction("my_function", new StringType()));
}
}
2) Edit your hibernate.dialect property of your session factory to point to that custom implementation:
<property name="hibernate.dialect" value="com.mypkg.dialect.CustomOracle10gDialect"/>
Update
If the function needs to be called from a certain schema then this would be suggested:
registerFunction("my_function"
, new StandardSQLFunction("schema.my_function", new StringType()));
Further reading -> native function calls
I create custom Elasticsearch plugin. Now I want to write a test for this plugin.
My expectations were - that I could run embedded Elasticsearch instance, set up it properly and then do some testing (index some documents, then query for it)
Problem is that I couldn't set up my plugin properly
Custom plugin code is parsing JSON query and set up some objects for later usage:
public class CustomQueryParserPlugin extends AbstractPlugin {
public static final String PLUGIN_NAME = "custom_query";
private final Settings settings;
#Inject
public CustomQueryParserPlugin (Settings settings) {
this.settings = settings;
}
#Override
public String name() {
return PLUGIN_NAME;
}
#Override
public String description() {
return "custom plugin";
}
public void onModule(IndicesQueriesModule module) {
module.addQuery(new CustomQueryParser(settings));
}
}
Test code:
public class CustomParserPluginTest extends ElasticsearchSingleNodeTest {
private static Node newNode() {
final Settings settings = ImmutableSettings.builder()
.put(ClusterName.SETTING, nodeName())
.put("node.name", nodeName())
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
.put(EsExecutors.PROCESSORS, 1) // limit the number of threads created
.put("http.enabled", false)
.put("plugin.types", CustomParserPlugin.class.getName())
.put("path.plugins", pathToPlugin)
.put("index.store.type", "ram")
.put("config.ignore_system_properties", true) // make sure we get what we set :)
.put("gateway.type", "none").build();
Node build = NodeBuilder.nodeBuilder().local(true).data(true).settings(
settings).build();
build.start();
assertThat(DiscoveryNode.localNode(build.settings()), is(true));
return build;
}
#Test
public void jsonParsing() throws URISyntaxException {
final Client client = newNode().client();
final SearchResponse test = client.prepareSearch("test-index").setSource(addQuery()).execute().actionGet();
}
private String addQuery() {
return "{"match_all":{"boost":1.2}}"
}
I've try multiple values for pathToPlugin - but nothing seems to works well, because JSON query always give me an exception:
QueryParsingException[[test-index] No query registered for [custom_query]];
All documentation I could find was about installing plugins and testing them on some local Elasticsearch installation.
What I am doing wrong here? Is there any documentation or examples of tests like that?
UPD. Here is a repo with extracted code of CustomQueryParserPlugin - https://github.com/MysterionRise/es-custom-parser
May be in initialize section in test I need to create in memory index?
To write tests for you plugin you can use Elasticsearch Cluster Runner.
For reference check how MinHash Plugin wrote test.
UPDATE:
I've changed CustomParserPluginTest class to use Elasticsearch Cluster Runner:
import static org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner.newConfigs;
import java.util.Map;
import junit.framework.TestCase;
import org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.ImmutableSettings.Builder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.get.GetField;
import org.junit.Assert;
import org.elasticsearch.action.search.SearchResponse;
import static org.hamcrest.core.Is.is;
public class CustomParserPluginTest extends TestCase {
private ElasticsearchClusterRunner runner;
#Override
protected void setUp() throws Exception {
// create runner instance
runner = new ElasticsearchClusterRunner();
// create ES nodes
runner.onBuild(new ElasticsearchClusterRunner.Builder() {
#Override
public void build(final int number, final Builder settingsBuilder) {
}
}).build(newConfigs().ramIndexStore().numOfNode(1));
// wait for yellow status
runner.ensureYellow();
}
#Override
protected void tearDown() throws Exception {
// close runner
runner.close();
// delete all files
runner.clean();
}
public void test_jsonParsing() throws Exception {
final String index = "test_index";
runner.createIndex(index, ImmutableSettings.builder().build());
runner.ensureYellow(index);
final SearchResponse test = runner.client().prepareSearch(index).setSource(addQuery()).execute().actionGet();
}
private String addQuery() {
return "{\"match_all\":{\"boost\":1.2}}";
}
}
I've created es-plugin.properties(pluginrootdirectory\src\main\resources) file with following content which will force elasticsearch instance to load plugin:
plugin=CustomQueryParserPlugin
When you will run the this test you will see in the output that the newly created insance of elasticsearch loaded the plugin.
[2015-04-29 19:22:10,783][INFO ][org.elasticsearch.node ] [Node 1]
version[1.5 .0], pid[34360], build[5448160/2015-03-23T14:30:58Z]
[2015-04-29 19:22:10,784][INFO ][org.elasticsearch.node ] [Node 1]
initializin g ... [2015-04-29 19:22:10,795][INFO
][org.elasticsearch.plugins] [Node 1] loaded [custom_query], sites []
[2015-04-29 19:22:13,342][INFO ][org.elasticsearch.node ] [Node 1]
initialized
[2015-04-29 19:22:13,342][INFO ][org.elasticsearch.node ] [Node 1]
starting .. .
Hope this helps.
I'm trying to use the Play framework (Java) to simply read some data from a few Oracle tables, probably even use a few complex queries later on. I'm following a tutorial but I'm having some issues retrieving the data.
My Model class look like this:
package models;
import java.util.ArrayList;
import java.util.List;
import play.libs.F;
import javax.persistence.*;
import com.avaje.ebean.*;
import play.db.ebean.*;
#Entity
#Table(name="TABLESPACE.CAT_BONDS")
public class Cat_Bond extends Model {
#Id
public String symbol;
public String database;
public String tickType;
public String assetClass;
public String sourcePlatform;
public String sourceExchange;
public static Finder<String, Cat_Bond> find = new Finder<String, Cat_Bond>(String.class,Cat_Bond.class);
public Cat_Bond(){}
public Cat_Bond(String symbol, String database, String tickType, String assetClass,
String sourcePlatform, String sourceExchange) {
this.symbol = symbol;
this.database = database;
this.tickType = tickType;
this.assetClass = assetClass;
this.sourcePlatform = sourcePlatform;
this.sourceExchange = sourceExchange;
}
/*
* retrieve all rows from the 'cat_bonds' table
*/
public static List<Cat_Bond> findAll(){
//return new ArrayList<Cat_Bond>(cat_bond);
return find.all();
}
/*
* Find by EAN
*/
public static Cat_Bond findByEan(String symbol){
return find.where().eq("symbol", symbol).findUnique();
}
}
My controller class:
package controllers;
import java.util.List;
import views.html.*;
import models.Cat_Bond;
import play.data.Form;
import play.mvc.*;
public class Cat_Bonds extends Controller {
private static final Form<Cat_Bond> cat_bondForm = Form.form(Cat_Bond.class);
public static Result list(){
List<Cat_Bond> cat_bond = Cat_Bond.findAll();
return ok(list.render(cat_bond));
}
And the application.conf entry looks like:
#Oracle
db.default.driver=oracle.jdbc.OracleDriver
db.default.url="jdbc:oracle:thin:#server.uk.net.intra:port/ALIAS"
db.default.user=user
db.default.password=pass
# Evolutions
# ~~~~~
# You can disable evolutions if needed
evolutionplugin=disabled
Problem is when the call to list is made in the controller then to findAll() in the model I get the error:
**[PersistenceException: Query threw SQLException:ORA-00904: "T0"."SOURCE_EXCHANGE": invalid identifier Bind values:[] Query was: select t0.symbol c0, t0.database c1, t0.tick_type c2, t0.asset_class c3, t0.source_platform c4, t0.source_exchange c5 from TABLESPACE.CAT_BONDS t0 ]**
#Column(name="xx")
Was required above each variable defined in the model class that was to be mapped to the table column.
You can use
clean
compile
~run
If it doesn't work properly, you can use #EntityConcurrencyMode(ConcurrencyMode.NONE) within your model class.
I've hit a wall using Objectify for the google appengine datastore when filtering on boolean values. This is roughly what I've:
class Task implements Serializable {
...
boolean failed;
...
}
No matter what i do when i search, i always get an empty response although there are objects in the db that has failed = false
Examples:
ofy().query(Task.class).filter("failed",false).list()
ofy().query(Task.class).filter("failed",Boolean.FALSE).list()
ofy().query(Task.class).filter("failed",0).list()
ofy().query(Task.class).filter("failed","false").list()
ofy().query(Task.class).filter("failed","FALSE").list()
I found this old question while Googling and I wanted to clear it up.
You should be able to query by boolean fields as long as they are indexed at the time that they entered the datastore. Here's a complete unit test using Objectify and the App Engine unit test library (To run it, you have to link in the unit test jar described here). The following test passes. So the problem lies elsewhere, and I suggest that you use unit tests to discover it.
import static org.junit.Assert.*;
import javax.persistence.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
class FakeEntity {
#Id public Long id;
public boolean boolProp;
public boolean equals(Object other) {
return other != null &&
other instanceof FakeEntity &&
((FakeEntity)other).id == this.id &&
((FakeEntity)other).boolProp == this.boolProp;
}
}
public class FakeEntityTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void testBoolQuery() {
ObjectifyFactory objectifyFactory = ObjectifyService.factory();
objectifyFactory.register(FakeEntity.class);
Objectify objectify = objectifyFactory.begin();
FakeEntity entityFalse = new FakeEntity();
FakeEntity entityTrue = new FakeEntity();
entityTrue.boolProp = true;
objectifyFactory.begin().put(entityFalse);
objectifyFactory.begin().put(entityTrue);
assertArrayEquals(
new FakeEntity[] {entityFalse},
objectify.query(FakeEntity.class)
.filter("boolProp", false).list().toArray());
assertArrayEquals(
new FakeEntity[] {entityTrue},
objectify.query(FakeEntity.class)
.filter("boolProp", true).list().toArray());
assertArrayEquals(
new FakeEntity[] {entityTrue},
objectify.query(FakeEntity.class)
.filter("boolProp", true).list().toArray());
assertArrayEquals(
new FakeEntity[] {entityTrue},
objectify.query(FakeEntity.class)
.filter("boolProp", Boolean.TRUE).list().toArray());
// Filtering on integers and strings WON'T work:
assertArrayEquals(
new FakeEntity[] {},
objectify.query(FakeEntity.class)
.filter("boolProp", "true").list().toArray());
assertArrayEquals(
new FakeEntity[] {},
objectify.query(FakeEntity.class)
.filter("boolProp", 0).list().toArray());
}
}
You haven't Indexed boolean failed property.
If a field is not indexed, filter will not work in objectify datastore.
So to make it work, add
#Index boolean failed;
Now your filter will work.
Please note that though indexed, already saved values cannot be filtered. So either create new records and save or read all datastore entities and save it again.
Hope this helps.