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












0














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
    Nov 20 at 20:19










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    Nov 20 at 20:24










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    Nov 20 at 20:28










  • 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
    Nov 20 at 20:37


















0














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
    Nov 20 at 20:19










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    Nov 20 at 20:24










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    Nov 20 at 20:28










  • 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
    Nov 20 at 20:37
















0












0








0







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 Nov 20 at 20:05









Pavan Kumar

197




197












  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    Nov 20 at 20:19










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    Nov 20 at 20:24










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    Nov 20 at 20:28










  • 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
    Nov 20 at 20:37




















  • How many contact types are there? Please post the code for Contact Type?
    – Michael Wiles
    Nov 20 at 20:19










  • Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
    – Pavan Kumar
    Nov 20 at 20:24










  • and what is the primary key? you mean as many rows as there there are Contacts?
    – Michael Wiles
    Nov 20 at 20:28










  • 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
    Nov 20 at 20:37


















How many contact types are there? Please post the code for Contact Type?
– Michael Wiles
Nov 20 at 20:19




How many contact types are there? Please post the code for Contact Type?
– Michael Wiles
Nov 20 at 20:19












Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
– Pavan Kumar
Nov 20 at 20:24




Contact Type is just a simple class which points to Type table. It can have as many row values as being inserted.
– Pavan Kumar
Nov 20 at 20:24












and what is the primary key? you mean as many rows as there there are Contacts?
– Michael Wiles
Nov 20 at 20:28




and what is the primary key? you mean as many rows as there there are Contacts?
– Michael Wiles
Nov 20 at 20:28












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
Nov 20 at 20:37






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
Nov 20 at 20:37














2 Answers
2






active

oldest

votes


















0














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
    Nov 20 at 20:51



















0














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























  • I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
    – Pavan Kumar
    Nov 27 at 20:02













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









0














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
    Nov 20 at 20:51
















0














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
    Nov 20 at 20:51














0












0








0






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 Nov 20 at 20:44









Michael Wiles

14.6k165692




14.6k165692












  • 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
    Nov 20 at 20:51


















  • 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
    Nov 20 at 20:51
















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
Nov 20 at 20:51




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
Nov 20 at 20:51













0














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























  • I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
    – Pavan Kumar
    Nov 27 at 20:02


















0














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























  • I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
    – Pavan Kumar
    Nov 27 at 20:02
















0












0








0






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 Nov 20 at 21:02

























answered Nov 20 at 20:56









Eugen Covaci

1,24527




1,24527












  • I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
    – Pavan Kumar
    Nov 27 at 20:02




















  • I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
    – Pavan Kumar
    Nov 27 at 20:02


















I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
– Pavan Kumar
Nov 27 at 20:02






I am able to add the row but the foreign key id in the child table (Contc_id) is entered as Null. Its not inputting the newly generated contact ID.
– Pavan Kumar
Nov 27 at 20:02




















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.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • 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%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

To store a contact into the json file from server.js file using a class in NodeJS

Redirect URL with Chrome Remote Debugging Android Devices

Dieringhausen