Reputation: 2029
i am trying to do my first steps in Java, and i am blocked with the next problem: i have this hieararchy class "User -> Traveller".
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class User {
// Some properties and accessors.
}
@Entity
@PrimaryKeyJoinColumn(name="user_id")
public class Traveller extends User{
// Some properties and accessors.
}
So, i need search a traveller by your username which is a User class property. I try this in my TravellerDao:
public Traveller findByUsername(String username){
EntityManager em = PersistenceHelper.getEm();
TypedQuery<Traveller> query = em.createQuery("FROM Traveller WHERE username = ?1", Traveller.class);
query.setParameter(1, username);
return query.getSingleResult();
}
But, a javax.persitence.NoResultException is catched. Where is the problem ? In the "where" clausule ? In the join ?. Any ideas ?
Notes:
1) The hierarchy works fine with "find" method. And the database is generated correctly.
2) I have an entry in the Traveller table that links up to one in User table.
3) In the database exists an user with the username that i am using to test.
4) The method get correctly the "username" parameter.
EDIT: Now works. The problem was the execution order of test cases. The query works fine.
Upvotes: 0
Views: 156
Reputation: 5480
I think your query is incorrect, I believe you are forced to name an alias for every entity you want to interact with. Have you tried this?
"SELECT t FROM Traveller t WHERE t.username = ?1", Traveller.class
Also you should have to cast the result when you call query.getSingleResult(). Because you pass in Traveller.class into the createQuery call which is paramaterized by Class<T> resultClass
Edit: Added a 1 after the ? as shown here. http://www.objectdb.com/java/jpa/query/parameter#Ordinal_Parameters_index_
public Country getCountryByName(EntityManager em, String name) {
TypedQuery<Country> query = em.createQuery(
"SELECT c FROM Country c WHERE c.name = ?1", Country.class);
return query.setParameter(1, name).getSingleResult();
}
Upvotes: 1