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 956017
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T00:28:39+00:00 2026-05-16T00:28:39+00:00

EDIT: Rewrote the question. Added bounty as its important for me. The final hint

  • 0

EDIT: Rewrote the question. Added bounty as its important for me. The final hint with which i can get findByAttributes to work (without reimplementing it in subclasses) will get my points.

In my app i’m doing typesafe database queries with the new JPA2 Criteria Query. Therefore I have a trait DAO which should be (re)usable for ALL entities in my application.
So this is how the outline the current trait i’m using looks like (which works):

trait DAO[T, K](implicit m: Manifest[T]) {
  @PersistenceContext 
  var em:EntityManager = _

  lazy val cb:CriteriaBuilder = em.getCriteriaBuilder

  def persist(entity: T)
  def update(entity: T)
  def remove(entity: T)
  def findAll(): ArrayList[T]

  // Pair of SingularAttribute and corresponding value
  // (used for queries for multiple attributes)
  type AttributeValuePair[A] = Pair[SingularAttribute[T, A], A]

  // Query for entities where given attribute has given value
  def findByAttribute[A](attribute:AttributeValuePair[A]):ArrayList[T]

  // Query for entities with multiple attributes (like query by example)
  def findByAttributes[A](attributes:AttributeValuePair[_]*):ArrayList[T] 
}

In a concrete DAO, i’m extending this trait like this, setting the type and implementing the methods (removed all except the most important method):

class UserDAO extends DAO[User, Long] {
  override type AttributeValuePair[T] = Pair[SingularAttribute[User, T], T]

  override def findByAttributes[T](attributes:AttributeValuePair[_]*):ArrayList[User] = {
    val cq = cb.createQuery(classOf[User])
    val queryRoot = cq.from(classOf[User])
    var criteria = cb.conjunction
    for (pair <- attributes) 
      criteria = cb.and(cb.equal(queryRoot.get(pair._1), pair._2 ))
    cq.where(Seq(criteria):_*)
    val results = em.createQuery(cq).getResultList
    results.asInstanceOf[ArrayList[User]]
  }
}

BTW, findByAttributes is really nice to use. Example:

val userList = userEJB.findByAttributes(
  User_.title -> Title.MR, 
  User_.email -> "email@test.com"
)

I realized, that findByAttributes is so generic, that its the same in ALL classes of my app that implement the DAO. The only thing that changes is the Type used in the method. So in another class wich inherits DAO, its

def findByAttributes[T](attributes:AttributeValuePair[_]*):ArrayList[Message] = {
  val cq = cb.createQuery(classOf[Message])
  val queryRoot = cq.from(classOf[Message])
  var criteria = cb.conjunction
  for (pair <- attributes) 
    criteria = cb.and(cb.equal(queryRoot.get(pair._1), pair._2 ))
  cq.where(Seq(criteria):_*)
  val results = em.createQuery(cq).getResultList
  results.asInstanceOf[ArrayList[User]]
}

So i created a new abstract class named SuperDAO that should contain the implemented generic methods, so that i don’t have to re-implement them in every subclass.
After some help from Landei (thanks), the (most important part of my) current implementation of my SuperDAO looks like this

abstract class SuperDAO[T, K](implicit m: Manifest[T]) {
  @PersistenceContext
  var em:EntityManager = _

  lazy val cb:CriteriaBuilder = em.getCriteriaBuilder

  type AttributeValuePair[A] = Pair[SingularAttribute[T, A], A]

  def findByAttributes(attributes:AttributeValuePair[_]*):ArrayList[T] = {
    val cq = cb.createQuery(m.erasure)
    val queryRoot = cq.from(m.erasure)
    var criteria = cb.conjunction
      for (pair <- attributes) { 
        criteria = cb.and(
          cb.equal(
            // gives compiler error
            queryRoot.get[SingularAttribute[T,_]](pair._1)
          )
          ,pair._2
        )
      }
    cq.where(Seq(criteria):_*)
    val results = em.createQuery(cq).getResultList
    results.asInstanceOf[ArrayList[T]]
  }

So the current problem is that the line with queryRoot.get produces the following error:

overloaded method value get with alternatives:   
(java.lang.String)javax.persistence.criteria.Path
[javax.persistence.metamodel.SingularAttribute[T, _]] <and>
(javax.persistence.metamodel.SingularAttribute[_ >: Any, 
javax.persistence.metamodel.SingularAttribute[T,_]])
javax.persistence.criteria.Path
[javax.persistence.metamodel.SingularAttribute[T, _]]  
cannot be applied to 
(javax.persistence.metamodel.SingularAttribute[T,_$1])

Whats meant with $1???

If needed: SingularAttribute Javadoc

EDIT @Landei:

Changing the method signature to

def findByAttributesOld[A](attributes:AttributeValuePair[A]*):ArrayList[T] = {

And the queryRoot.get to

queryRoot.get[A](pair._1.asInstanceOf[SingularAttribute[T,A]])

Results in the (much shorter!) error:

overloaded method value get with alternatives:  
(java.lang.String)javax.persistence.criteria.Path[A] <and>   
(javax.persistence.metamodel.SingularAttribute[_ >: Any,     A])
javax.persistence.criteria.Path[A]  cannot be applied to 
(javax.persistence.metamodel.SingularAttribute[T,A])

The solution of @Sandor Murakozi seems to work. Have to test it a bit. But i would also appreciate a shorter solution, if its possible at all!

  • 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-05-16T00:28:40+00:00Added an answer on May 16, 2026 at 12:28 am

    EDIT: Added comments as requested by @ifischer

    I think your main problem is that you lose valuable type information by just passing m.erasure as this returns Class[_] instead of Class[T] what you actually want here. Doing a cast before the rest will save you some nasty stuff.

    Also the unbound wildcards used in JPA 2.0 are a bit annoying as you need to jump some hoops to get around them.

    As it does not make much sense to query for no attributes I pulled the first attribute out of the *-parameter. This also means that you do not need to start with conjunction.

    I shortened some names so that the code fits in the box without line breaks:

    // import java.util.list as JList, so it does not shadow scala.List
    import java.util.{List => JList}
    
    abstract class SuperDAO[T <: AnyRef, K](implicit m: Manifest[T]) {
    
      @PersistenceContext
      var em: EntityManager = _
    
      // pretend that we have more type info than we have in the Class object.
      // it is (almost) safe to cast the erasure to Class[T] here
      def entityClass = m.erasure.asInstanceOf[Class[T]]
    
      lazy val cb: CriteriaBuilder = em.getCriteriaBuilder
    
      // Type alias for SingularAttributes accepted for this DAOs entity classes
      // the metamodel will only ever provide you with Attributes of the form
      // SingularAttribute<? super X,E>, where X is the entity type (as your
      // entity class may extend from another) and E is the element type.
      // We would actually like to use a contravariant definition of the first
      // type parameter here, but as Java has no notion of that in the definition
      // side, we have to use an existential type to express the contravariance
      // similar to the way it would be done in Java.
      type Field[A] = (SingularAttribute[_ >: T,A],A)
    
      // As we need at least one attribute to query for, pull the first argument out
      // of the varargs.
      def findByAttributes(attribute: Field[_], attributes: Field[_]*): JList[T] = {
        val cq = cb.createQuery(entityClass)
        val root = cq.from(entityClass)
    
        // shorthand for creating an equal predicate as we need
        // that multiple times below
        def equal(a: Field[_]) = cb.equal(root.get(a._1), a._2)
    
        // the Seq of Predicates to query for:
        def checks = Seq(
          // if there is only one argument we just query for one equal Predicate
          if (attributes.isEmpty) equal(attribute)
    
          // if there are more, map the varargs to equal-Predicates and prepend
          // the first Predicate to them. then wrap all of them in an and-Predicate
          else cb.and(equal(attribute) +: attributes.map(equal) : _*)
        )
    
        // as we already casted the entityClass we do not need to cast here
        em.createQuery(cq.where(checks : _*)).getResultList
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to solve the following question which i can't get to work by
Edit: This question was written in 2008, which was like 3 internet ages ago.
Edit: From another question I provided an answer that has links to a lot
EDIT: This question is more about language engineering than C++ itself. I used C++
EDIT What small things which are too easy to overlook do I need to
edit #2: Question solved halfways. Look below As a follow-up question, does anyone know
I wanna rewrite links like index.php?page=entry&id=15&action=edit to entry/15/edit . This is how my .htaccess
EDIT: This was formerly more explicitly titled: - Best solution to stop Kontiki's KHOST.EXE
EDIT: Learned that Webmethods actually uses NLST, not LIST, if that matters Our business
Edit : Solved, there was a trigger with a loop on the table (read

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.