I have the following JPA (2.0.2) entities:
Employee
#Entity
#Table(name = "T_EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ElementCollection
#CollectionTable(name = "T_COMPETENCE")
private Set<Competence> competences;
// Getter and setters
}
and Competence
#Embeddable
public class Competence {
#JoinColumn(nullable = false)
#ManyToOne
private Skill skill;
// Getter and setters
}
(The skill entity shouldn't be important and is therefore omitted, so are various additional attributes.)
I'm using EclipseLink (2.2.0) to query my entities with a DAO. Now I'd like to use the following query:
public List<Employee> findBySkill(Skill skill) {
TypedQuery<Employee> query = getCurrentEntityManager().createQuery(
"SELECT e FROM Employee e JOIN e.competences c WHERE c.skill = :skill",
Employee.class);
query.setParameter("skill", skill);
return query.getResultList();
}
But it keeps throwing the following exception:
Caused by: Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [SELECT e FROM Employee e JOIN e.competences c WHERE c.skill = :skill], line 1, column 54: unknown state or association field [skill] of class [com.kaio.model.Competence].
at org.eclipse.persistence.exceptions.JPQLException.unknownAttribute(JPQLException.java:457)
at org.eclipse.persistence.internal.jpa.parsing.DotNode.validate(DotNode.java:88)
at org.eclipse.persistence.internal.jpa.parsing.Node.validate(Node.java:91)
at org.eclipse.persistence.internal.jpa.parsing.BinaryOperatorNode.validate(BinaryOperatorNode.java:34)
at org.eclipse.persistence.internal.jpa.parsing.EqualsNode.validate(EqualsNode.java:41)
at org.eclipse.persistence.internal.jpa.parsing.WhereNode.validate(WhereNode.java:34)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:207)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:183)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:173)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateReadQueryInternal(JPQLParseTree.java:110)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateQuery(JPQLParseTree.java:84)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:216)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:187)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:139)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:123)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1376)
... 48 more
The message is pretty clear: It can't find the attribute Skill on my class Competence. But in my opinion there is no reason on that. Or do I have a wrong approach on my problem? How should I query in a List of embeddable objects?
Any help is appreciated.
Okay, this seems to be a bug and it has been solved in a later version of eclipse link. I updated the project to EclipseLink 2.4 and the problem disappeared.
Your Competence table will have a Skill.id field, so try:
"SELECT e FROM Employee e JOIN e.competences c WHERE c.skill.id = :skillId"
query.setParameter("skillId", skill.getId());
Related
I have two Entities. Parent and Child.
#Entity
public class Parent {
#Id
#Column(name = "PARENT_ID")
private BigInteger id;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
}
#Entity
#NamedEntityGraph(name = "Child.parentObj", attributeNodes = #NamedAttributeNodes("parentObj"))
public class Child{
//blah blah blah
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="PARENT_ID")
Parent parentObj;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="CHILD_ID")
Set<Address> address
//blah blah blah
}
ChildRepository.java
public interface ChildRepository extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>{
#EntityGraph(value="Child.parentObj")
public List<Child> findAll(Specification<Child> spec);
}
I am trying to find child entities by criteria and it should always have parent.
I am getting exception that it is trying to find parentObj in Address table.
Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address [..]
I found this link and tried solution given by Joep but same error.
Spring Data JPA + JpaSpecificationExecutor + EntityGraph
what am I missing. I am not able to understand why/how i limit to look for parentObj in just Child Object as Address has no reference to Parent.
I am doing search by Address.street.
I have tried ad-hoc entity graph too. exception:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address
Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:500)
at org.hibernate.engine.query.spi.EntityGraphQueryHint.getFromElements(EntityGraphQueryHint.java:95)
at org.hibernate.engine.query.spi.EntityGraphQueryHint.toFromElements(EntityGraphQueryHint.java:68)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:676)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:4905)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4606)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2104)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:796)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:597)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
... 60 more
I wanted to find Child entries by criteria search and get ParentObj for each child. I wanted to do join and not individual select for Parent. I was trying to solve that by using EntityGraph but it didn't work. As #EKlavya pointed out Specification and EntityGraph don't work togather.
The way I solved was:
root.fetch("parentObj", JOIN.LEFT);
in my toPredicate method. this will get Child entity with Parent in 1 query.
You are using Child.parentObj as Entity graph name but you named the entity graph as Child.parent. Use
#EntityGraph(value="Child.parent")
Without #NamedEntityGraph
we can define an ad-hoc entity graph, without #NamedEntityGraph just use
#EntityGraph(attributePaths = {"parentObj"})
Update:
Entity graph and specification both are not working together.
There is a way to solve this. Don't do eager for parent fetch child only first then make a list of child ids from child's and get parents using in clause query using child ids. Total only 2 queries needed. If you want to solve this using 1 query use DSL to do raw query.
I use spring data jpa, I have these classe (each one have id... not displayed)
public class HOV{
#ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
#JoinColumn(name = "vehicle_type_id")
private VehicleTypes vehicleType;
...
}
public class VehicleTypes{
#OneToMany(mappedBy = "vehicleType")
private List<Vehicles> vehicles = new ArrayList<>();
}
so in hov repository, i tried to search by vehiclesId
List<HOV> findByVehicleTypeVehiclesId(Integer id);
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'hOVRepository': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Failed to create query for method public abstract java.util.List
com.lcm.repository.HOVRepository.findByVehicleTypeVehiclesId(java.lang.Integer)!
Illegal attempt to dereference path source [null.vehicleType.vehicles]
of basic type
In your situation, I think, is better to provide a query yourself, for example:
#Query("select h from HOV h join h.vehicleType vt left join vt.vehicles v where v.id = ?1")
List<HOV> findWithQuery(Integer vehicleId);
Here are my entities:
#Entity
public class Actor {
private List<Film> films;
#ManyToMany
#JoinTable(name="film_actor",
joinColumns =#JoinColumn(name="actor_id"),
inverseJoinColumns = #JoinColumn(name="film_id"))
public List<Film> getFilms(){
return films;
}
//... more in here
Moving on:
#Entity
public class Film {
private List actors;
#ManyToMany
#JoinTable(name="film_actor",
joinColumns =#JoinColumn(name="film_id"),
inverseJoinColumns = #JoinColumn(name="actor_id"))
public List<Actor> getActors(){
return actors;
}
//... more in here
And the join table:
#javax.persistence.IdClass(com.tugay.sakkillaa.model.FilmActorPK.class)
#javax.persistence.Table(name = "film_actor", schema = "", catalog = "sakila")
#Entity
public class FilmActor {
private short actorId;
private short filmId;
private Timestamp lastUpdate;
So my problem is:
When I remove a Film from an Actor and merge that Actor, and check the database, I see that everything is fine. Say the actor id is 5 and the film id is 3, I see that these id 's are removed from film_actor table..
The problem is, in my JSF project, altough my beans are request scoped and they are supposed to be fetching the new information, for the Film part, they do not. They still bring me Actor with id = 3 for Film with id = 5. Here is a sample code:
#RequestScoped
#Named
public class FilmTableBackingBean {
#Inject
FilmDao filmDao;
List<Film> allFilms;
public List<Film> getAllFilms(){
if(allFilms == null || allFilms.isEmpty()){
allFilms = filmDao.getAll();
}
return allFilms;
}
}
So as you can see this is a request scoped bean. And everytime I access this bean, allFilms is initially is null. So new data is fetched from the database. However, this fetched data does not match with the data in the database. It still brings the Actor.
So I am guessing this is something like a cache issue.
Any help?
Edit: Only after I restart the Server, the fetched information by JPA is correct.
Edit: This does not help either:
#Entity
public class Film {
private short filmId;
#ManyToMany(mappedBy = "films", fetch = FetchType.EAGER)
public List<Actor> getActors(){
return actors;
}
The mapping is wrong.
The join table is mapped twice: once as the join table of the many-to-many association, and once as an entity. It's one or the other, but not both.
And the many-to-many is wrong as well. One side MUST be the inverse side and use the mappedBy attribute (and thus not define a join table, which is already defined at the other, owning side of the association). See example 7.24, and its preceeding text, in the Hibernate documentation (which also applies to other JPA implementations)
Side note: why use a short for an ID? A Long would be a wiser choice.
JB Nizet is correct, but you also need to maintain both sides of relationships as there is caching in JPA. The EntityManager itself caches managed entities, so make sure your JSF project is closing and re obtaining EntityManagers, clearing them if they are long lived or refreshing entities that might be stale. Providers like EclipseLink also have a second level cache http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching
I have an entity VM with a relationship to another entity BP. The relationship is eagerly fetched. First I load a VM. After loading the VM is detached, serialized and changed at the client side. Now I want to update the changed entity so I use the EntityManager.merge() method from JPA. Now I run into the following error from OpenJPA:
"Encountered new object in persistent field "Vm.bp" during attach. However, this field does not allow cascade attach. Set the cascade attribute for this field to CascadeType.MERGE or CascadeType.ALL (JPA annotations) or "merge" or "all" (JPA orm.xml). You cannot attach a reference to a new object without cascading."
Why do I have to add a Cascade.MERGE to a relationship to another entity that will never change? And why does JPA think that BP is a new object ("...cannot attach reference to a new object...")?
When using ManyToOne relationships do I always have to add Cascade.MERGE in order to update the entity or is this because of the EAGER fetch type?
Here's my entity:
#Entity
#Table(name = "VM")
public class Vm extends BaseEntity implements Serializable {
public static final long serialVersionUID = -8495541781540291902L;
#Id
#SequenceGenerator(name = "SeqVm", sequenceName = "SEQ_VM")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqVm")
#Column(name = "ID")
private Long id;
// lots of other fields and relations
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "BP_ID")
private Bp bp;
// ...
}
I found the reason why this error message comes up: The #Version annotated database field of the related Bp entity was initialized with "0". Apparently OpenJPA (1.2.3) is not able to cope with entity versions of zero.
Setting the version to 1 solved my issue.
I have the following situation:
(source: kawoolutions.com)
JPA 2.0 mappings (It might probably suffice to consider only the Zip and ZipId classes as this is where the error seems to come from):
#Entity
#Table(name = "GeoAreas")
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING)
public abstract class GeoArea implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
protected Integer id;
#Column(name = "name")
protected String name;
...
}
#Entity
#Table(name = "Countries")
#DiscriminatorValue(value = "country")
public class Country extends GeoArea
{
#Column(name = "iso_code")
private String isoCode;
#Column(name = "iso_nbr")
private String isoNbr;
#Column(name = "dial_code")
private Integer dialCode = null;
...
}
#Entity
#Table(name = "Zips")
#IdClass(value = ZipId.class)
public class Zip implements Serializable
{
#Id
#Column(name = "code")
private String code;
#Id
#ManyToOne
#JoinColumn(name = "country_code", referencedColumnName = "iso_code")
private Country country = null;
...
}
public class ZipId implements Serializable
{
private String country;
private String code;
...
}
Pretty simple design:
A country is a geo area and inherits the ID from the root class. A ZIP code is unique within its country so it combines an ISO code plus the actual ZIP code as PK. Thus Zips references Countries.iso_code, which has an alternative unique, not-null key on it (reference to non-primary key column!). The Zip.country association gets an #Id annotation and its variable name is the same as the one in its ID class ZipId.
However I get this error message from within Eclipse (also using JBoss Tools):
Validation Message:
"The attribute matching the ID class attribute country does not have the correct type java.lang.String"
Why is this wrong in JPA 2.0 syntax (see #Id annotation on Zip.country)? I don't think it is. After all the types of Zip.country and ZipId.country can't be the same for JPA 2 because of the #Id annotation on the #ManyToOne and the PK being a simple integer, which becomes the ID class counterpart. Can anyone check/confirm this please?
Could this be a bug, probably in JBoss Tools? (Which software component is reporting the above bug? When putting the 3 tables and entity classes into a new JavaSE project there's no error shown with the exact code...)
Answering own question...
The way I modeled the reference, I use a String because the FK points to the iso_code column in the Countries table which is a CHAR(2), so basically my mapping is right. However, the problem is that JPA 2.0 doesn't allow anything but references to primary key columns. This is what the Eclipse Dali JPA validator shows.
Taken from "Pro JPA 2.0" by Keith/Schincariol p.283 top, "Basic Rules for Derived Identifiers" (rule #6): "If an id attribute in an entity is a relationship, then the type of the matching attribute in the id class is of the same type as the primary key type of the target entity in the relationship (whether the primary key type is a simple type, an id class, or an embedded id class)."
Personal addendum:
I disagree with JPA 2.0 having this limitation. JPA 1.0 mappings allow references to non-PK columns. Note, that using JPA 1.0 mappings instead isn't what I'm looking for. I'd rather be interested in the reason why this restriction was imposed on JPA 2.0. The JPA 2.0 is definitely limiting.
I'd say focus your attention on the CompoundIdentity relationship. See this question, and my answer there
Help Mapping a Composite Foreign Key in JPA 2.0
ZipId has no "country" field in your case
I have not tested your code, but it looks pretty much related to the use of the #PrimareKeyJoinColumn annotation.
The JPA 2.0 specification in section 11.1.40 states:
The PrimaryKeyJoinColumn annotation is
used to join the primary table of an
entity subclass in the JOINED mapping
strategy to the primary table of its
superclass; it is used within a
SecondaryTable annotation to join a
secondary table to a primary table;
and it may be used in a OneToOne
mapping in which the primary key of
the referencing entity is used as a
foreign key to the referenced
entity[108].
The example in the spec looks like your case.
#Entity
#Table(name="CUST")
#Inheritance(strategy=JOINED)
#DiscriminatorValue("CUST")
public class Customer { ... }
#Entity
#Table(name="VCUST")
#DiscriminatorValue("VCUST")
#PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer { ... }
I hope that helps!