I am not new to SQL, but I am completely new to Hibernate. I expected that selecting a lost of objects from a table, given a column value, would be a very simple task. But I can't get it done.
Both my mentor, and this question below suggested the same thing, which lead me to write the code below: JPA: How to get entity based on field value other than ID?
Criteria criteria = session.createCriteria(Competition.class);
List<Competition> list = (List<Competition>) criteria
.add(Restrictions.eq("Event_EventID", 1)).list();
This works, but the method Session.createCriteria()
is deprecated. Since I am new to hibernate, I might as well learn it the way it's intended to work, so I'd prefer not to use deprecated methods.
THe official Hibernate documentation simply says to use the JPA Criteria. I have found extremely verbose JPA variants, that I simply find unacceptable. This example is what you would need for ONLY getting a full list of objects from all the records, without any WHERE clause... (from https://www.tutorialspoint.com/jpa/jpa_criteria_api.htm)
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager( );
CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Employee> from = criteriaQuery.from(Employee.class);
//select all records
System.out.println(“Select all records”);
CriteriaQuery<Object> select = c riteriaQuery.select(from);
TypedQuery<Object> typedQuery = entitymanager.createQuery(select);
List<Object> resultlist = typedQuery.getResultList();
If this is the correct way to do it, I see no advantage from my standard Preparedstatement-approach. This is more verbose, and more complicated than anything I have seen.
Now, I've tried to look into specific questions about how to select lists of objects, not using deprecated methods in 5.2, and avoiding the JPA have-to-scroll-to-see-the-complete-code thing, but this is as close as I got: Hibernate 5.2 version -> A lot of Query methods deprecate?
This made me write the following code:
session.beginTransaction();
List<Competition> list = (List<Competition>) session.createQuery(
"FROM Competition WHERE Event_EventID = 1").getResultList();
While this works, and is simple, it opens up for SQL injections if i were to have something else than ints as variable values. I've also been told in code reviews that when using Hibernate, no SQL syntax should be necessary.
Needless to say, I am a bit frustrated that something that should be so simple, is in fact really hard to figure out. It is either deprecated, extremely verbose, or prone to SQL injections. Does anyone know if I have missed something obvious, or if Hibernate is simply poorly designed and/or documented in this case?