In the database there is a table having a reflexive one-to-many relationship :
create table structure
(
struct_code varchar2(15) not null,
str_struct_code varchar2(15),
struct_lib varchar2(255),
struct_sigle varchar2(10),
struct_comment clob,
struct_interne smallint default 1,
constraint pk_structure primary key (struct_code)
);
alter table structure add constraint fk_structur_associati_structur foreign key (str_struct_code) references structure (struct_code);
I created the corresponding model :
#Entity
#Table(name = "structure")
public class Structure {
#Id()
#Column(name="struct_code")
private String code;
#Column(name="struct_sigle")
private String sigle;
#Column(name="struct_lib")
private String lib;
#Column(name="struct_interne")
private Integer interne;
#ManyToOne
#JoinColumn(name = "struct_code")
private Structure sousStructure;
public Structure() {
super();
}
public Structure(String code) {
super();
}
// getters and setters
}
But when I built the project then I got the error : mappingexception repeated column in mapping for entity : com.ambre.pta.model.Structure column: struct_code (should be mapped with insert="false" update="false")
So how to write correctly the reflexive relation ?
I do have something like this in place:
#ManyToOne
#JoinColumn(name = "parent_struct_code", nullable = true)
private Structure parentStructure;
#OneToMany(mappedBy = "parentStructure", cascade = CascadeType.REMOVE, fetch=FetchType.LAZY)
private List<Structure> sousStructures = new ArrayList<>();
Related
I have three tables
CREATE TABLE "ingredient" (
"id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
"ingredient" VARCHAR(50) NOT NULL
);
CREATE TABLE "pizza" (
"id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
"pizza" VARCHAR(50) NOT NULL
);
CREATE TABLE "pizza_structure" (
"pizza_id" INT NOT NULL,
"ingredient_id" INT NOT NULL,
"amount" INT NOT NULL
);
how to join them, to get Pizzas structure as a Map
#Entity
#Table(name = "ingredient")
public class Ingredient{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Ingredient() {
}
}
#Entity
#Table(name = "pizza")
public class Pizza {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany ????
private Map<Ingredient, Integer> pizzaStructure;
public Pizza() {
}
public Pizza(String name, Map<Long, Integer> pizzaStructure) {
this.name = name;
this.pizzaStructure = pizzaStructure;
}
}
do I need to create #Embeddable class PizzaStructure, if yes when how to use it?
now I'm getting an error
Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class:
how to join them, to get Pizzas structure as a Map
It seems to look like this:
#ElementCollection
#CollectionTable(name = "pizza_structure", joinColumns = {#JoinColumn(name = "pizza_id")})
#Column(name = "amount")
#MapKeyJoinColumn(name = "ingredient_id")
private Map<Ingredient, Integer> pizzaStructure;
do I need to create #Embeddable class PizzaStructure
No.
More info is here: Hibernate User Guide - Maps.
Note that table pizza_structure should have foreign keys to pizza and ingredient tables and also unique constrain of pizza_id and ingredient_id, like this (it's postgresql dialect):
create table pizza_structure
(
pizza_id ... constraint fk_structure_pizza references pizza,
ingredient_id ... constraint fk_structure_ingredient references ingredient,
amount ...,
constraint pizza_structure_pkey primary key (pizza_id, ingredient_id)
);
You have a manyToMany relationship between pizza and ingredient and an additional column in your relationship.
I found a similar question here: JPA 2.0 many-to-many with extra column
(I would comment, but i do not have enough reputation.)
Unable to find column with logical name: VERTICAL_MARKET_ID in org.hibernate.mapping.Table(bck_vertical_market) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:582)
Can anyone help with this fail? None of existing posts help me. My classes which uses VerticalMarket looks like:
#Entity
#Table(name = "BCK_VERTICAL_MARKET")
public class VerticalMarketEntity implements Serializable {
private VerticalMarketID verticalMarketId;
private String name;
public VerticalMarketEntity() {
}
public VerticalMarketEntity(VerticalMarketID verticalMarketId) {
if (Assert.CHECK)
Assert.notNull(verticalMarketId, "Parameter for id must be set");
this.verticalMarketId = verticalMarketId;
}
#EmbeddedId
#AttributeOverride(name = "verticalMarketId", column = #Column(name = "VERTICAL_MARKET_ID", nullable = false, length = 100))
#Attribute(index = 0, primaryKey = true)
public VerticalMarketID getVerticalMarketId() {
return verticalMarketId;
}
#Attribute(index = 1, type = String100TD.class)
#Column(name = "NAME", length = 100)
#Basic
public String getName() {
return name;
}
}
#Entity
#Table(name = "BCK_CERTIFICATE")
public class CertificateEntity {
private VerticalMarketEntity verticalMarket;
#Relation(index = 2, target = VerticalMarketEntity.class)
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "VERTICAL_MARKET", referencedColumnName = "VERTICAL_MARKET_ID")
public VerticalMarketEntity getVerticalMarket() {
return verticalMarket;
}
#Entity
#Table(name = "BCK_OFFERED_SERVICE")
public class OfferedServiceEntity implements Serializable {
private VerticalMarketEntity verticalMarket;
#Relation(index = 2, target = VerticalMarketEntity.class)
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "VERTICAL_MARKET", referencedColumnName = "VERTICAL_MARKET_ID")
public VerticalMarketEntity getVerticalMarket() {
return verticalMarket;
}
}
CREATE TABLEBCK_VERTICAL_MARKET (
VERTICAL_MARKET_ID CHAR(36) NOT NULL,
NAME VARCHAR2(100 CHAR) NOT NULL
)
ALTER TABLE BCK_VERTICAL_MARKET ADD CONSTRAINT PK_VERTICAL_MARKET PRIMARY KEY (VERTICAL_MARKET_ID);
CREATE TABLEBCK_CERTIFICATE (
CERTIFICATE_ID CHAR(36) NOT NULL,
IS_OTHER NUMBER(1) NOT NULL,
VERTICAL_MARKET CHAR(36) NOT NULL,
NAME VARCHAR2(100 CHAR) NOT NULL
);
ALTER TABLE BCK_CERTIFICATE ADD CONSTRAINT PK_CERTIFICATE PRIMARY KEY (CERTIFICATE_ID);
ALTER TABLE BCK_CERTIFICATE ADD CONSTRAINT FK__C_VERTICAL_MARKET_ID
FOREIGN KEY (VERTICAL_MARKET) REFERENCES BCK_VERTICAL_MARKET (VERTICAL_MARKET_ID);
CREATE TABLE BCK_OFFERED_SERVICE (
OFFERED_SERVICE_ID CHAR(36) NOT NULL,
VERTICAL_MARKET CHAR(36) NOT NULL,
OFFERED_SERVICE_TYPE CHAR(36)
) ;
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT PK_OFFERED_SERVICES PRIMARY KEY (OFFERED_SERVICE_ID);
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT FK___O_S_VERTICAL_MARKET_ID
FOREIGN KEY (VERTICAL_MARKET) REFERENCES BCK_VERTICAL_MARKET (VERTICAL_MARKET_ID);
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT FK___O_S_T_ID
FOREIGN KEY (OFFERED_SERVICE_TYPE) REFERENCES BCK_OFFERED_SERVICE_TYPE (OFFERED_SERVICE_TYPE_ID);
I have this Parent class
#Entity
#Table(name = "category")
#NamedQuery(name = "category.findAll", query = "SELECT c FROM Category c")
public class Category implements Serializable {
public Category(){}
#Column(name = "name", nullable = false)
#Id
private String name;
#Column(name = "col2")
private Boolean col2;
}
And i have referenced the parent table in child table as follows:
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "cat_name")
private Category category
when i run this JPQL query
update Category c SET c.name=:newName ,c.termsCanHaveChildren=:canHaveChdrn where c.name=:oldName
it's return with foreign key constraint error while i have put Cascade All in child field
Cannot delete or update a parent row: a foreign key constraint fails (`terms`.`term`, CONSTRAINT `FKaykenypxci167nqioh4xx9p3a` FOREIGN KEY (`cat_name`) REFERENCES `category` (`name`))
The problem lays at the constraint being generated by your persistence provider (hibernate), for the #JoinColumn(name = "cat_name") at the child table (and not with the CascadeType that you're defining)...
The generated constraint should indicated that when the PK of Category is Updated, any reference to such column should be updated also...
I believe this configuration should work (but you need to test it first, because I always generated my database model using scripts and not using hibernate features):
#ManyToOne
#JoinColumn(
name = "cat_name",
foreignKey = #ForeingKey(
name = "fk_child_category",
foreignKeyDefinition = "FOREIGN KEY (cat_name) REFERENCES category ON UPDATE CASCADE"
)
)
private Category category;
Also you need to check if your database supports "ON UPDATE CASCADE"... According to this link, oracle does not... (What database are you using?)
If this does not work, try the suggestion of Michelle...
That's expected: you are changing the Primary Key (#Id), that's used in a Foreign Key (#JoinColumn).
Use a surrogated immutable primary key.
This question has been asked in many forms here but none of the solutions seem to work for me. I'm trying to delete the parent entity and I want all of the child entities to also be deleted.
My entities:
#Entity
#Table(name = "item", catalog = "myshchema")
public class Item implements java.io.Serializable {
#JoinColumn(name = "item_id", insertable = false, updatable = false, nullable = false)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ItemCategory> categories;
/* Getters and Setters and other fields*/
}
Table for Item:
CREATE TABLE `item` (
`item_id` int(11) NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
PRIMARY KEY (`item_id`),
UNIQUE KEY `item_id_UNIQUE` (`item_id`),
KEY `FK_ITEM_STORE_ID_idx` (`store_id`),
CONSTRAINT `FK_ITEM_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `store` (`store_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8;
And my other entity
#Entity
#Table(name = "item_category", catalog = "myschema")
#IdClass(ItemCategoryIndex.class)
public class ItemCategory implements java.io.Serializable {
#Id
#Column(name = "category_id", unique = true, nullable = false, insertable = false, updatable = false)
private Integer categoryId;
#Id
private Store store;
#Id
private Item item;
#Id
private String categoryName;
/* Getters and Setters */
}
Table for ItemCategory:
CREATE TABLE `item_category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`category_name` varchar(45) NOT NULL,
PRIMARY KEY (`category_id`),
UNIQUE KEY `category_id_UNIQUE` (`category_id`),
UNIQUE KEY `IDX_UNIQUE_STORE_CATEGORY` (`store_id`,`item_id`,`category_name`) USING BTREE,
KEY `FK_CATEGORY_STORE_ID_idx` (`store_id`),
KEY `FK_ITEM_CATEGORY_ID_idx` (`item_id`),
CONSTRAINT `FK_CATEGORY_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `store` (`store_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_ITEM_CATEGORY_ID` FOREIGN KEY (`item_id`) REFERENCES `item` (`item_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=162 DEFAULT CHARSET=utf8;
I try to delete the item like this:
Item item = entityManager.find(Item.class, idList.get(i));
entityManager.remove(item);
My logs show that Hibernate is trying to set the primary key for ItemCategory to null:
Hibernate: update myschema.item_category set item_id=null where item_id=?
ERROR o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions 146 - Column 'item_id' cannot be null
I even tried looping through the child records and deleting them manually, but Hibernate still issues this update to null query. What am I doing wrong?
I have to break your problem down to two parts
First - let's talk about your database schema design.
According to your schema, item and item_category has a one-to-many relationship meaning an item can have/be-assigned-to different categories but different items cannot have/be-assigned-to the same category.
That is totally fine if it is indeed your business requirement, I mention it because it does not make sense to me and this circumstance rarely happens.
If what you want is that a category can have multiple items and vice versa, itemand item_category must be a many-to-many relationship. There should be a join table additionally.
Second - let's say the schema don't change
ItemCategory is the owner of the relationship because it has a foreign key item_id refering to item table. So the ItemCategoy should look roughly like this:
#Entity
#Table(name = "item_category")
public class ItemCategory {
#Id
private Integer categoryId;
private Store store;
#ManyToOne
#JoinColumn(name="item_id", /*cascade = ...*/)
private Item item;
private String categoryName;
/* Getters and Setters */
}
Your Item entity will be roughly like this:
#Entity
#Table(name = "item", catalog = "myshchema")
public class Item implements java.io.Serializable {
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy="item")
private Set<ItemCategory> categories; //`mappedBy`used here because this entity is not the owner of the relationship according to what mentioned above
/* Getters and Setters and other fields*/
}
To remove all the child entities(ItemCategory) from Item , simply
em.remove(item);
The orphanRemoval is true, deleting the parent, the children will be deleted as well.
In Hibernate, you need to decide who is owning the relationship. If you have the parent side (ItemCategory) owning the relationship, you will find insertion/deletion of Item+ ItemCategory will involve update of item_id in ItemCategory table (which is what I observed from your exception). In most case it is not preferable. We usually let the children own the relationship. This is done by using mappedBy
(pseudo-code)
class Item {
//...
#OneToMany(mappedBy = "item", cascade=ALL, orphanRemoval=true)
private Set<ItemCategory> categories;
}
class ItemCategory {
//...
#ManyToOne
#JoinColumn(name="item_id")
Item item;
}
The trick here is mappedBy
I am try persist in database this entity:
#Entity
#Table(name="pessoa_juridica")
public class PessoaJuridica {
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="cnpj")
#Order(value=1)
private String cnpj;
#Column(name="razao_social")
#Order(value=2)
private String razaoSocial;
#OneToOne( fetch = FetchType.EAGER, cascade = {CascadeType.ALL} )
#Order(value=3)
#JoinColumn(name="contato")
private Contato contato;
}
but when I open the view with the form, I get this error:
org.springframework.beans.NullValueInNestedPathException: Invalid property 'pessoaJuridica.contato' of bean class [com.spring.loja.model.cliente.persistence.model.Cliente]: Could not instantiate property type [java.lang.Integer] to auto-grow nested property path:
java.lang.InstantiationException:
java.lang.Integerorg.springframework.beans.BeanWrapperImpl.newValue(BeanWrapperImpl.java:651)
org.springframework.beans.BeanWrapperImpl.createDefaultPropertyValue(BeanWrapperImpl.java:620)
org.springframework.beans.BeanWrapperImpl.setDefaultValue(BeanWrapperImpl.java:609)
org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:574)
org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:548)
org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:549)
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:714)
org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99)
org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:229)
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_form_005flabel_005f13(fields_jsp.java:2969)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fwhen_005f17(fields_jsp.java:2836)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fchoose_005f3(fields_jsp.java:2583)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fforEach_005f4(fields_jsp.java:2539)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fwhen_005f14(fields_jsp.java:2444)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fchoose_005f0(fields_jsp.java:242)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspx_meth_c_005fforEach_005f0(fields_jsp.java:150)org.apache.jsp.WEB_002dINF.jsp.common.fields_jsp._jspService(fields_jsp.java:115)org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954)org.apache.jsp.WEB_002dINF.jsp.private_.cadastrar_jsp._jspx_meth_form_005fform_005f0(cadastrar_jsp.java:166)org.apache.jsp.WEB_002dINF.jsp.private_.cadastrar_jsp._jspService(cadastrar_jsp.java:88)org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1217)org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)javax.servlet.http.HttpServlet.service(HttpServlet.java:621)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
the setter/getter methods for Contato are:
public Integer getContato() {
return contato.getId();
}
public void setContato(Integer id) {
this.contato = new Contato(id);
}
the class Contatois this:
#Entity
#Table(name="contato")
public class Contato {
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name="nome", unique=true)
#Order(value=1)
private String nome;
#Column(name="email")
#Order(value=2)
private String email;
#Column(name="telefone")
#Order(value=3)
private String telefone;
public Contato() {
this.id = null;
this.nome = null;
this.email = null;
this.telefone = null;
}
public Contato(Integer id) {
this.id = id;
}
}
If I try this for the setter/getter method:
public Contato getContato() {
return contato;
}
public void setContato(Contato contato) {
this.contato = contato;
}
the view is opened, but when I try submit the form, I get the error:
org.hibernate.PersistentObjectException: detached entity passed to persist: com.spring.loja.model.contato.persistence.model.Contatoorg.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:314)org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:314)org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)com.spring.loja.config.generic.persistence.Dao.persist(Dao.java:32)com.spring.loja.config.generic.persistence.Dao$$FastClassBySpringCGLIB$$ddbbe880.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)com.spring.loja.model.cliente.persistence.ClienteHome$$EnhancerBySpringCGLIB$$83cbd101.persist(<generated>)com.spring.loja.config.generic.service.service.cadastra(service.java:45)com.spring.loja.config.generic.service.service$$FastClassBySpringCGLIB$$c92a3159.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)com.spring.loja.model.cliente.service.ClienteService$$EnhancerBySpringCGLIB$$71ccd54c.cadastra(<generated>)com.spring.loja.config.generic.controller.controller.cadastra(controller.java:42)com.spring.loja.config.generic.controller.controller$$FastClassBySpringCGLIB$$c8cc444b.invoke(<generated>)org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)com.spring.loja.model.cliente.controller.ClienteController$$EnhancerBySpringCGLIB$$ffe13d4e_2.cadastra(<generated>)sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)java.lang.reflect.Method.invoke(Method.java:606)org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)javax.servlet.http.HttpServlet.service(HttpServlet.java:647)org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)javax.servlet.http.HttpServlet.service(HttpServlet.java:728)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
anyone knows the right way to persist the entity?
UPDATE
the field contato is mapped on the view as this:
<form:label path="pessoaJuridica.contato.id" class="label label-default">contato</form:label>
<form:select path="pessoaJuridica.contato.id" class="form-control select embed" data-lista="${url}" data-altera="${altera}" data-remove="${remove}"/>
UPDATE 2
In database, this is the how tables are created:
CREATE TABLE pessoa_juridica
(
id serial NOT NULL,
cnpj character varying(255),
razao_social character varying(255),
contato integer,
CONSTRAINT pessoa_juridica_pkey PRIMARY KEY (id),
CONSTRAINT fk_eaa4oxajsuofatiyag213dio9 FOREIGN KEY (contato)
REFERENCES contato (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE pessoa_juridica
OWNER TO klebermo;
CREATE TABLE contato
(
id serial NOT NULL,
email character varying(255),
nome character varying(255),
telefone character varying(255),
CONSTRAINT contato_pkey PRIMARY KEY (id),
CONSTRAINT uk_rrtn7wgfxo0jfwkhby23f72cn UNIQUE (nome)
)
WITH (
OIDS=FALSE
);
ALTER TABLE contato
OWNER TO klebermo;
As I remember, the join column name is not the name of the object you are joining to, but the name of the column on the object you are joining to.
You told JPA to cascade all! and passed detached object to save, that is an issue.
According to Hibernate.
CascadeType.PERSIST: cascades the persist (create) operation to
associated entities persist() is called or if the entity is managed
You said #OneToOne( fetch = FetchType.EAGER, cascade = {CascadeType.ALL} ) means it will apply all Transitive persistence.
So removing cascade = {CascadeType.ALL} will solve the prob.
#OneToOne( fetch = FetchType.EAGER)
#Order(value=3)
#JoinColumn(name="contato")
private Contato contato;