I have a Java EE Entity class containing a java.util.Date
field. The value for this field for some reason is not being stored.
@Entity
@Table(name = "PERSISTENCE_USER")
@NamedQueries({
@NamedQuery(name = "findAllusers",
query = "SELECT U FROM User u "
+ "ORDER BY u.userId"
),
@NamedQuery(name = "getAUser",
query = "SELECT U FROM User u "
+ "WHERE u.userId =?1 AND u.password=?2 "
+ "ORDER BY u.userId"
)
})
public class User implements Serializable {
private static final long serialVersionUID = 10044331905L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String firstName;
@NotNull
private String lastName;
@Temporal(TemporalType.TIMESTAMP)
private Date dateOfBirth;
............
}
Here is a singleton that populates a row in the table:
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class DataLoaderSessionBean {
@EJB
private LoginRequestSessionBean requestLogin;
@PostConstruct
public void createData() {
try {
List<User> users = new ArrayList();
Date date = new Date(System.currentTimeMillis());
users.add(new User("Joe","Ottaviano",date));
users.add(new User("Partrick","Tucker",date));
requestLogin.addUsers(users);
} catch (Exception e) {
}
}
Later when I retrieve and examine the data the date field is null:
@Stateful
public class LoginRequestSessionBean {
@PersistenceContext
EntityManager em;
public void addUsers(List<User> users) throws EJBException {
users
.stream()
.forEach(this::addUser);
}
public void addUser(User u) throws EJBException {
try {
if (em != null) {
if (em.isOpen()) {
if (u != null) {
em.persist(u);
} else {
throw (new EJBException("NULL user can not be added"));
}
} else {
throw (new EJBException("EntityManager is closed"));
}
} else {
throw (new EJBException("EntityManager is NULL"));
}
} catch (EntityManagerSetupException e) {
System.out.println("Caught an Exception: "+ e.getMessag();
throw e;
}
}
public List<User> getUsers() throws EJBException{
logger.entering(className, "getUsers()");
List<User> users = null;
try {
if (em != null) {
if (em.isOpen()) {
Query q = em.createNamedQuery("findAllusers");
users = (List<User>) q.getResultList();
for (User user : users){
Date d = user.getDateOfBirth();
if(d == null){
System.out.println("The dob for user "+user.getLasName()+" null);
}
}
} else {
throw (new EJBException("EntityManager is closed"));
}
} else {
throw (new EJBException("EntityManager is NULL"));
}
} catch (EntityManagerSetupException e) {
System.out.println(e.getMessage());
throw new EJBException(e.getMessage());
}
return users;
}
}
Any idea how to store values for java.util.Date
?
The code you posted seems correct. You should check that the constructor in the User
class sets the dateOfBirth
field.