Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8417701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:07:48+00:00 2026-06-10T02:07:48+00:00

I am trying to perform a DB access through a DAO object, and I

  • 0

I am trying to perform a DB access through a DAO object, and I have bumped into the case where I need to query a field in another Entity.

Considering two entities (EntityA and EntityB) that are connected in entity A through the foreign key EntityA.idEntityB.

I have GenericDao<EntityA> daoA and I am trying to get all the results that match a determined field of EntityB: idEntityB.fieldOfB all in the same find method of the dao.

Is it possible? And if so some directions would be nice. Thanks

edit

An example of my code:

Entities

public class EntityA {
    @JoinColumn(name = "id_entity_b", referencedColumnName = "id")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private EntityB idEntityB;
    // getter+setter...
}

public class EntityB {
    // ...
    private String fieldOfB;
    // getter+setter...
}

DAO Access

GenericDao<EntityA> daoA = // ...

Set<Criterion> filter = new HashSet<Criterion>();
filter.add(Restrictions.eq("idEntityB.fieldOfB"));

List<EntityA> list = dao.findByFilter(filter);

The error message is something like “Could not resolve property idEntityB.fieldOfB“

edit 2

I was able to find something like what I want to do. Although my API is slightly different I believe this is helful for anyone who gets across this problem at an early stage of their own project.

http://code.google.com/p/hibernate-generic-dao/

The framework features a powerful and flexible search functionality.
This is used by passing a search object to search methods on general
and generic DAOs.

Searches with nested properties are fully supported in this project.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T02:07:49+00:00Added an answer on June 10, 2026 at 2:07 am

    Here is my generic Criteria filtering method.

    Properties according to bean conventions have following form foo.bar.name.
    With Criteria API a tree can be build from a given filtering map and Restrictions can be added. One special case I observed during testing is that filtering on the identifier property does not needs a new subcriteria since this property is already fetched.

    /**
     * Creates a detached criteria from the given Type and given map of filters.
     * 
     * @param type Target type the Criteria is build for.
     * @param identifierPropertyName If provided (not null) the identifier
     *            property name can be identified for the given type to simplify
     *            the queries if the identifier property is the only property
     *            used on the parent no subqueries are needed.
     * @param filters
     * 
     * @see #createTree(Set, String)
     * @see #addRestrictions(DetachedCriteria, TreeNode)
     * 
     * @return
     */
    public static DetachedCriteria createDetachedCriteria(final Class<?> type, final String identifierPropertyName,
        final Map<String, Criterion> filters)
    {
        final DetachedCriteria criteria = DetachedCriteria.forClass(type);
    
        // add restrictions using tree
        final TreeNode<Entry<String, Criterion>> rootNode = HibernateUtils2.createTree(filters.entrySet(),
            identifierPropertyName);
    
        final Iterator<TreeNode<Entry<String, Criterion>>> it = rootNode.getChildren().iterator();
    
        while (it.hasNext())
            HibernateUtils.addRestrictions(criteria, it.next());
    
        return criteria;
    }
    
    /**
     * Creates a Tree from the given Set using a fictional root TreeNode.
     * 
     * @param <T>
     * 
     * @param filters
     * @param identifierPropertyName Property name which is merged with its
     *            parent property. Example: <b>user.id</b> is treated as single
     *            property.
     * @return
     */
    public static <T extends Object> TreeNode<Entry<String, T>> createTree(final Set<Entry<String, T>> filters,
        final String identifierPropertyName)
    {
    
        final Iterator<Entry<String, Object>> it = filters.iterator();
    
        /*
         * create key property tree for Entity properties
         */
        final TreeNode<Entry<String, Object>> rootNode = new TreeNode<Entry<String, Object>>(
            new SimpleEntry<String, Object>("root", null));
    
        while (it.hasNext())
        {
            final Entry<String, Object> entry = it.next();
            // foo.bar.name
            final String key = entry.getKey();
    
            String[] props;
    
            /*
             * check if we have a nested hierarchy
             */
            if (key.contains("."))
            {
                props = key.split("\\.");
                // check for identifier since identifier property name does not
                // need new subcriteria
                if (!StringUtils.isBlank(identifierPropertyName))
                {
                    int propsTempLength = props.length - 1;
                    if (props[propsTempLength].equals(identifierPropertyName))
                    {
                        props = Arrays.copyOf(props, propsTempLength);
                        propsTempLength--;
                        props[propsTempLength] = props[propsTempLength] + "." + identifierPropertyName;
                    }
                }
    
                // check for "this" identifier of beginning, which needs to be
                // added for projections because of hibernate not recognizing it
                if (props.length > 1 && props[0].equals("this"))
                {
                    props[0] = "this." + props[1];
    
                    props = ArrayUtils.remove(props, 1);
                }
            }
            else
                props = new String[]
                {
                    key
                };
    
            TreeNode<Entry<String, Object>> currNode = rootNode;
    
            // create nested criteria
            for (int i = 0; i < props.length; i++)
            {
                Object valueAdd;
    
                // only leaf needs value
                if (i != props.length - 1)
                    valueAdd = null;
                else
                    valueAdd = entry.getValue();
    
                final TreeNode<Entry<String, Object>> childTempNode = new TreeNode<Entry<String, Object>>(
                    new SimpleEntry<String, Object>(props[i], valueAdd));
    
                // try to get the real node
                TreeNode<Entry<String, Object>> childNode = currNode.getChild(childTempNode.getElement());
                // check if we already have a unique node
                if (childNode == null)
                {
                    childNode = childTempNode;
                    // add new child to set if its a new node
                    currNode.addChild(childNode);
                }
    
                currNode = childNode;
            }
        }
    
        return rootNode;
    }
    
    /**
     * Recursively adds the given Restriction's wrapped in the given TreeNode to
     * the Criteria.
     * 
     * @param criteria
     * @param treeNode
     */
    public static void addRestrictions(final DetachedCriteria criteria,
        final TreeNode<Entry<String, Criterion>> treeNode)
    {
        // if we have a leaf simply add restriction
        if (treeNode.getChildren().size() == 0)
            criteria.add(treeNode.getElement().getValue());
        else
        {
            // create new sub Criteria and iterate children's
            final DetachedCriteria subCriteria = criteria.createCriteria(treeNode.getElement().getKey());
    
            final Iterator<TreeNode<Entry<String, Criterion>>> it = treeNode.getChildren().iterator();
    
            while (it.hasNext())
                HibernateUtils.addRestrictions(subCriteria, it.next());
        }
    }
    
    /*
     * Utility classes
     */
    
    /**
     * Generic TreeNode implementation with a Set to hold its children to only allow
     * unique children's.
     */
    public class TreeNode<T>
    {
        private final T element;
    
        private final Set<TreeNode<T>> childrens;
    
        public TreeNode(final T element)
        {
            if (element == null)
                throw new IllegalArgumentException("Element cannot be null");
    
            this.element = element;
    
            this.childrens = new HashSet<TreeNode<T>>();
        }
    
        public void addChildren(final TreeNode<T> children)
        {
            this.childrens.add(children);
        }
    
        /**
         * Retrieves the children which equals the given one.
         * 
         * @param children
         * @return If no children equals the given one returns null.
         */
        public TreeNode<T> getChildren(final TreeNode<T> children)
        {
            final Iterator<TreeNode<T>> it = this.childrens.iterator();
    
            TreeNode<T> next = null;
    
            while (it.hasNext())
            {
                next = it.next();
                if (next.equals(children))
                    return next;
            }
    
            return null;
        }
    
        public T getElement()
        {
            return this.element;
        }
    
        public Set<TreeNode<T>> getChildrens()
        {
            return this.childrens;
        }
    
        /**
         * Checks if the element of this instance equals the one of the given
         * Object.
         */
        @Override
        public boolean equals(final Object obj)
        {
            if (this == obj)
                return true;
    
            if (obj != null && obj instanceof TreeNode)
            {
                final TreeNode<?> treeNode = (TreeNode<?>) obj;
    
                return this.element.equals(treeNode.element);
            }
            else
                return false;
        }
    
        @Override
        public int hashCode()
        {
            int hash = 1;
            hash = hash * 17 + this.element.hashCode();
            return hash;
        }
    }
    

    Hope this helps you. Or have a look at the generic dao project you mentioned. I knew about this project and checked it out but never downloaded it.

    Using this approach a query can be created very simple like following:

    Map<String, Object> filters = new HashMap<String, Object>();
    filters.put("foo.bar.name", Restrictions.like("name", "peter"));
    filters.put("foo.test.id", Restrictions.eq("id", 2));
    
    List<Class> data = HibernateUtils.createDetachedCriteria(Class, "get identifier from sessionFactory", filters).getExecutableCriteria(session).list();
    

    This odd approach to add the property name as the key and into the Restrictions is related to the fact that Restrictions have no getter and setter for property names.

    Custom filtering

    My real application uses similar code which is not restricted to Criterion class only.
    For my web tier I created custom filters which are equivalent to Restrictions api but the client does not needs hibernate jar’s anymore.

    Edit

    Generic filtering across non-entities such as component’s and composite-id’s is not supported. It can easily be extended with help of ClassMetadata to support them without need for reflection. If code is needed i can provide it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have Chrome 7.0 and am trying to access fields of a global object.
I have an NSDictionary object called myData, and I'm trying to access it from
I am trying to perform a JNDI-lookup from within the GWT devmode. I have
I'm trying to perform a DISTINCT clause on a query like this SELECT DISTINCT
I'm trying to debug a remote server. How would I perform ruby-debug and access
i am trying to perform an action where i can access and tag images
I'm trying to perform a linq to entities query on a table that's inherited
Am trying to perform some specific actions, before closing the access database (whenever the
I am trying to get access to SocialCast's API from PHP. They have just
I am trying to perform the following linq to entities query- var data =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.