保存后无法获取数据库生成的值

时间:2017-07-06 11:49:15

标签: postgresql hibernate jpa spring-boot spring-data-jpa

我正在使用SpringBoot,Spring数据和postgresql。

在postgres中我创建了一个表。

@Entity
public class User implements Serializable {

  private static final long serialVersionUID = 9129894781337596497L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @Column(insertable = false)
  private String userId;

  public static User create(){
    User user = new User();
    return user;
  }

  public String getUserId(){
    return userId;
  }

}

比创建实体

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}

比如创建这样的jpa存储库

User user = userRepository.save(User.create());
assertThat(user.getUserId()).isNotNull();

当我保存用户时,我需要获取id和userId,但我得到null,而在数据库中生成UUID。

public class ParentModel {
    public List<FolderModel> FolderModels { get; set; }
}

如何从数据库中获取这些生成的值?

2 个答案:

答案 0 :(得分:1)

你必须重新读取插入的实体OR(因为Hibernate 3.2?)你可以在列(https://docs.jboss.org/hibernate/orm/5.0/topical/html/generated/GeneratedValues.html#_legacy_support_in_database_generation)上指定@Generated(GenerationTime.INSERT),这会导致hibernate重新读取属性值插入后。

我创建了一个小小的演示:

http://peter.risko.hu/java_incubator/spring_data_postgres_uuid.zip

用户实体:

@Id
@SequenceGenerator(name="seq", sequenceName="seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
@Column(columnDefinition = "serial")
private Integer id;

@Column(insertable = false, name="user_id")
private String userId;

public String getUserId(){
    return userId;
}

public static User create(){
    User user = new User();
    log.info("user created in memory: " + user);
    return user;
}

public Integer getId(){
    return id;
}

@Override
public String toString() {
    return "[id: " + id + ", userId: " + userId + "]";
}

测试:

@Test
public void testInsert() {
    User u = userRepository.save(User.create());
    log.info("user after save: " + u);
    log.info("users queried from db: " + userRepository.findAll());
}

输出:

tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 960, userId: null]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8]]

如果我应用@Generated(GenerationTime.INSERT):

@Column(insertable = false, name="user_id")
@Generated(GenerationTime.INSERT)
private String userId;

然后结果是:

tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8], [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]]

答案 1 :(得分:0)

您应该将属性iduserId中缺少的getter和setter添加到User类中。