Skip to content
Advertisement

JPA does not return default value after saving

I faced a problem. A have an entity:

@Entity
@Table(name = "user")
public class User {

  @Id
  @GeneratedValue
  private Integer id;

  @Column(name = "date_create", insertable = false, updatable = false, nullable = false)
  private Date dateCreate;

}

DDL of the related table:

CREATE TABLE user (
  id SERIAL PRIMARY KEY,
  date_create TIMESTAMP NOT NULL DEFAULT now()
);

I have such logic:

@Service
public class Service1 {

  @Autowired
  private UserRepository userRepository;

  @Transactional
  public User createUser() {
    return userRepository(new User());
  }
 }

 @Service
 public class Service2 {

   @Autowired
   private Service1 service1;

   public void createUser() {
     User createdUser = service1.createUser();
     System.out.println(createdUser.getDateCreate()); // actual result : null
   }
  }

Field dateCreate is set by DB function now() but it is not returned by JPA in created entity.

Does anyone know how to solve this problem? Without using Hibernate or Spring specific tools. Just JPA.

Advertisement

Answer

You need to refresh the data after saving it to the database and to get the latest state of the object, as entityManager.refresh(createdUser)

You can use it as mentioned below.

 @Service
 public class Service2 {

   @Autowired
   private Service1 service1;

   @PersistenceContext
   private EntityManager entityManager;

   public void createUser() {
     User createdUser = service1.createUser();
     entityManager.refresh(createdUser);
     System.out.println(createdUser.getDateCreate()); // actual result : null
   }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement