0

I want to find only the username field in my Registration collection

I am using the following query

db.Registration.find( {"username":"abcd"},  {username:1, _id:0} )

How will I write this query in hibernate?

paul po
  • 99
  • 1
  • 10

2 Answers2

0

If your entity looks like this:

@Entity
class Registration {
  @Id
  String id;

  String username:
}

This should work:

String query = "FROM Registration r WHERE r.username = :username ORDER by r.username ASC, r.id DESC"
List<Registration> results = entityManager.createQuery( query )
                               .setParameter("username", "abcd")
                               .getResultList()

or

Registration results = entityManager.createQuery( query )
                               .setParameter("username", "abcd")
                               .getSingleResult()

You can also use native queries but I will let you to the documentation: https://docs.jboss.org/hibernate/ogm/5.4/reference/en-US/html_single/#ogm-mongodb-queries-native

Davide D'Alto
  • 7,421
  • 2
  • 16
  • 30
-1

You'll need to annotate the (none PK) columns you want to retrieve in the Entity with:

@Column(name = "username")
NOTiFY
  • 1,255
  • 1
  • 20
  • 36
  • That's not true. You only need that if the name of the property is not "username". Properties are queryable fields by default (unless you make them transient). – Davide D'Alto Jul 10 '18 at 13:29