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;
}
...
}
The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit.
Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts. Related Hibernate docs can be found here and here.
getFlushMode – get the flush mode for all the objects of the persistence context. lock - Lock an entity instance that is contained in the persistence context with the specified lock mode type. refresh – it refreshes the state of the instance from the database also it will overwrite the changes to the entity.
EntityManagerFactory vs EntityManagerWhile EntityManagerFactory instances are thread-safe, EntityManager instances are not. The injected JPA EntityManager behave just like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With