JPA保存后不返回默认值

huangapple go评论72阅读模式
英文:

JPA does not return default value after saving

问题

我遇到了一个问题。
我有一个实体:

@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:

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

我有以下逻辑:

@Service
public class Service1 {

  @Autowired
  private UserRepository userRepository;

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

@Service
public class Service2 {

  @Autowired
  private Service1 service1;

  public void createUser() {
    User createdUser = service1.createUser();
    System.out.println(createdUser.getDateCreate()); // 实际结果:null
  }
}

字段 dateCreate 是由数据库函数 now() 设置的,但在创建的实体中,JPA 没有返回它。

有人知道如何解决这个问题吗?不使用 Hibernate 或 Spring 特定工具,只用 JPA。

英文:

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.

答案1

得分: 4

你需要在将数据保存到数据库后进行数据刷新,以获取对象的最新状态,方法是使用 entityManager.refresh(createdUser)

您可以按照以下方式使用它。

@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()); // 实际结果:null
  }
}
英文:

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
   }
}

答案2

得分: 1

你可以使用注解 @PrePersist 在持久化之前创建日期。

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

    @Id
    @GeneratedValue
    private Integer id;

    @Column(name = "date_create")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreate;

    @PrePersist
    private void onCreate() {
        dateCreate = new Date();
    }
}
英文:

You can use the anotation @PrePersist to create the date before persisting.

    @Entity
    @Table(name = "user")
    public class User {
    
          @Id
          @GeneratedValue
          private Integer id;
        
          @Column(name = "date_create")
          @Temporal(TemporalType.TIMESTAMP)
          private Date dateCreate;


          @PrePersist
          private void onCreate() {
          dateCreate= new Date();
         }
        
        }

答案3

得分: 0

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

  @Id
  @GeneratedValue
  private Integer id;

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

}

private LocalDateTime dateCreate;
  1. LocalDate 用于将日期存储到数据库中,不包含时间。
  2. LocalDateTime 用于将带有时间的日期存储到数据库中。

<details>
<summary>英文:</summary>

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

@Id
@GeneratedValue
private Integer id;

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

}

OR

private LocaleDateTime dateCreate;

1. LocaleDate is store date into database without time.
2. LocaleDateTime is store date with time into database.

</details>



huangapple
  • 本文由 发表于 2020年8月18日 18:33:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63466802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定