How to prevent Spring JPA Entities from becoming optional when saving to CRUDRepository?












0















I was trying to learn Spring Framework and ran into a problem with saving entities into CRUD Repository. I had few Entities with automatic numeric ID generation and they work just fine, but then I tried to make a class with String being a primary key just like this:



@Entity
@Table(name = "USERS")
@Builder
public class User {
@Id
@Column(name = "USER_NAME", nullable = false)
@Getter @Setter
private String name;

@Column(name = "USER_PASS", nullable = false)
@Getter @Setter
private String pass;
}


First I was getting exceptions about this class not having a default constructor:



org.springframework.orm.jpa.JpaSystemException: No default constructor for entity:  : com.company.Model.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity:  : com.company.Model.User


Already weird, but still I decided to change @Builder annotation into 2 constructors, one with both arguments and second with none. I tried to save the entity instance into CRUD Repository userDAO (which is nothing more than interface extending CRUDRepository) by the typical test:



User admin = new User("admin", "6aDcZ72k");

...

@Test
public void saveUserAndFindById() {
admin = userDAO.save(admin);
assertThat(userDAO.findById(admin.getName())).isEqualTo(admin);
}


The result was assertion failed because the saved entity had "Optional" type:



org.junit.ComparisonFailure: 
Expected :com.company.Model.User@2c06b113
Actual :Optional[com.company.Model.User@2c06b113]


I know I'm doing something really wrong but can't figure this out. Or maybe there is a way to just prevent making it optional? There must be few other entities with the reference on this class, but these references obviously don't work because of the above issue.










share|improve this question

























  • Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

    – Pooja Aggarwal
    Nov 21 '18 at 7:10











  • To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

    – geneqew
    Nov 21 '18 at 7:33











  • @PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

    – Silvan
    Nov 21 '18 at 7:35











  • @geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

    – Silvan
    Nov 21 '18 at 7:36











  • Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

    – JB Nizet
    Nov 21 '18 at 7:37


















0















I was trying to learn Spring Framework and ran into a problem with saving entities into CRUD Repository. I had few Entities with automatic numeric ID generation and they work just fine, but then I tried to make a class with String being a primary key just like this:



@Entity
@Table(name = "USERS")
@Builder
public class User {
@Id
@Column(name = "USER_NAME", nullable = false)
@Getter @Setter
private String name;

@Column(name = "USER_PASS", nullable = false)
@Getter @Setter
private String pass;
}


First I was getting exceptions about this class not having a default constructor:



org.springframework.orm.jpa.JpaSystemException: No default constructor for entity:  : com.company.Model.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity:  : com.company.Model.User


Already weird, but still I decided to change @Builder annotation into 2 constructors, one with both arguments and second with none. I tried to save the entity instance into CRUD Repository userDAO (which is nothing more than interface extending CRUDRepository) by the typical test:



User admin = new User("admin", "6aDcZ72k");

...

@Test
public void saveUserAndFindById() {
admin = userDAO.save(admin);
assertThat(userDAO.findById(admin.getName())).isEqualTo(admin);
}


The result was assertion failed because the saved entity had "Optional" type:



org.junit.ComparisonFailure: 
Expected :com.company.Model.User@2c06b113
Actual :Optional[com.company.Model.User@2c06b113]


I know I'm doing something really wrong but can't figure this out. Or maybe there is a way to just prevent making it optional? There must be few other entities with the reference on this class, but these references obviously don't work because of the above issue.










share|improve this question

























  • Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

    – Pooja Aggarwal
    Nov 21 '18 at 7:10











  • To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

    – geneqew
    Nov 21 '18 at 7:33











  • @PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

    – Silvan
    Nov 21 '18 at 7:35











  • @geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

    – Silvan
    Nov 21 '18 at 7:36











  • Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

    – JB Nizet
    Nov 21 '18 at 7:37
















0












0








0








I was trying to learn Spring Framework and ran into a problem with saving entities into CRUD Repository. I had few Entities with automatic numeric ID generation and they work just fine, but then I tried to make a class with String being a primary key just like this:



@Entity
@Table(name = "USERS")
@Builder
public class User {
@Id
@Column(name = "USER_NAME", nullable = false)
@Getter @Setter
private String name;

@Column(name = "USER_PASS", nullable = false)
@Getter @Setter
private String pass;
}


First I was getting exceptions about this class not having a default constructor:



org.springframework.orm.jpa.JpaSystemException: No default constructor for entity:  : com.company.Model.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity:  : com.company.Model.User


Already weird, but still I decided to change @Builder annotation into 2 constructors, one with both arguments and second with none. I tried to save the entity instance into CRUD Repository userDAO (which is nothing more than interface extending CRUDRepository) by the typical test:



User admin = new User("admin", "6aDcZ72k");

...

@Test
public void saveUserAndFindById() {
admin = userDAO.save(admin);
assertThat(userDAO.findById(admin.getName())).isEqualTo(admin);
}


The result was assertion failed because the saved entity had "Optional" type:



org.junit.ComparisonFailure: 
Expected :com.company.Model.User@2c06b113
Actual :Optional[com.company.Model.User@2c06b113]


I know I'm doing something really wrong but can't figure this out. Or maybe there is a way to just prevent making it optional? There must be few other entities with the reference on this class, but these references obviously don't work because of the above issue.










share|improve this question
















I was trying to learn Spring Framework and ran into a problem with saving entities into CRUD Repository. I had few Entities with automatic numeric ID generation and they work just fine, but then I tried to make a class with String being a primary key just like this:



@Entity
@Table(name = "USERS")
@Builder
public class User {
@Id
@Column(name = "USER_NAME", nullable = false)
@Getter @Setter
private String name;

@Column(name = "USER_PASS", nullable = false)
@Getter @Setter
private String pass;
}


First I was getting exceptions about this class not having a default constructor:



org.springframework.orm.jpa.JpaSystemException: No default constructor for entity:  : com.company.Model.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity:  : com.company.Model.User


Already weird, but still I decided to change @Builder annotation into 2 constructors, one with both arguments and second with none. I tried to save the entity instance into CRUD Repository userDAO (which is nothing more than interface extending CRUDRepository) by the typical test:



User admin = new User("admin", "6aDcZ72k");

...

@Test
public void saveUserAndFindById() {
admin = userDAO.save(admin);
assertThat(userDAO.findById(admin.getName())).isEqualTo(admin);
}


The result was assertion failed because the saved entity had "Optional" type:



org.junit.ComparisonFailure: 
Expected :com.company.Model.User@2c06b113
Actual :Optional[com.company.Model.User@2c06b113]


I know I'm doing something really wrong but can't figure this out. Or maybe there is a way to just prevent making it optional? There must be few other entities with the reference on this class, but these references obviously don't work because of the above issue.







java spring spring-data-jpa






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 7:33









Billy Frost

1,800198




1,800198










asked Nov 21 '18 at 7:05









SilvanSilvan

134




134













  • Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

    – Pooja Aggarwal
    Nov 21 '18 at 7:10











  • To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

    – geneqew
    Nov 21 '18 at 7:33











  • @PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

    – Silvan
    Nov 21 '18 at 7:35











  • @geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

    – Silvan
    Nov 21 '18 at 7:36











  • Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

    – JB Nizet
    Nov 21 '18 at 7:37





















  • Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

    – Pooja Aggarwal
    Nov 21 '18 at 7:10











  • To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

    – geneqew
    Nov 21 '18 at 7:33











  • @PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

    – Silvan
    Nov 21 '18 at 7:35











  • @geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

    – Silvan
    Nov 21 '18 at 7:36











  • Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

    – JB Nizet
    Nov 21 '18 at 7:37



















Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

– Pooja Aggarwal
Nov 21 '18 at 7:10





Try this assertThat(userDAO.findById(admin.getName()).getPassword()).isEqualTo(admin.getPassword());

– Pooja Aggarwal
Nov 21 '18 at 7:10













To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

– geneqew
Nov 21 '18 at 7:33





To start with, aside from the 2 constructors you've added, also include a default constructor in your entity (without args)

– geneqew
Nov 21 '18 at 7:33













@PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

– Silvan
Nov 21 '18 at 7:35





@PoojaAggarwal Yeah, it'll pass, but still an attempt to make a reference on User from another entity will throw TransientPropertyValueException telling me that User is transcient/optional and that is not really meant to be.

– Silvan
Nov 21 '18 at 7:35













@geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

– Silvan
Nov 21 '18 at 7:36





@geneqew Like I said, the second constructor is already without any args. It just don't work without default constructor

– Silvan
Nov 21 '18 at 7:36













Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

– JB Nizet
Nov 21 '18 at 7:37







Well, yes, findById() returns an Optional<User>. That would be clear if you read the javadoc. docs.spring.io/spring-data/data-commons/docs/current/api/org/…. Here's the javadoc of Optional to learn how to use it: docs.oracle.com/javase/8/docs/api/java/util/Optional.html

– JB Nizet
Nov 21 '18 at 7:37














2 Answers
2






active

oldest

votes


















0














First of all,jpa require the entity has a No Arguments Constructor cause it will create a instance first and then populate it.The easiest way is to add @NoArgumentsConstructor that offered by lombok on the entity class.



And then,Optional is used by spring data jpa in order to avoid NullPointException and in fact it be is useful actually.If you want to use the interface that Spring-data-jpa offered,then you have to use Optional too.You cloud look here for more info about Optional:link1,link2



By the way,I usually use it like:



ExampleEntity example=exampleRepository.findById(id).orElseThrow(()->new ExampleNotFoundException());


In this way,you dont need to deal with Optional or think about NullPointException.



or:



ExampleEntity example=exampleRepository.findById(id).orElse(null);


In this way if you cant find the target entity,then it will be null.So dont forget to check if the entity is null.



Hope it could help~~~






share|improve this answer

































    1














    It is not your save(...) that is returning Optional but userDAO.findById(admin.getName(). According to the documentation, CrudReposiotry provides a findById() whose return type is Optional<T>.



    public interface CrudRepository<T, ID extends Serializable>
    extends Repository<T, ID> {
    Optional<T> findById(ID primaryKey);
    }


    If you do not want Optional as return type, You will need to provide your own method to do that. For example:



    public interface PeronRepository extends CrudRepository<Person, String> {
    Person findById(String personId);
    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53406857%2fhow-to-prevent-spring-jpa-entities-from-becoming-optional-when-saving-to-crudrep%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      First of all,jpa require the entity has a No Arguments Constructor cause it will create a instance first and then populate it.The easiest way is to add @NoArgumentsConstructor that offered by lombok on the entity class.



      And then,Optional is used by spring data jpa in order to avoid NullPointException and in fact it be is useful actually.If you want to use the interface that Spring-data-jpa offered,then you have to use Optional too.You cloud look here for more info about Optional:link1,link2



      By the way,I usually use it like:



      ExampleEntity example=exampleRepository.findById(id).orElseThrow(()->new ExampleNotFoundException());


      In this way,you dont need to deal with Optional or think about NullPointException.



      or:



      ExampleEntity example=exampleRepository.findById(id).orElse(null);


      In this way if you cant find the target entity,then it will be null.So dont forget to check if the entity is null.



      Hope it could help~~~






      share|improve this answer






























        0














        First of all,jpa require the entity has a No Arguments Constructor cause it will create a instance first and then populate it.The easiest way is to add @NoArgumentsConstructor that offered by lombok on the entity class.



        And then,Optional is used by spring data jpa in order to avoid NullPointException and in fact it be is useful actually.If you want to use the interface that Spring-data-jpa offered,then you have to use Optional too.You cloud look here for more info about Optional:link1,link2



        By the way,I usually use it like:



        ExampleEntity example=exampleRepository.findById(id).orElseThrow(()->new ExampleNotFoundException());


        In this way,you dont need to deal with Optional or think about NullPointException.



        or:



        ExampleEntity example=exampleRepository.findById(id).orElse(null);


        In this way if you cant find the target entity,then it will be null.So dont forget to check if the entity is null.



        Hope it could help~~~






        share|improve this answer




























          0












          0








          0







          First of all,jpa require the entity has a No Arguments Constructor cause it will create a instance first and then populate it.The easiest way is to add @NoArgumentsConstructor that offered by lombok on the entity class.



          And then,Optional is used by spring data jpa in order to avoid NullPointException and in fact it be is useful actually.If you want to use the interface that Spring-data-jpa offered,then you have to use Optional too.You cloud look here for more info about Optional:link1,link2



          By the way,I usually use it like:



          ExampleEntity example=exampleRepository.findById(id).orElseThrow(()->new ExampleNotFoundException());


          In this way,you dont need to deal with Optional or think about NullPointException.



          or:



          ExampleEntity example=exampleRepository.findById(id).orElse(null);


          In this way if you cant find the target entity,then it will be null.So dont forget to check if the entity is null.



          Hope it could help~~~






          share|improve this answer















          First of all,jpa require the entity has a No Arguments Constructor cause it will create a instance first and then populate it.The easiest way is to add @NoArgumentsConstructor that offered by lombok on the entity class.



          And then,Optional is used by spring data jpa in order to avoid NullPointException and in fact it be is useful actually.If you want to use the interface that Spring-data-jpa offered,then you have to use Optional too.You cloud look here for more info about Optional:link1,link2



          By the way,I usually use it like:



          ExampleEntity example=exampleRepository.findById(id).orElseThrow(()->new ExampleNotFoundException());


          In this way,you dont need to deal with Optional or think about NullPointException.



          or:



          ExampleEntity example=exampleRepository.findById(id).orElse(null);


          In this way if you cant find the target entity,then it will be null.So dont forget to check if the entity is null.



          Hope it could help~~~







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 8:21

























          answered Nov 21 '18 at 8:10









          AokoQinAokoQin

          794




          794

























              1














              It is not your save(...) that is returning Optional but userDAO.findById(admin.getName(). According to the documentation, CrudReposiotry provides a findById() whose return type is Optional<T>.



              public interface CrudRepository<T, ID extends Serializable>
              extends Repository<T, ID> {
              Optional<T> findById(ID primaryKey);
              }


              If you do not want Optional as return type, You will need to provide your own method to do that. For example:



              public interface PeronRepository extends CrudRepository<Person, String> {
              Person findById(String personId);
              }





              share|improve this answer




























                1














                It is not your save(...) that is returning Optional but userDAO.findById(admin.getName(). According to the documentation, CrudReposiotry provides a findById() whose return type is Optional<T>.



                public interface CrudRepository<T, ID extends Serializable>
                extends Repository<T, ID> {
                Optional<T> findById(ID primaryKey);
                }


                If you do not want Optional as return type, You will need to provide your own method to do that. For example:



                public interface PeronRepository extends CrudRepository<Person, String> {
                Person findById(String personId);
                }





                share|improve this answer


























                  1












                  1








                  1







                  It is not your save(...) that is returning Optional but userDAO.findById(admin.getName(). According to the documentation, CrudReposiotry provides a findById() whose return type is Optional<T>.



                  public interface CrudRepository<T, ID extends Serializable>
                  extends Repository<T, ID> {
                  Optional<T> findById(ID primaryKey);
                  }


                  If you do not want Optional as return type, You will need to provide your own method to do that. For example:



                  public interface PeronRepository extends CrudRepository<Person, String> {
                  Person findById(String personId);
                  }





                  share|improve this answer













                  It is not your save(...) that is returning Optional but userDAO.findById(admin.getName(). According to the documentation, CrudReposiotry provides a findById() whose return type is Optional<T>.



                  public interface CrudRepository<T, ID extends Serializable>
                  extends Repository<T, ID> {
                  Optional<T> findById(ID primaryKey);
                  }


                  If you do not want Optional as return type, You will need to provide your own method to do that. For example:



                  public interface PeronRepository extends CrudRepository<Person, String> {
                  Person findById(String personId);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 7:40









                  PrashantPrashant

                  1,172919




                  1,172919






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53406857%2fhow-to-prevent-spring-jpa-entities-from-becoming-optional-when-saving-to-crudrep%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Xamarin.form Move up view when keyboard appear

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Anylogic : not able to use stopDelay()