Not able to use JPA annotation @OneToOne(cascade=CascadeType.ALL)











up vote
0
down vote

favorite












I have a parent class Contact which has one to one relationship with ContactType.



@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I am trying to create a new contact using ContactRepository.save() which extends JPARepository. I am getting the following error.




Violation of PRIMARY KEY constraint type. Cannot insert duplicate key in object ContactType




If I change the contact type declaration to below:



@OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I get the following error:




object references an unsaved transient instance - save the transient instance before flushing




Code used to create a contact (It just calls JPARepository.save()):



contactsRepository.save(contact);


How to use merge and persist the data at the same time.










share|improve this question






















  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    7 hours ago










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    7 hours ago










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    7 hours ago










  • The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
    – Pavan Kumar
    6 hours ago

















up vote
0
down vote

favorite












I have a parent class Contact which has one to one relationship with ContactType.



@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I am trying to create a new contact using ContactRepository.save() which extends JPARepository. I am getting the following error.




Violation of PRIMARY KEY constraint type. Cannot insert duplicate key in object ContactType




If I change the contact type declaration to below:



@OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I get the following error:




object references an unsaved transient instance - save the transient instance before flushing




Code used to create a contact (It just calls JPARepository.save()):



contactsRepository.save(contact);


How to use merge and persist the data at the same time.










share|improve this question






















  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    7 hours ago










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    7 hours ago










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    7 hours ago










  • The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
    – Pavan Kumar
    6 hours ago















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a parent class Contact which has one to one relationship with ContactType.



@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I am trying to create a new contact using ContactRepository.save() which extends JPARepository. I am getting the following error.




Violation of PRIMARY KEY constraint type. Cannot insert duplicate key in object ContactType




If I change the contact type declaration to below:



@OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I get the following error:




object references an unsaved transient instance - save the transient instance before flushing




Code used to create a contact (It just calls JPARepository.save()):



contactsRepository.save(contact);


How to use merge and persist the data at the same time.










share|improve this question













I have a parent class Contact which has one to one relationship with ContactType.



@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I am trying to create a new contact using ContactRepository.save() which extends JPARepository. I am getting the following error.




Violation of PRIMARY KEY constraint type. Cannot insert duplicate key in object ContactType




If I change the contact type declaration to below:



@OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


I get the following error:




object references an unsaved transient instance - save the transient instance before flushing




Code used to create a contact (It just calls JPARepository.save()):



contactsRepository.save(contact);


How to use merge and persist the data at the same time.







java sql spring-boot sql-server-2012 spring-data-jpa






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 7 hours ago









Pavan Kumar

236




236












  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    7 hours ago










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    7 hours ago










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    7 hours ago










  • The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
    – Pavan Kumar
    6 hours ago




















  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    7 hours ago










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    7 hours ago










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    7 hours ago










  • The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
    – Pavan Kumar
    6 hours ago


















How many contact types are there? Please post the code for Contact Type?
– Michael Wiles
7 hours ago




How many contact types are there? Please post the code for Contact Type?
– Michael Wiles
7 hours ago












Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
– Pavan Kumar
7 hours ago




Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
– Pavan Kumar
7 hours ago












and what is the primary key? you mean as many rows as there there are Contacts?
– Michael Wiles
7 hours ago




and what is the primary key? you mean as many rows as there there are Contacts?
– Michael Wiles
7 hours ago












The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
– Pavan Kumar
6 hours ago






The primary Key is type string. It should insert a new row to Type table if the user enters new type Ex:"Type2" when creating a new contact. If the user enters already existing type then it should to insert a new row.
– Pavan Kumar
6 hours ago














2 Answers
2






active

oldest

votes

















up vote
0
down vote













Your comments mentioned:




The primary Key is type string. I want to insert a new row to type if
the user enters new type Ex:"Type2" when creating a new contact. If
the user enters already existing type then I dont want to insert a new
row.




This makes sense then why you're getting a Cannot insert duplicate key error.



The reality is there is not a one to one relationship between Contact and Contact Type as there is not one contact type for every contact. As you said, contact types are reused. What you should be doing is using a many to one between Contact and Contact Type as one contact can have only one Contact Type but one Contact Type can apply to more than one Contact. Iow, the same Contact Type can be one more than one Contact.



So you make it a many to one and then before you save you'll need to look up the Contact Type matching the given one and insert that one if it exists, if not, populate it and let the cascade save the new Contact Type.






share|improve this answer





















  • A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
    – Pavan Kumar
    6 hours ago


















up vote
0
down vote













Calling contactsRepository.save(contact) with:



@OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


raises exception because the persistence context cascades the persist operation and sees contactType as transient with primary key set, ready to be persisted. A row with the same PK already exists, hence the error.



The second case:



@OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "type")
private ContactType contactType;


The operation is persist (not merge) therefore not cascaded. The persistent context sees contactType as transient and cannot go further with the persist because one of the dependencies is in transient state.



Solution



Get rid of cascade:



@OneToOne
@JoinColumn(name = "type")
private ContactType contactType;


Before calling contactsRepository.save(contact); make sure the contactType is in managed state. You can do it this way:



contact.setContactType( entityManager.getReference(ContactType.class, contactType.getId()));


Make sure you replace getId() with the primary key getter.



Merging contactType into the persistence context with contact.setContactType(contactTypeRepository.merge(contactType)); is also valid.






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',
    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%2f53400732%2fnot-able-to-use-jpa-annotation-onetoonecascade-cascadetype-all%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








    up vote
    0
    down vote













    Your comments mentioned:




    The primary Key is type string. I want to insert a new row to type if
    the user enters new type Ex:"Type2" when creating a new contact. If
    the user enters already existing type then I dont want to insert a new
    row.




    This makes sense then why you're getting a Cannot insert duplicate key error.



    The reality is there is not a one to one relationship between Contact and Contact Type as there is not one contact type for every contact. As you said, contact types are reused. What you should be doing is using a many to one between Contact and Contact Type as one contact can have only one Contact Type but one Contact Type can apply to more than one Contact. Iow, the same Contact Type can be one more than one Contact.



    So you make it a many to one and then before you save you'll need to look up the Contact Type matching the given one and insert that one if it exists, if not, populate it and let the cascade save the new Contact Type.






    share|improve this answer





















    • A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
      – Pavan Kumar
      6 hours ago















    up vote
    0
    down vote













    Your comments mentioned:




    The primary Key is type string. I want to insert a new row to type if
    the user enters new type Ex:"Type2" when creating a new contact. If
    the user enters already existing type then I dont want to insert a new
    row.




    This makes sense then why you're getting a Cannot insert duplicate key error.



    The reality is there is not a one to one relationship between Contact and Contact Type as there is not one contact type for every contact. As you said, contact types are reused. What you should be doing is using a many to one between Contact and Contact Type as one contact can have only one Contact Type but one Contact Type can apply to more than one Contact. Iow, the same Contact Type can be one more than one Contact.



    So you make it a many to one and then before you save you'll need to look up the Contact Type matching the given one and insert that one if it exists, if not, populate it and let the cascade save the new Contact Type.






    share|improve this answer





















    • A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
      – Pavan Kumar
      6 hours ago













    up vote
    0
    down vote










    up vote
    0
    down vote









    Your comments mentioned:




    The primary Key is type string. I want to insert a new row to type if
    the user enters new type Ex:"Type2" when creating a new contact. If
    the user enters already existing type then I dont want to insert a new
    row.




    This makes sense then why you're getting a Cannot insert duplicate key error.



    The reality is there is not a one to one relationship between Contact and Contact Type as there is not one contact type for every contact. As you said, contact types are reused. What you should be doing is using a many to one between Contact and Contact Type as one contact can have only one Contact Type but one Contact Type can apply to more than one Contact. Iow, the same Contact Type can be one more than one Contact.



    So you make it a many to one and then before you save you'll need to look up the Contact Type matching the given one and insert that one if it exists, if not, populate it and let the cascade save the new Contact Type.






    share|improve this answer












    Your comments mentioned:




    The primary Key is type string. I want to insert a new row to type if
    the user enters new type Ex:"Type2" when creating a new contact. If
    the user enters already existing type then I dont want to insert a new
    row.




    This makes sense then why you're getting a Cannot insert duplicate key error.



    The reality is there is not a one to one relationship between Contact and Contact Type as there is not one contact type for every contact. As you said, contact types are reused. What you should be doing is using a many to one between Contact and Contact Type as one contact can have only one Contact Type but one Contact Type can apply to more than one Contact. Iow, the same Contact Type can be one more than one Contact.



    So you make it a many to one and then before you save you'll need to look up the Contact Type matching the given one and insert that one if it exists, if not, populate it and let the cascade save the new Contact Type.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 6 hours ago









    Michael Wiles

    14.5k165692




    14.5k165692












    • A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
      – Pavan Kumar
      6 hours ago


















    • A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
      – Pavan Kumar
      6 hours ago
















    A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
    – Pavan Kumar
    6 hours ago




    A given contact can have only one type. It cant have multiple values associated to it. For example: Type table has 2 rows type1 and type2. Contact1 can have only one of these either type1 or type2. If the user enters type3 then it should create a new row type3.
    – Pavan Kumar
    6 hours ago












    up vote
    0
    down vote













    Calling contactsRepository.save(contact) with:



    @OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "type")
    private ContactType contactType;


    raises exception because the persistence context cascades the persist operation and sees contactType as transient with primary key set, ready to be persisted. A row with the same PK already exists, hence the error.



    The second case:



    @OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
    @JoinColumn(name = "type")
    private ContactType contactType;


    The operation is persist (not merge) therefore not cascaded. The persistent context sees contactType as transient and cannot go further with the persist because one of the dependencies is in transient state.



    Solution



    Get rid of cascade:



    @OneToOne
    @JoinColumn(name = "type")
    private ContactType contactType;


    Before calling contactsRepository.save(contact); make sure the contactType is in managed state. You can do it this way:



    contact.setContactType( entityManager.getReference(ContactType.class, contactType.getId()));


    Make sure you replace getId() with the primary key getter.



    Merging contactType into the persistence context with contact.setContactType(contactTypeRepository.merge(contactType)); is also valid.






    share|improve this answer



























      up vote
      0
      down vote













      Calling contactsRepository.save(contact) with:



      @OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
      @JoinColumn(name = "type")
      private ContactType contactType;


      raises exception because the persistence context cascades the persist operation and sees contactType as transient with primary key set, ready to be persisted. A row with the same PK already exists, hence the error.



      The second case:



      @OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
      @JoinColumn(name = "type")
      private ContactType contactType;


      The operation is persist (not merge) therefore not cascaded. The persistent context sees contactType as transient and cannot go further with the persist because one of the dependencies is in transient state.



      Solution



      Get rid of cascade:



      @OneToOne
      @JoinColumn(name = "type")
      private ContactType contactType;


      Before calling contactsRepository.save(contact); make sure the contactType is in managed state. You can do it this way:



      contact.setContactType( entityManager.getReference(ContactType.class, contactType.getId()));


      Make sure you replace getId() with the primary key getter.



      Merging contactType into the persistence context with contact.setContactType(contactTypeRepository.merge(contactType)); is also valid.






      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        Calling contactsRepository.save(contact) with:



        @OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
        @JoinColumn(name = "type")
        private ContactType contactType;


        raises exception because the persistence context cascades the persist operation and sees contactType as transient with primary key set, ready to be persisted. A row with the same PK already exists, hence the error.



        The second case:



        @OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
        @JoinColumn(name = "type")
        private ContactType contactType;


        The operation is persist (not merge) therefore not cascaded. The persistent context sees contactType as transient and cannot go further with the persist because one of the dependencies is in transient state.



        Solution



        Get rid of cascade:



        @OneToOne
        @JoinColumn(name = "type")
        private ContactType contactType;


        Before calling contactsRepository.save(contact); make sure the contactType is in managed state. You can do it this way:



        contact.setContactType( entityManager.getReference(ContactType.class, contactType.getId()));


        Make sure you replace getId() with the primary key getter.



        Merging contactType into the persistence context with contact.setContactType(contactTypeRepository.merge(contactType)); is also valid.






        share|improve this answer














        Calling contactsRepository.save(contact) with:



        @OneToOne(cascade=CascadeType.ALL, orphanRemoval = true)
        @JoinColumn(name = "type")
        private ContactType contactType;


        raises exception because the persistence context cascades the persist operation and sees contactType as transient with primary key set, ready to be persisted. A row with the same PK already exists, hence the error.



        The second case:



        @OneToOne(cascade=CascadeType.MERGE, orphanRemoval = true)
        @JoinColumn(name = "type")
        private ContactType contactType;


        The operation is persist (not merge) therefore not cascaded. The persistent context sees contactType as transient and cannot go further with the persist because one of the dependencies is in transient state.



        Solution



        Get rid of cascade:



        @OneToOne
        @JoinColumn(name = "type")
        private ContactType contactType;


        Before calling contactsRepository.save(contact); make sure the contactType is in managed state. You can do it this way:



        contact.setContactType( entityManager.getReference(ContactType.class, contactType.getId()));


        Make sure you replace getId() with the primary key getter.



        Merging contactType into the persistence context with contact.setContactType(contactTypeRepository.merge(contactType)); is also valid.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 6 hours ago

























        answered 6 hours ago









        Eugen Covaci

        3496




        3496






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53400732%2fnot-able-to-use-jpa-annotation-onetoonecascade-cascadetype-all%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







            Popular posts from this blog

            Berounka

            Sphinx de Gizeh

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...