Hibernate One to many Mapping Error - spring

I'm going to develop hospital management system.in that there is a mapping like below.
doctor can select tablets[selectedTablets] ---> they inserted to Eprescriber form and saved as a record.at begin there is these fields. patient Name & SelectedTablets for him
But when i'm going to develop its gives me a below error.i refer Mkyong Tutorials for my hibernate part.
please help me to sort out this issue.
here is my bean classes. is there any issue with my mappings with my business logic
#Entity
#Table(name = "E_PRESCRIBER")
public class EPrescriber implements Serializable {
private static final long serialVersionUID = 440529869955257543L;
public EPrescriber() {
super();
}
public EPrescriber(int ePrescriberid, List<SelectedTablets> selectedTablets) {
this.ePrescriberid = ePrescriberid;
this.selectedTablets = selectedTablets;
}
#Id
#Column(name = "ePrescriberid" ,unique = true, nullable = false)
#SequenceGenerator(name = "ePrescriber_seq", sequenceName = "ePrescriber_id_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ePrescriber_seq")
private int ePrescriberid;
public int getePrescriberid() {
return ePrescriberid;
}
public void setePrescriberid(int ePrescriberid) {
this.ePrescriberid = ePrescriberid;
}
#Column private String patientName;
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
#OneToMany(fetch = FetchType.LAZY,targetEntity=SelectedTablets.class, mappedBy = "ePrescriberid")
private List<SelectedTablets> selectedTablets=new ArrayList<SelectedTablets>();
public List<SelectedTablets> getSelectedTablets() {
return selectedTablets;
}
public void setSelectedTablets(List<SelectedTablets> selectedTablets) {
this.selectedTablets = selectedTablets;
}
}
another bean class here
#Entity
#Table(name = "SelectedTablets")
public class SelectedTablets implements Serializable {
private static final long serialVersionUID = 4854785134773287611L;
public SelectedTablets() {
}
#Id
#Column(name = "id", unique = true, nullable = false)
#SequenceGenerator(name = "selectedTablets_seq", sequenceName = "selectedTablets_id_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "selectedTablets_seq")
private int id;
#Column private Tablets tablets;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ePrescriberid", nullable = true)
private EPrescriber ePrescriberid;
public EPrescriber getePrescriberid() {
return ePrescriberid;
}
public void setePrescriberid(EPrescriber ePrescriberid) {
this.ePrescriberid = ePrescriberid;
}
public Tablets getTablets() {
return tablets;
}
public void setTablets(Tablets tablets) {
this.tablets = tablets;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
here is the DAO class method. seems here is my issue. ? ? ?
#Repository
#Transactional
public class EPrescriberDAO {
#Autowired
private SessionFactory sessionFactory;
public void getTabletbyNameAndSave(String []selectedMedicines) {
EPrescriber ePrescriber=new EPrescriber();
List<SelectedTablets> selectedTabletsList=new ArrayList<SelectedTablets>();
for (String item : selectedMedicines) {
Tablets tablets=null;
String hql="from Tablets t where t.category='"+item.trim()+"' ";
Query queryList = sessionFactory.getCurrentSession().createQuery(hql);
tablets=(Tablets)queryList.uniqueResult();
SelectedTablets selectedTablets=new SelectedTablets();
selectedTablets.setTablets(tablets);
selectedTablets.setePrescriberid(ePrescriber);
selectedTabletsList.add(selectedTablets);
sessionFactory.getCurrentSession().save(selectedTablets);
}
ePrescriber.setPatientName("Ranil");
ePrescriber.setSelectedTablets(selectedTabletsList);
sessionFactory.getCurrentSession().save(ePrescriber);
}
}
if fault with my DAO, then please advice me too for correct those faults
-thanks
error log
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.priyan.patients.EPrescriber
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:242)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:430)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:265)
at org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:619)
at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3141)
at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:501)
at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:227)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:150)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1142)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:835)
at com.priyan.patients.EPrescriberDAO.getTabletbyNameAndSave(EPrescriberDAO.java:25)
at com.priyan.patients.EPrescriberDAO$$FastClassByCGLIB$$59da35c6.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621)
at com.priyan.patients.EPrescriberDAO$$EnhancerByCGLIB$$bb3659b.getTabletbyNameAndSave(<generated>)
at com.priyan.patients.ContactsControllers.setTabletsNames(ContactsControllers.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760)
at java.lang.Thread.run(Unknown Source)

#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinColumn(name = "ePrescriberid", nullable = true)
private EPrescriber ePrescriberid;
SelectedTablets.java edited as above.now my issue sorted & thanks 4 all

Related

Spring Data Cassandra Not handling raw UDTS, throws no suitable converter exception

After upgrading to Spring 2.4.0 , spring data Cassandra is throwing no suitable converter found exception
Here is my UDT
#Setter
#Getter
#ToString
#NoArgsConstructor
#UserDefinedType(value="ADDRESS")
#AllArgsConstructor
public class Address implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String address1;
private String address2;
private String state;
private String city;
private String country;
private String zip;
private String longitude;
private String latitude;
}
Here is my main table
package com.sellingsimplified.msor.common.schema;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.constraints.NotEmpty;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.CassandraType.Name;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Getter
#Setter
#ToString
#Table(value = "#{#contactCassandra}")
#Document(indexName = "#{#contactIndex}")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Contact implements Serializable,MSOREntity {
/**
*
*/
private static final long serialVersionUID = 5141439096729821675L;
#PrimaryKey
#Id
private Long contactid;// 1
private Long companyid;// 1
#CassandraType(type =Name.UDT, userTypeName = "NAME")
#Field(type = FieldType.Auto, includeInParent = true)
private com.sellingsimplified.msor.common.schema.Name contactname;// 1
#javax.validation.constraints.Email
private String corpemail;// 1
#CassandraType(type = Name.UDT, userTypeName = "EMAIL")
#Field(type = FieldType.Auto, includeInParent = true)
private Email contactemail;// 1
#NotEmpty(message="Jobtitle cannot be empty")
private String jobtitle;
private String skill;// newly added field
#CassandraType(type =Name.UDT, userTypeName = "ADDRESS")
#Field(type = FieldType.Auto, includeInParent = true)
#Column("contactaddress")
private Address contactaddress;
#CassandraType(type = Name.UDT, userTypeName = "PHONE")
#Field(type = FieldType.Auto, includeInParent = true)
private Phone contactphone;
private String companyname;
/**
* linkedinurl, facebookurl, twitterurl, xing_url, viadeo_url, misc_url
*/
private Map<String, String> contactsocialurl;
private String twitterhandle;
private String jobfunction;
private String createdby;
private String modifiedby;
private Date createdon;
private Date modifiedon;
private String updatedby;
private Date updatedon;
private String status;
private String contactverificationstatus;
private String copyaddress;
private String contactverified;
private String emailverified;
private String phonenumberverified;
private String senioritylevel;
private String contactsource;
private String lastmodifiedsystem;
private String domain;
private String comment;
private String processstatus;
private String enrichmentstage;
private String thresholdstatus;
private String incomingemailtype;
private String pageaccessedby;
private String groupid;
private String emailpattern;
private String emailcheck;
private String websitedomain;
private String humanhelp;
private String notVerifiedreason;
private String notVerifiedcomment;
private String zone;
private String companycheck;
private String industry;
private String employeetotal;
#CassandraType(type =Name.UDT, userTypeName = "NAME")
#Field(type = FieldType.Object, includeInParent = true)
private com.sellingsimplified.msor.common.schema.Name contactnamenl;
private String jobtitlenl;
#CassandraType(type = Name.UDT, userTypeName = "ADDRESS")
#Field(type = FieldType.Auto, includeInParent = true)
private Address contactaddressnl;
private String contacthash;
private String sourceurl;
#CassandraType(type = Name.UDT, userTypeName = "COMPANY")
#Field(type = FieldType.Auto, includeInParent = true)
private Company contactcompany;
private Long tokenid = -1L;
// new fields
private Map<String, String> customfields;
private Map<String, String> flags;
private Set<String> usertags;
private Set<String> systemtags;
private String user;
private String chromeuser;
private String experience;
private String notes;
#CassandraType(type = Name.UDT, userTypeName = "JobHistory")
#Field(type = FieldType.Auto, includeInParent = true)
private List<JobHistory> jobhistory;
private List<EmailHistory> emailhistory;
private String contactidtxt;
private Date lastaccessedate;
private Date ecmverifiedon;
private Date verifiedon;
private String isactive;
private String isverified;
private String isarchived;
private String isdeleted;
private Set<Long> mergedcontactids;
private String emaildomain;
private String contactotherfield1;
private String contactotherfield2;
private String contactotherfield3;
private String contactotherfield4;
private String contactotherfield5;
private String contactotherfield6;
private String contactotherfield7;
private String contactotherfield8;
private String contactotherfield9;
private String contactotherfield10;
private String linkedinurl;
private String facebookurl;
private String twitterurl;
private String miscurl;
private String linkedinhandle;
private String facebookhandle;
private String xinghandle;
private String viadeolinkhandle;
private String srcemail;
// new fields
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contacthash == null) ? 0 : contacthash.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contact other = (Contact) obj;
if (contacthash == null) {
if (other.contacthash != null)
return false;
} else if (!contacthash.equals(other.contacthash))
return false;
return true;
}
#Override
public EntityType entityType() {
// TODO Auto-generated method stub
return EntityType.CONTACT;
}
#Override
public String hash() {
// TODO Auto-generated method stub
return contacthash;
}
}
Address is a User Defined Type and used in Table contact.
I am extending AbstractCassandraConfiguration to create Cassandra configutaion
package com.sellingsimplified.msor.common.cassandra;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cassandra.CassandraProperties;
import org.springframework.boot.autoconfigure.cassandra.CqlSessionBuilderCustomizer;
import org.springframework.boot.autoconfigure.cassandra.DriverConfigLoaderBuilderCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.CqlSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.SessionBuilderConfigurer;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import com.datastax.oss.driver.api.core.CqlSessionBuilder;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
#Configuration
#ConditionalOnProperty(value = "cassandra.enable", havingValue = "true", matchIfMissing = false)
#EnableCassandraRepositories(basePackages = "com.sellingsimplified.msor.common.repository")
public class CassandraConfig extends AbstractCassandraConfiguration {
#Value("${cassandra.table.contact:CONTACT}")
private String contactCassandra;
#Value("${cassandra.table.company:COMPANY}")
private String companyCassandra;
#Value("${spring.data.cassandra.contact-points}")
private String contactPoints;
#Value("${spring.data.cassandra.port}")
private int port;
#Value("${spring.data.cassandra.keyspace}")
private String keySpace;
#Value("${spring.data.cassandra.username}")
private String username;
#Value("${spring.data.cassandra.password}")
private String password;
#Value("${spring.data.cassandra.schema-action}")
private String schemaAction;
#Value("${cassandra.table.contact.history:ContactHistory}")
private String contactHistoryCassandra;
#Value("${cassandra.table.company.history:CompanyHistory}")
private String companyHistoryCassandra;
#Override
protected String getKeyspaceName() {
return keySpace;
}
#Override
protected String getContactPoints() {
return contactPoints;
}
#Override
protected int getPort() {
return port;
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.valueOf(schemaAction);
}
protected boolean getMetricsEnabled() {
return false;
}
#Bean(name = "companyCassandra")
public String companyCassandra() {
return companyCassandra;
}
#Bean(name = "contactHistoryCassandra")
public String contactHistoryCassandra() {
return contactHistoryCassandra;
}
#Bean(name = "companyHistoryCassandra")
public String companyHistoryCassandra() {
return companyHistoryCassandra;
}
#Bean(name = "contactCassandra")
public String contactCassandra() {
return contactCassandra;
}
#Bean
public CqlSessionBuilderCustomizer authCustomizer(CassandraProperties properties) {
return (builder) -> builder.withAuthCredentials(properties.getUsername(), properties.getPassword());
}
#Bean
#Override
public CqlSessionFactoryBean cassandraSession() {
CqlSessionFactoryBean cassandraSession = super.cassandraSession();// super session should be called only once
cassandraSession.setUsername(username);
cassandraSession.setPassword(password);
cassandraSession.setLocalDatacenter("DC1");
return cassandraSession;
}
#Override
public String[] getEntityBasePackages() {
return new String[] { "com.sellingsimplified" };
}
#Override
protected SessionBuilderConfigurer getSessionBuilderConfigurer() {
return new SessionBuilderConfigurer() {
#Override
public CqlSessionBuilder configure(CqlSessionBuilder cqlSessionBuilder) {
return cqlSessionBuilder.withConfigLoader(DriverConfigLoader.programmaticBuilder()
.withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofMillis(15000))
.withDuration(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, Duration.ofSeconds(100))
.withBoolean(DefaultDriverOption.METADATA_SCHEMA_ENABLED, false)
.withDuration(DefaultDriverOption.METADATA_SCHEMA_REQUEST_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONTROL_CONNECTION_AGREEMENT_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, Duration.ofSeconds(100)).build());
}
};
}
#Bean
DriverConfigLoaderBuilderCustomizer cassandraDriverCustomizer() {
return (builder) -> builder
.withDuration(DefaultDriverOption.CONTROL_CONNECTION_TIMEOUT, Duration.ofSeconds(100))
.withBoolean(DefaultDriverOption.METADATA_SCHEMA_ENABLED, false)
.withDuration(DefaultDriverOption.METADATA_SCHEMA_REQUEST_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONTROL_CONNECTION_AGREEMENT_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofSeconds(100))
.withDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, Duration.ofSeconds(100));
}
}
I am getting below exception while saving Contact Object
Caused by: org.springframework.data.cassandra.CassandraUncategorizedException: No converter found capable of converting from type [com.sellingsimplified.msor.common.schema.Address] to type [com.datastax.oss.driver.api.core.data.UdtValue]; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.sellingsimplified.msor.common.schema.Address] to type [com.datastax.oss.driver.api.core.data.UdtValue]
at org.springframework.data.cassandra.core.cql.CassandraExceptionTranslator.translate(CassandraExceptionTranslator.java:160) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.cql.CassandraExceptionTranslator.translateExceptionIfPossible(CassandraExceptionTranslator.java:72) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.config.CqlSessionFactoryBean.translateExceptionIfPossible(CqlSessionFactoryBean.java:646) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.3.1.jar:5.3.1]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.3.1.jar:5.3.1]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.1.jar:5.3.1]
at com.sun.proxy.$Proxy135.save(Unknown Source) ~[na:na]
at com.sellingsimplified.msor.marchingengine.consumer.MSORGatewayEndpoint.processLead(MSORGatewayEndpoint.java:70) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171) ~[spring-messaging-5.3.1.jar:5.3.1]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120) ~[spring-messaging-5.3.1.jar:5.3.1]
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48) ~[spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:321) ~[spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.invoke(BatchMessagingMessageListenerAdapter.java:170) ~[spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:162) ~[spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.adapter.BatchMessagingMessageListenerAdapter.onMessage(BatchMessagingMessageListenerAdapter.java:58) ~[spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeBatchOnMessage(KafkaMessageListenerContainer.java:1744) [spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeBatchOnMessageWithRecordsOrList(KafkaMessageListenerContainer.java:1735) [spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeBatchOnMessage(KafkaMessageListenerContainer.java:1693) [spring-kafka-2.6.3.jar:2.6.3]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeBatchListener(KafkaMessageListenerContainer.java:1622) [spring-kafka-2.6.3.jar:2.6.3]
... 7 common frames omitted
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.sellingsimplified.msor.common.schema.Address] to type [com.datastax.oss.driver.api.core.data.UdtValue]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:322) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175) ~[spring-core-5.3.1.jar:5.3.1]
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.convertIfNecessary(ConvertingPropertyAccessor.java:120) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.getProperty(ConvertingPropertyAccessor.java:91) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.getWriteValue(MappingCassandraConverter.java:744) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.writeMapFromWrapper(MappingCassandraConverter.java:490) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.convert.MappingCassandraConverter.write(MappingCassandraConverter.java:456) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.StatementFactory.insert(StatementFactory.java:307) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.CassandraTemplate.doInsert(CassandraTemplate.java:632) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:622) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:93) ~[spring-data-cassandra-3.1.1.jar:3.1.1]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:524) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:531) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:156) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.1.jar:2.4.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.1.jar:5.3.1]
at com.sun.proxy.$Proxy135.save(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.1.jar:5.3.1]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.1.jar:5.3.1]
... 26 common frames omitted
You will need to implement a class annotated with #Entity that is mapped to your UDT.
Have a look at the Entities page of the Java driver docs for details. Cheers!

Why I've got a multiply data from findById() method Spring Data?

Hi everyone I recently work with Spring Data and I have such a question.
I have my Entity that mapped like this:
#Getter
#Setter
#EqualsAndHashCode(callSuper = true)
#ToString(callSuper = true)
#Table(name = "movie")
#Entity
public class Movie extends BaseEntity {
private String name;
#Enumerated(EnumType.STRING)
#Column(columnDefinition = "enum('ACTION','DRAMA','COMEDY','FANTASY','HORROR')")
private Genre genre;
private BigDecimal budget;
#ManyToMany(mappedBy = "movies")
private Set<Actor> actors;
public Movie() {
}
}
My Actor Entity:
#Getter
#Setter
#EqualsAndHashCode(callSuper = true, exclude = "movies")
#ToString(callSuper = true, exclude = "movies")
#Table(name = "actor")
#Entity
public class Actor extends BaseEntity {
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "salary")
private BigDecimal salary;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "actor_movie",
joinColumns = {#JoinColumn(name = "actor_id")},
inverseJoinColumns = {#JoinColumn(name = "movie_id")}
)
private Set<Movie> movies;
public Actor() {
}
}
And my BaseEntity;
#Data
#MappedSuperclass
public class BaseEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
I am using JpaRepository<Actor, Long> to get my actors from database:
#Repository
public interface ActorRepository extends JpaRepository<Actor, Long> {
}
And here is my controller:
#RestController
#RequestMapping("actor")
public class ActorController {
#Autowired
ActorRepository actorRepository;
#PostMapping
public Actor save(#RequestBody Actor actor) {
actorRepository.save(actor);
return actor;
}
#GetMapping
public Iterable<Actor> findAllActors() {
return actorRepository.findAll();
}
#GetMapping("{id}")
public Actor findActor(#PathVariable Long id) {
return actorRepository.findById(id).orElseThrow(NotFoundException::new);
}
#PutMapping("{id}")
public Actor update(#RequestBody Actor actor, #PathVariable Long id) {
actor.setId(id);
return actorRepository.save(actor);
}
#DeleteMapping("{id}")
public ResponseEntity<Actor> delete(#PathVariable Long id) {
actorRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
So when I'm trying to get my actor by id it gets a so many times:
And finally it fails with StackOverFlowError:
java.lang.StackOverflowError: null
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_172]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_172]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_172]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_172]
at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_172]
at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_172]
at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_172]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_172]
at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_172]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_172]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_172]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_172]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:737) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:145) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:107) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.9.jar:2.9.9]
Why is this happens? And how it can be fixed?

Dynamic type caste Spring pathvariable

I am planning to create one simple Spring Rest Service Project with JPA which will fetch the details from the database based on the entity name and entity id given in path variables.
consider following code.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ds.dao.EntityDAO;
import com.ds.entities.Employees;
import javax.persistence.Entity;
#Controller
#RequestMapping("/")
public class DynaRestController {
#Autowired
EntityDAO entityDAO;
#RequestMapping(value = "{entityName}/{enityId}",method = RequestMethod.GET)
public #ResponseBody Object getEntity(#PathVariable("entityName") String entityName,#PathVariable("enityId") Object id) {
return entityDAO.getEntityById(entityName, id);
}
}
Entity DAO Class
public class EntityDAO {
#Autowired
EntityManager entityManager;
public Object getEntityById(String entityName, Object id) {
EntityType<?> entityType = getEntityByName(entityName);
Object idcasted = entityType.getIdType().getJavaType().cast(id);
System.out.println(idcasted.getClass().getName());
Object entity = entityManager.find(entityType.getJavaType(), idcasted);
System.out.println("Entity.. Name .." + entityName);
// Employees entity = session.load(Employees.class, id);
return entity;
}
private EntityType<?> getEntityByName(String name) {
Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
for (Iterator<EntityType<?>> iterator = entities.iterator(); iterator.hasNext();) {
EntityType<?> entityType = (EntityType<?>) iterator.next();
if (entityType.getName().equals(name))
return entityType;
}
return null;
}
}
Employees Class
#Configurable
#Entity
#Table(name = "employees", catalog = "employees")
public class Employees implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int empNo;
private Date birthDate;
private String firstName;
private String lastName;
private String gender;
private Date hireDate;
private Set<Titles> titleses = new HashSet<Titles>(0);
private Set<Salaries> salarieses = new HashSet<Salaries>(0);
private Set<DeptEmp> deptEmps = new HashSet<DeptEmp>(0);
private Set<DeptManager> deptManagers = new HashSet<DeptManager>(0);
public Employees() {
}
public Employees(int empNo, Date birthDate, String firstName, String lastName, String gender, Date hireDate) {
this.empNo = empNo;
this.birthDate = birthDate;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.hireDate = hireDate;
}
public Employees(int empNo, Date birthDate, String firstName, String lastName, String gender, Date hireDate,
Set<Titles> titleses, Set<Salaries> salarieses, Set<DeptEmp> deptEmps, Set<DeptManager> deptManagers) {
this.empNo = empNo;
this.birthDate = birthDate;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.hireDate = hireDate;
this.titleses = titleses;
this.salarieses = salarieses;
this.deptEmps = deptEmps;
this.deptManagers = deptManagers;
}
#Id
#Column(name = "emp_no", unique = true, nullable = false)
public int getEmpNo() {
return this.empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
#Temporal(TemporalType.DATE)
#Column(name = "birth_date", nullable = false, length = 10)
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "first_name", nullable = false, length = 14)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false, length = 16)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "gender", nullable = false, length = 2)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Temporal(TemporalType.DATE)
#Column(name = "hire_date", nullable = false, length = 10)
public Date getHireDate() {
return this.hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Titles> getTitleses() {
return this.titleses;
}
public void setTitleses(Set<Titles> titleses) {
this.titleses = titleses;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<Salaries> getSalarieses() {
return this.salarieses;
}
public void setSalarieses(Set<Salaries> salarieses) {
this.salarieses = salarieses;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
#JsonBackReference
public Set<DeptEmp> getDeptEmps() {
return this.deptEmps;
}
public void setDeptEmps(Set<DeptEmp> deptEmps) {
this.deptEmps = deptEmps;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "employees")
public Set<DeptManager> getDeptManagers() {
return this.deptManagers;
}
public void setDeptManagers(Set<DeptManager> deptManagers) {
this.deptManagers = deptManagers;
}
}
When i am dynamically casting the path variable by using following code
Object idcasted = entityType.getIdType().getJavaType().cast(id);
Object entity = entityManager.find(entityType.getJavaType(), idcasted);
it is throwing ClassCastExpcetion
java.lang.ClassCastException: Cannot cast java.lang.String to int
at java.lang.Class.cast(Class.java:3369) ~[na:1.8.0_112]
at com.techm.att.ds.dao.EntityDAO.getEntityById(EntityDAO.java:33) ~[classes/:na]
at com.techm.att.ds.dao.EntityDAO$$FastClassBySpringCGLIB$$8e64d745.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
any Help will be highly appriciated..
I write you a simple example regarding the comments.
This is the same behavior. Your RestController gets actually a string:
public static void main(String[] args) {
Object myString = "myString";
System.out.println(myString.getClass()); // class java.lang.String
int.class.cast(myString);
}
The cast method checks the instanceof your given value and it fails:
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}

org.hibernate.exception.ConstraintViolationException with onetomany annotation in hibernate

I am new to exploring spring boot and hibernate and facing a certain issue which i believe is not new. However with all the suggestions in place, I still could not find a way to resolve the problem that I am currently facing.
Can anyone of you please point where I am going wrong?
Following is the scenario -
I have a Category class and each instance of the category class can have many instances of sub-categories.
I have setup the relationship using #OneToMany annotation. However when trying to save records to the database, I am facing the
org.hibernate.exception.ConstraintViolationException with exception reported saying foreign key value cannot be NULL.
Please find below the class declarations
Category.class
import java.util.Date;
import java.util.Set;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="Category")
#Scope("session")
#EntityListeners(AuditingEntityListener.class)
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Category_Id")
private Long Id;
private String CategoryName;
private String CategoryValue;
#Column(name = "IsActive", columnDefinition = "BOOLEAN")
private Boolean IsActive;
// #OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
#OneToMany(fetch = FetchType.EAGER, mappedBy = "category")
// #JoinTable(name = "Category_SubCategory", joinColumns = { #JoinColumn(name = "Category_Id") }, inverseJoinColumns = { #JoinColumn(name = "Sub_Category_Id") })
private Set<SubCategory> SubCategories;
#CreatedBy
#Column(nullable = false, updatable = false)
private String CreatedBy;
#CreatedDate
#Column(nullable = false, updatable = false)
private Date CreatedDate;
#LastModifiedBy
#Column(nullable = false)
private String ModifiedBy;
#LastModifiedDate
#Column(nullable = false)
private Date ModifiedDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getCategoryName() {
return CategoryName;
}
public void setCategoryName(String categoryName) {
CategoryName = categoryName;
}
public String getCategoryValue() {
return CategoryValue;
}
public void setCategoryValue(String categoryValue) {
CategoryValue = categoryValue;
}
public Boolean getIsActive() {
return IsActive;
}
public void setIsActive(Boolean isActive) {
IsActive = isActive;
}
public Set<SubCategory> getSubCategories() {
return SubCategories;
}
public void setSubCategories(Set<SubCategory> subCategories) {
SubCategories = subCategories;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(Date createdDate) {
CreatedDate = createdDate;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return ModifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
ModifiedDate = modifiedDate;
}
}
SubCategory.class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.context.annotation.Scope;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name="SubCategory")
#Scope("session")
#EntityListeners(AuditingEntityListener.class)
public class SubCategory {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Sub_Category_Id")
private Long Id;
private String SubCategoryName;
private String SubCategoryValue;
#Column(name = "IsActive", columnDefinition = "BOOLEAN")
private Boolean IsActive;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "Category_Id", nullable = false)
private Category category;
#CreatedBy
#Column(nullable = false, updatable = false)
private String CreatedBy;
#CreatedDate
#Column(nullable = false, updatable = false)
private Date CreatedDate;
#LastModifiedBy
#Column(nullable = false)
private String ModifiedBy;
#LastModifiedDate
#Column(nullable = false)
private Date ModifiedDate;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getSubCategoryName() {
return SubCategoryName;
}
public void setSubCategoryName(String subCategoryName) {
SubCategoryName = subCategoryName;
}
public String getSubCategoryValue() {
return SubCategoryValue;
}
public void setSubCategoryValue(String subCategoryValue) {
SubCategoryValue = subCategoryValue;
}
public Boolean getIsActive() {
return IsActive;
}
public void setIsActive(Boolean isActive) {
IsActive = isActive;
}
public String getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(String createdBy) {
CreatedBy = createdBy;
}
public Date getCreatedDate() {
return CreatedDate;
}
public void setCreatedDate(Date createdDate) {
CreatedDate = createdDate;
}
public String getModifiedBy() {
return ModifiedBy;
}
public void setModifiedBy(String modifiedBy) {
ModifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return ModifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
ModifiedDate = modifiedDate;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
ServiceImpl -
#Override
public void save(Category category) {
Set<SubCategory> subCategoryRec = category.getSubCategories();
if(subCategoryRec != null && subCategoryRec.size() > 0) {
for(SubCategory rec: subCategoryRec) {
try {
subcategoryRepository.save(rec);
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
try {
categoryRepository.save(category);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Not sure where I am wrong.
The exception reported has the following stacktrace -
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2855)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3426)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:619)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:273)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:254)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:299)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
at com.sun.proxy.$Proxy113.persist(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
at com.sun.proxy.$Proxy113.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:513)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:475)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 104 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null
The reason is you are trying to save a child object before saving parent object. Hence change the implementation as first save parent object followed by child object as shown below.
categoryRepository.save(category);
Set<SubCategory> subCategoryRec = category.getSubCategories();
if(subCategoryRec != null && subCategoryRec.size() > 0) {
for(SubCategory rec: subCategoryRec) {
subcategoryRepository.save(rec);
}
}
Well, actually you should not do this manually. For this exact problem you should use CASCADING
From here:
In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other.
So this should basically solve your problem:
#OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade=CascadeType.PERSIST)
private Set<SubCategory> SubCategories;
You can choose between several Cascade-Types, if you want a different behaviour for DELETE etc.:
The cascade types supported by the Java Persistence Architecture are as below:
CascadeType.PERSIST : means that save() or persist() operations cascade to related entities.
CascadeType.MERGE : means that related entities are merged when the owning entity is merged.
CascadeType.REFRESH : does the same thing for the refresh() operation.
CascadeType.REMOVE : removes all related entities association with this setting when the owning entity is deleted.
CascadeType.DETACH : detaches all related entities if a “manual detach” occurs.
CascadeType.ALL : is shorthand for all of the above cascade operations.
See here.
EDIT: (Referencing the other proposed answer):
Calling .save will not automatically commit the transaction, try .saveAndFlush if you really want to do it manually, but i would recommend using Cascade.
See: Difference between save and saveAndFlush in Spring data jpa

org.hibernate.HibernateException: More than one row with the given identifier was found: 681

Dec 17, 2015 3:49:03 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/crafartweb] threw exception [Request processing failed; nested
exception is org.hibernate.HibernateException: More than one row with
the given identifier was found: 681, for class:
com.crafart.dataobjects.StoreDO] with root cause
org.hibernate.HibernateException: More than one row with the given identifier was found: 681, for class: com.crafart.dataobjects.StoreDO
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:104)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2374)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:722)
at org.hibernate.type.EntityType.resolve(EntityType.java:492)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:168)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:137)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1112)
at org.hibernate.loader.Loader.processResultSet(Loader.java:969)
at org.hibernate.loader.Loader.doQuery(Loader.java:917)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:348)
at org.hibernate.loader.Loader.doList(Loader.java:2548)
at org.hibernate.loader.Loader.doList(Loader.java:2534)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2364)
at org.hibernate.loader.Loader.list(Loader.java:2359)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:357)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1194)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at com.crafart.data.SellerDAOImpl.getSellerDetails(SellerDAOImpl.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy78.getSellerDetails(Unknown Source)
at com.crafart.seller.service.ManageSellerServiceImpl.getSellerDetails(ManageSellerServiceImpl.java:170)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy89.getSellerDetails(Unknown Source)
at com.crafart.MenuController.showManageSellers(MenuController.java:216)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run
(Thread.java:744)
My StoreClass is ---
/**
*
*/
package com.crafart.dataobjects;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* store entity data object maps to store table in crafart database. Property
* belongs to store table and store_id is primary key which is generated by db
* sequence <blockquote>seq_store<blockquote>
*
* #author Karthi
* #version 1.0
*
*/
#Entity
#Table(name = "STORE")
public class StoreDO implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -3168290124126749175L;
#Id
#Column(name = "store_id")
#SequenceGenerator(name = "seq_store", sequenceName = "seq_store", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_store")
private long storeId;
#ManyToOne
#JoinColumn(name = "seller_id", nullable = false)
private SellerDO sellerDO;
#Column(name = "name")
private String name;
#Column(name = "store_url")
private String storeUrl;
#Column(name = "store_description")
private String storeDescription;
#Column(name = "return")
private String storeReturn;
public SellerDO getSellerDO() {
return sellerDO;
}
public void setSellerDO(SellerDO sellerDO) {
this.sellerDO = sellerDO;
}
public long getStoreId() {
return storeId;
}
public void setStoreId(long storeId) {
this.storeId = storeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStoreUrl() {
return storeUrl;
}
public void setStoreUrl(String storeUrl) {
this.storeUrl = storeUrl;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String store_Description) {
this.storeDescription = store_Description;
}
public String getStoreReturn() {
return storeReturn;
}
public void setStoreReturn(String store_Return) {
this.storeReturn = store_Return;
}
}
**
storeBO class is this
**
/**
*
*/
package com.crafart.dataobjects;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* seller entity data object maps to seller table in crafart database. Property
* belongs to seller table and seller_id is primary key which is generated by db
* sequence <blockquote>seq_seller<blockquote>
*
* #author karthi
* #version 1.0
*/
#Entity
#Table(name = "SELLER")
public class SellerDO implements Serializable, Cloneable {
/**
* generated serial id
*/
private static final long serialVersionUID = 2950842206999695829L;
#Id
#Column(name = "seller_id")
#SequenceGenerator(name = "seq_seller", sequenceName = "seq_seller", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_seller")
private long sellerId;
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private StoreDO storeDO;
#Column(name = "first_Name")
private String firstName;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "SELLER_ADDRESS", joinColumns = { #JoinColumn(name = "SELLER_ID") }, inverseJoinColumns = { #JoinColumn(name = "ADDRESS_ID") })
private List<AddressDO> addressDOs = new ArrayList<>();
#OneToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "SELLER_CONTACT", joinColumns = { #JoinColumn(name = "SELLER_ID") }, inverseJoinColumns = { #JoinColumn(name = "CONTACT_ID") })
private List<ContactDO> contactDOs = new ArrayList<>();
#ManyToMany(mappedBy = "sellerDOs")
private List<ProductDO> productDOs = new ArrayList<>();
#Column(name = "last_Name")
private String lastName;
#Column(name = "gender")
private int gender;
#Column(name = "dob")
private String dateOfBirth;
private int tin_no;
#Column(name = "company_Name")
private String companyName;
#Column(name = "company_Logo")
private String companyLogo;
#Column(name = "epch_no")
private String epchNo;
#Column(name = "vat_no")
private String vat_no;
#Column(name = "cst_no")
private String cst_no;
/*
* add variables
* */
#Column(name = "gst_no")
private String gst_no;
#Column(name = "officeno")
private int officeno;
#Column(name = "mobileno")
private int mobileno;
#Column(name = "email")
private String email;
#Column(name = "panno")
private String panno;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "commission_id",nullable = true)
private CommissionDO commissionDO;
private int status;
private int approved;
#Column(name = "password")
private String password;
#Column(name = "confirm_password")
private String confirmpassword;
public String getEpchNo() {
return epchNo;
}
public void setEpchNo(String epchNo) {
this.epchNo = epchNo;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public long getSellerId() {
return sellerId;
}
public void setSellerId(long sellerId) {
this.sellerId = sellerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getTin_no() {
return tin_no;
}
public void setTin_no(int tin_no) {
this.tin_no = tin_no;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyLogo() {
return companyLogo;
}
public void setCompanyLogo(String companyLogo) {
this.companyLogo = companyLogo;
}
public String getEpch_no() {
return epchNo;
}
public void setEpch_no(String epch_no) {
this.epchNo = epch_no;
}
public String getVat_no() {
return vat_no;
}
public int getOfficeno() {
return officeno;
}
public void setOfficeno(int officeno) {
this.officeno = officeno;
}
public int getMobileno() {
return mobileno;
}
public void setMobileno(int mobileno) {
this.mobileno = mobileno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPanno() {
return panno;
}
public void setPanno(String panno) {
this.panno = panno;
}
public void setVat_no(String vat_no) {
this.vat_no = vat_no;
}
public String getCst_no() {
return cst_no;
}
public void setCst_no(String cst_no) {
this.cst_no = cst_no;
}
public String getGst_no() {
return gst_no;
}
public void setGst_no(String gst_no) {
this.gst_no = gst_no;
}
public CommissionDO getCommissionDO() {
return commissionDO;
}
public void setCommissionDO(CommissionDO commissionDO) {
this.commissionDO = commissionDO;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getApproved() {
return approved;
}
public void setApproved(int approved) {
this.approved = approved;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public List<ContactDO> getContactDOs() {
return contactDOs;
}
public void setContactDOs(List<ContactDO> contactDOs) {
this.contactDOs = contactDOs;
}
public StoreDO getStoreDO() {
return storeDO;
}
public void setStoreDO(StoreDO storeDO) {
this.storeDO = storeDO;
}
public List<AddressDO> getAddressDOs() {
return addressDOs;
}
public void setAddressDOs(List<AddressDO> addressDOs) {
this.addressDOs = addressDOs;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<ProductDO> getProductDOs() {
return productDOs;
}
public void setProductDOs(List<ProductDO> productDOs) {
this.productDOs = productDOs;
}
}
You have an invalid mapping
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private StoreDO storeDO;
Should be
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private List<StoreDO> storeDO;
#OneToMany(mappedBy = "sellerDO", targetEntity=StoreDO.class, cascade = CascadeType.ALL)
private Set<StoreDO> storeDO;

Resources