/** * Create a new Query-by-example query * * @param session * @param entity */ @SuppressWarnings("unchecked") public ExampleQuery(Configuration configuration, Session session, T entity) { this.session = Assert.notNull(session, "session"); this.entityPath = (PathBuilder) pathBuilderFactory.create(entity.getClass()); this.conditions = new BooleanBuilder(); BeanMap beanMap = new BeanMap(entity); MappedClass mappedClass = configuration.getMappedClass(entity.getClass()); for (MappedPath mappedPath : mappedClass.getProperties()) { MappedProperty<?> property = mappedPath.getMappedProperty(); Object value = property.getValue(beanMap); if (value != null // date/time values are skipped && !DATE_TIME_TYPES.contains(value.getClass()) // collection values are skipped && !property.isCollection() // map values are skipped && !property.isMap() // blank nodes are skipped && !(value instanceof BID)) { Expression<Object> propertyPath = (Expression) entityPath.get(property.getName(), property.getType()); conditions.and(ExpressionUtils.eqConst(propertyPath, value)); } } }
@Test public void Query() throws IOException { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addClass(TEST.NS, Person.class).addId("id").addProperties(); builder.addClass(new UID(TEST.NS, "Dept"), Department.class).addId("id").addProperties(); builder.addClass(TEST.NS, Company.class).addId("id").addProperties(); Configuration configuration = builder.build(); Session session = SessionUtil.openSession(new MiniRepository(), Collections.<Locale> emptySet(), configuration); Person person = new Person(); person.firstName = "Bob"; person.lastName = "Smith"; session.save(person); session.clear(); // getById Person other = session.getById(person.id, Person.class); assertNotNull(other.id); assertEquals(person.firstName, other.firstName); assertEquals(person.lastName, other.lastName); // query PathBuilder<Person> personPath = new PathBuilderFactory().create(Person.class); assertEquals(other, session.from(personPath).where(personPath.getString("firstName").eq("Bob")).uniqueResult(personPath)); assertEquals(other, session.from(personPath).where(personPath.getString("lastName").eq("Smith")).uniqueResult(personPath)); // list assertEquals(1, session.from(personPath).list(personPath).size()); // findInstances assertEquals(1, session.findInstances(Person.class).size()); session.close(); }