I've encountered a rather odd case in Java EE 6 where using the JPA EntityManager's find
method along with an entity's primary id returns null, but using the Criteria API to select all entities with that id works fine.
Here is the code I'm using for find
:
// Always returns null, even for records I know for sure are in there.
user = em.find(User.class, userId);
...and here's the code I'm using with the Criteria API:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> u = criteria.from(User.class);
TypedQuery<User> query = em.createQuery(
criteria.select(u).where(builder.equal(u.get("id"), userId)));
user = query.getSingleResult();
Any idea why find
returns null but Criteria finds the User? I tried these two alternate methods in the exact same spot in the program.
Here are the relevant portions of the User entity:
@Entity
@Table(name = "USERS")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
...
private Long id;
...
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_generator")
@SequenceGenerator(name = "user_id_generator", sequenceName = "user_sequence", allocationSize = 1)
@Column(name="id")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
...
}
I figured out the problem. It was due to a field in the database being null
where it should not have been permitted. This was due to me editing it by hand. After I added a value to that field, the problem went away.