I have the following relationship:
@Entity
public class SomeEntity {
//...
@EmbeddedId
private SomeEntityIdentity id;
@OneToOne
@NotFound(action = NotFoundAction.EXCEPTION) //This is the important bit
@JoinColumns({
//...
})
private OtherEntity example;
//...
}
Then, I use Spring data's findOne()
to grab my entity by the Id:
SomeEntityIdentity id = new SomeEntityIdentity();
id.setAttribute1(1);
id.setAttribute2(new BigDecimal(123));
return this.someEntityRepository.findOne(id);
The problem is that no exception is thrown if OtherEntity
is not found, as findOne()
simply returns null. Even if I set @OneToOne(optional = false)
I still get a null from findOne()
, when I was excepting only OtherEntity
to be null.
I believe an exception should be thrown. Does anyone any have ideas?
Thank you!
Edit: Identity and Repository classes below.
@Embeddable
public class SomeEntityIdentity implements Serializable {
private int attribute1;
private BigDecimal attribute2;
public void setAttribute1(int attribute1) {
this.attribute1 = attribute1;
}
public void setAttribute2(BigDecimal attribute2) {
this.attribute2 = attribute2;
}
}
public interface SomeEntityRepository extends JpaRepository<SomeEntity, SomeEntityIdentity> {
}
Turned out to be an incompatibility between Hibernate and Spring Data versions.
This project was using Hibernate 4.3.1.Final
to take advantage of JPA 2.1
features; but with spring-data-jpa
1.6.6.RELEASE
, that doesn't support that Hibernate version.
Because everything was working correctly (up until this issue) I didn't notice this at first. When I tried upgrading spring-data-jpa
to an Hibernate 4.3
compatible version I couldn't, because spring-data-jpa
jumps from Hibernate 3 to Hibernate 5 on 2.0.x
versions. This also seems to require Java 8, so that was a no go for me.
Ended up downgrading to Hibernate 3.6.10.Final
and everything started working OK.
TL;DR: Always check version compatibility between Spring and other libraries, even if there's no obvious errors.
I just wanted to finish by saying that Spring version management is a total pain.
Working dependency configuration:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.6.6.RELEASE</version>
</dependency>