0

I have object with @Id (primary key) and this is some business UIID field and I want another Long technical Id for some reasons but when saving the object I get null from getObjectId field:

@Id
private String id;

@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "object_id")
private Long objectId;

public Long getObjectId() {
    return objectId;
}

public void setObjectId(Long objectId) {
    this.objectId = objectId;
}

I have this storage class:

   interface MyObjectStorage extends JpaRepository<MyObject, String>

And this is how I save it:

 final MyObject saved = storage.saveAndFlush(toSave);
 saved.objectId is null here..

And in my MySQL db the objectId field is marked not null auto increment..

PS. And I don't want this objectId field to be used by JPA when findById is executed.

michealAtmi
  • 1,012
  • 2
  • 14
  • 36
  • you can achieve with database sequence https://stackoverflow.com/questions/51633747/map-autoincrement-non-primary-key-in-hibernate – Mohamed Saligh Dec 18 '19 at 09:35
  • But do I must to mark this field with @Id annotation ? I don't want JPA to use this field when findById is executed. The String id field must be used then.. – michealAtmi Dec 18 '19 at 09:37
  • 1
    pls take a look at the answer for this post https://stackoverflow.com/questions/277630/hibernate-jpa-sequence-non-id – star67 Dec 18 '19 at 09:45
  • 3
    Does this answer your question? [Hibernate JPA Sequence (non-Id)](https://stackoverflow.com/questions/277630/hibernate-jpa-sequence-non-id) – star67 Dec 18 '19 at 09:47
  • Ok I see those posts are related to my needs, Thanks! – michealAtmi Dec 18 '19 at 09:57

2 Answers2

0

Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The @GeneratedValue annotation is only used in conjunction with @Id to create auto-numbers.

The solution (or work-around) suggested in this forum is to create a separate entity with a generated Id, something like this:

 @Entity
    public class GeneralSequenceNumber {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "object_id")
       private Long objectId;
    }

    @Entity 
    public class MyEntity {
      @Id ..
      private Long id;

      @OneToOne(...)
      private GeneralSequnceNumber myVal;
    }
Seshidhar G
  • 265
  • 1
  • 9
-1

try the following code @Id must be a type of Integer or Long

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "object_id")
private Long objectId;

private String id;

public Long getObjectId() {
    return objectId;
}

public void setObjectId(Long objectId) {
    this.objectId = objectId;
}

interface MyObjectStorage extends JpaRepository<MyObject, Long>

Sandhya
  • 1
  • 3