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

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?

Related

findById causes StackOverflowError but findAll workds fine

I'm having a strange problem with a spring boot endpoint that calls JpaRepository findById(). When ever I send a GET request to the endpoint /v1/goals/{id} a stack overflow error occurs, while GET requests to /v1/goals work fine.
Edit: added the error message to the bottom
Simplified Controller class:
#RestController
public class GoalController {
private final GoalServiceImpl service;
#Autowired
GoalController(GoalServiceImpl service) { this.service = service; }
#GetMapping("/v1/goals")
ResponseEntity<List<Goal>> allGoals() { return new ResponseEntity<>(service.getGoals(), HttpStatus.OK); }
#GetMapping("/v1/goals/{id}")
ResponseEntity<String> singleGoal(#PathVariable Long id) {
return new ResponseEntity<>(service.getGoalById(id).toString(), HttpStatus.OK);
}
}
Simplified Service class:
#Service
public class GoalServiceImpl implements GoalService {
private final GoalRepository repository;
#Autowired
public GoalServiceImpl(GoalRepository repository) { this.repository = repository; }
public Goal getGoalById(Long id) {
return repository
.findById(id)
.orElseThrow(() -> new GoalNotFoundException(id));
}
public List<Goal> getGoals() { return repository.findAll(); }
}
Simplified Entity class:
#NoArgsConstructor
#Data
#Entity
public class Goal {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long goalId;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id")
#JsonIgnore
private User user;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "goal")
#JsonIgnoreProperties(value = "goal")
private List<Milestone> milestones;
}
Simplified Milestone Entity:
#NoArgsConstructor
#Data
#Entity
public class Milestone {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private Long milestone_id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
#JsonIgnore
private User user;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "goal_id")
private Goal goal;
Simplified User Entity:
#NoArgsConstructor
#Data
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userId;
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
#JsonIgnoreProperties(value = "user")
private List<Goal> goals;
}
Error message:
java.lang.StackOverflowError: null
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:56) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at com.motivate.api.user.User$HibernateProxy$KaIclPZ9.toString(Unknown Source) ~[classes/:na]
at java.base/java.lang.String.valueOf(String.java:2951) ~[na:na]
at com.motivate.api.goal.Goal.toString(Goal.java:16) ~[classes/:na]
at java.base/java.lang.String.valueOf(String.java:2951) ~[na:na]
at java.base/java.lang.StringBuilder.append(StringBuilder.java:168) ~[na:na]
at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:473) ~[na:na]
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:622) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at java.base/java.lang.String.valueOf(String.java:2951) ~[na:na]
at com.motivate.api.user.User.toString(User.java:11) ~[classes/:na]
at jdk.internal.reflect.GeneratedMethodAccessor58.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:56) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at com.motivate.api.user.User$HibernateProxy$KaIclPZ9.toString(Unknown Source) ~[classes/:na]
Solution
provided by Chris and PaulD in the comments:
#GetMapping("/v1/goals/{id}")
ResponseEntity<Goal> singleGoal(#PathVariable Long id) {
return new ResponseEntity<>(service.getGoalById(id), HttpStatus.OK);
}
Remove the toString() as that causes the whole object to be serialised by lombok which doesn't take into account the jackson annotations. Change ResponseEntity to be of type Goal and pass in the whole entity.

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!

EntityNotFoundException on save function

I am trying to save Entity with one to many relation. It throws EntityNotFoundException when trying to save the entity
I did some research but not able to find any solution to this
Order Entity:
#Data
#Component
#Entity
#Slf4j
#Table (name = ORDER_TABLE_NAME)
public class OrderEntity {
//== Order Details
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = ORDER_ID_COLUMN)
private String orderIdGuid;
#Column (name = ORDER_BOOKED_DATETIME_COLUMN)
private LocalDateTime orderBookedDate;
#Column(name = ORDER_STATUS_COLUMN)
private String orderStatus;
#OneToMany( cascade={CascadeType.ALL}, orphanRemoval = true)
#JoinColumn(name= ORDER_ID_COLUMN)
#Autowired
private List<ProductEntity> products;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = ORDER_ID_COLUMN)
private List<Followup> followups;
Product Entity:
#Data
#Component
#Entity
#Table (name=ORDER_PRODUCT_TABLE)
public class ProductEntity {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column (name = PRODUCT_PRIMARY_ID)
private String product_primary_id;
//=== defined by constants
#Column(name = PRODUCT_NAME)
private String productName;
DAOClass:
#Component
#Data
#Slf4j
public class DAOOrderRepository {
#Autowired
OrderRepository orderRepository;
public void saveOrderEntity(OrderEntity orderEntity) {
orderEntity.setOrderUpdatedDate(LocalDate.now());
orderRepository.save(orderEntity);
}
public OrderEntity findOrderByOrderId(String orderId) {
return orderRepository.findOrderEntityByOrderIdGuid(orderId);
}
public List<OrderEntity> findAllOrdersByEmployeeId(String employeeId) {
return orderRepository.findBySalesRepEmployeeId(employeeId);
}
}
Repository:
#Repository
public interface OrderRepository extends JpaRepository<OrderEntity,String> {
List<OrderEntity> findBySalesRepEmployeeId(String employeeId);
OrderEntity findOrderEntityByOrderIdGuid(String orderIdGuid);
}
Exception:
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to
find
com.app.apicore.Entities.OrderServiceEntity.ProductEntity.ProductEntity
with id 03350d2a-15cf-46da-ba2c-58aeec79db9a; nested exception is
javax.persistence.EntityNotFoundException: Unable to find
com.app.apicore.Entities.OrderServiceEntity.ProductEntity.ProductEntity
with id 03350d2a-15cf-46da-ba2c-58aeec79db9a
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:378)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy111.save(Unknown Source)
at com.app.apicore.Apis.DAOOrderRepository.saveOrderEntity(DAOOrderRepository.java:24)
Each order is a new order record. So when i try to save the order record for the first time, it saves the order data correct. It saves the order data correct for second time to. But on the third time throws exception.

Object.setXXX(Spring Data JPA Entity) throws NullPointerException

I am facing Spring Data JPA underlying object problem. If there is an object and calls its setter method and if the parameter could be entity returned by JpaRepository, it throws NullPointerException.
Entity Cheat
#Entity
#Table(name = "cheat")
#DynamicInsert
#DynamicUpdate
#Getter
#Setter
#EqualsAndHashCode(exclude={"vote"})
#NoArgsConstructor
#RequiredArgsConstructor(staticName="of")
public class Cheat implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cheat_seq", length = 10)
private Long cheatSeq;
#Column(name = "question", unique = true, nullable = false)
#NonNull
private String question;
#Column(name = "answer", unique = true, nullable = false)
#NonNull
private String answer;
#Column(name = "writer_ip", nullable = false)
#NonNull
private String writerIP;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "reg_date", nullable = false)
#NonNull
private Date regDate;
#Transient
#NonNull
private String regDateText;
#OneToMany(mappedBy = "cheat", fetch=FetchType.EAGER)
private Set<CheatVote> vote = new HashSet<CheatVote>();
#Override
public String toString() {
return "Cheat [cheatSeq=" + cheatSeq + "]";
}
}
And entity CheatVote which is a #ManyToOne collection from Cheat, is below:
#Entity
#Table(name="cheat_vote")
#DynamicInsert
#DynamicUpdate
#Getter
#Setter
#RequiredArgsConstructor(staticName="of")
#NoArgsConstructor
public class CheatVote implements Serializable{
private static final long serialVersionUID = 1L;
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Id
#Column(name="seq", nullable=false)
private Long seq;
#Column(name="val", nullable=false)
#NonNull
private Integer value;
#Column(name="ip_address", nullable=false)
#NonNull
private String ipAddress;
#JoinColumn(name="cheat_fk", referencedColumnName="cheat_seq")
#ManyToOne(cascade=CascadeType.ALL)
#NonNull
private Cheat cheat;
#Override
public String toString() {
return "CheatVote [seq=" + seq + "]";
}
}
Service layer is below:
#Transactional
#Service
public class CheatVoteServiceImpl implements CheatVoteService{
#Autowired
private CheatVoteRepository repository;
#Autowired
private CheatService cheatService;
#Override
public void addGoodVote(Long cheatSeq, String ipAddress) throws NotFoundEntityException {
Cheat cheat = cheatService.findOne(cheatSeq);
CheatVote vote = new CheatVote();
vote.setCheat(cheat);
vote.setValue(CheatVoteRepository.VOTE_TYPE_GOOD);
vote.setIpAddress(ipAddress);
Set<CheatVote> votes = new HashSet<CheatVote>();
votes.add(vote);
cheat.setVote(votes);
cheatService.addCheat(cheat);
repository.save(vote);
}
}
Repository layer is below:
public interface CheatVoteRepository extends JpaRepository<CheatVote, Long>{
Integer VOTE_TYPE_GOOD = 1;
}
Test code is below:
#Test
public void voteTest() throws Exception{
cheatService.addCheat(addDTO1);
Cheat cheat = cheatService.findAll().get(0);
assertEquals(0, cheat.getVote().size());
cheatVoteService.addGoodVote(cheat.getCheatSeq(), "127.0.0.1");
}
Two DTO objects are below. One is :
#NoArgsConstructor
#Data
public class CheatAddNewDTO {
private String ipAddress;
private List<CheatUnit> unitList;
}
And the other one is:
#RequiredArgsConstructor(staticName="of")
#NoArgsConstructor
#Data
public class CheatUnit {
#NotNull
#NonNull
#Mapping("question")
private String question;
#NotNull
#NonNull
#Mapping("answer")
private String answer;
}
It throws NullPointerException:
java.lang.NullPointerException: cheat
at com.ddedderu.moonBladeQuiz.data.entity.CheatVote.setCheat(CheatVote.java:29)
at com.ddedderu.moonBladeQuiz.data.service.CheatVoteServiceImpl.addGoodVote(CheatVoteServiceImpl.java:31)
at com.ddedderu.moonBladeQuiz.data.service.CheatVoteServiceImpl$$FastClassBySpringCGLIB$$d089e475.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736)
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:282)
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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671)
at com.ddedderu.moonBladeQuiz.data.service.CheatVoteServiceImpl$$EnhancerBySpringCGLIB$$b1f41534.addGoodVote(<generated>)
at com.ddedderu.moonBladeQuiz.MoonBladeQuizApplicationTests.voteTest(MoonBladeQuizApplicationTests.java:85)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
After seeing that error stacks, I got thinking that when the entity is set in something object's setter method, its proxy object (maybe used with AOP skill) does something to deal with JPA internal system.
But why do I have to even consider that underlying part of JPA ?
Or is that error stack comes because of my malformed entity structure?
What went wrong?
And I am sorry that I can not react on your comment quickly !
Feel free to require any code related with this question !
Thank you.
The NPE doesn't come from JPA nor Spring Data JPA.
It is simply that in these three lines:
Cheat cheat = cheatService.findOne(cheatSeq);
CheatVote vote = new CheatVote();
vote.setCheat(cheat);
The cheat doesn't get found and therefore is null and when you call vote.setCheat the Lombok #NonNull annotation takes effect and throws an exception.
To fix the problem do one of the following:
check that cheat is non-null before setting it.
remove the #NonNull annotation.

Hibernate One to many Mapping Error

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

Resources