我有一个包含 java.util.Date
现场。由于某种原因,未存储此字段的值。
@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;
............
}
下面是一个填充表中一行的单例:
@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) {
}
}
稍后检索和检查数据时,日期字段为空:
@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;
}
}
你知道如何存储 java.util.Date
?
1条答案
按热度按时间atmip9wb1#
你发布的代码似乎是正确的。您应该检查
User
类设置dateOfBirth
现场。