Instead of update query , calling insert query in spring jpa - java
I am trying to update multiple table in spring jpa.
Consumer table update is happening perfectl but provider table is not able to update. Instead of it , its trying for insert which causes violation of primary key which is expected because it is trying for insert instead of update.
Although my code flow for both the table is same but there is issue only with producer.
This is my Consumer entity
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
#Data
#Entity
#Table(name = "consumer_table")
#IdClass(ConsumerId.class)
public class Consumer implements Serializable {
#Id
#Column(name = "consumer_cmdb")
private String consumerCMDB;
#Id
#Column(name = "api_name")
private String apiName;
#Column(name = "consumer_app_vp")
private String consumerAppVp;
#Column(name = "consumer_app_director")
private String consumerAppDirector;
#Column(name = "consumer_app_manager")
private String consumerAppManager;
#Column(name = "consumer_tps")
private String consumerTps;
#Column(name = "consumer_hosted_on")
private String consumerHost;
#Column(name = "consumer_system_type")
private String consumerSystemType;
#Column(name = "carbon_namespace_ownership")
private String consumerCarbonNamespaceOwnership;
#Column(name = "hosted_vm_ownership")
private String consumerHostedVmOwnership;
#Column(name = "consumer_status")
private String consumerStatus;
#Column(name = "comments")
private String ConsumerComments;
#Column(name = "consumer_auth_type")
private String ConsumerAuthType;
}
This is my Consumer repository
import java.util.List;
#Repository
public interface ConsumerRepository extends JpaRepository<Consumer, ConsumerId> {
List<Consumer> findByConsumerCMDB(String CMDB);
#Query(nativeQuery = true,value = "select count(*) from consumer_table where api_name IS NOT NULL AND consumer_cmdb=:cmdbId")
Integer getTotalApisOwned(#Param("cmdbId") String cmdbId);
List<Consumer> findByApiName(String apiName);
Consumer findByApiNameAndConsumerCMDB(String apiName,String consumerCMDB);
}
This is my Provider entity
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
#Data
#Entity
#Table(name = "provider_table")
#IdClass(Provider.class)
public class Provider implements Serializable {
#Id
#Column(name = "api_name")
private String apiName;
#Id
#Column(name = "provider_cmdb")
private String providerCMDB;
#Column(name = "provider_app_vp")
private String providerAppVp;
#Column(name = "provider_app_director")
private String providerAppDirector;
#Column(name = "upstream_service_hosted_on")
private String upstreamServiceHost;
#Column(name = "upstream_service_url")
private String upstreamServiceUrl;
#Column(name = "upstream_vm_ownership")
private String upstreamVmOwnership;
#Column(name = "upstream_service_type")
private String upstreamServiceType;
#Column(name = "carbon_namespace_ownership")
private String providerCarbonNamespaceOwnership;
#Column(name = "hosted_vm_ownership")
private String providerHostedVmOwnership;
#Column(name = "provider_status")
private String providerStatus;
#Column(name = "comments")
private String providerComments;
}
This is my Provider Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface ProviderRepository extends JpaRepository<Provider, ProviderId> {
public List<Provider> findByApiName(String apiName);
public Provider findByUpstreamServiceUrl(String upstreamUrl);
public Provider findByApiNameAndProviderCMDB(String apiName,String providerCMDB);
/* #Query()
public void updateProviderByCMDBAndApiName(Provider provider, String providerCMDB, String apiName);*/
}
Here is the logs
2022-07-13 21:13:25.442 DEBUG [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] org.hibernate.SQL : select consumer0_.api_name as api_name1_1_0_, consumer0_.consumer_cmdb as consumer2_1_0_, consumer0_.consumer_auth_type as consumer3_1_0_, consumer0_.comments as comments4_1_0_, consumer0_.consumer_app_director as consumer5_1_0_, consumer0_.consumer_app_manager as consumer6_1_0_, consumer0_.consumer_app_vp as consumer7_1_0_, consumer0_.carbon_namespace_ownership as carbon_n8_1_0_, consumer0_.consumer_hosted_on as consumer9_1_0_, consumer0_.hosted_vm_ownership as hosted_10_1_0_, consumer0_.consumer_status as consume11_1_0_, consumer0_.consumer_system_type as consume12_1_0_, consumer0_.consumer_tps as consume13_1_0_ from consumer_table consumer0_ where consumer0_.api_name=? and consumer0_.consumer_cmdb=?
Hibernate: select consumer0_.api_name as api_name1_1_0_, consumer0_.consumer_cmdb as consumer2_1_0_, consumer0_.consumer_auth_type as consumer3_1_0_, consumer0_.comments as comments4_1_0_, consumer0_.consumer_app_director as consumer5_1_0_, consumer0_.consumer_app_manager as consumer6_1_0_, consumer0_.consumer_app_vp as consumer7_1_0_, consumer0_.carbon_namespace_ownership as carbon_n8_1_0_, consumer0_.consumer_hosted_on as consumer9_1_0_, consumer0_.hosted_vm_ownership as hosted_10_1_0_, consumer0_.consumer_status as consume11_1_0_, consumer0_.consumer_system_type as consume12_1_0_, consumer0_.consumer_tps as consume13_1_0_ from consumer_table consumer0_ where consumer0_.api_name=? and consumer0_.consumer_cmdb=?
2022-07-13 21:13:25.444 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [a1]
2022-07-13 21:13:25.445 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [cm1]
2022-07-13 21:13:25.811 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([api_name1_1_0_] : [VARCHAR]) - [a1]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer2_1_0_] : [VARCHAR]) - [cm1]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer3_1_0_] : [VARCHAR]) - [cat4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([comments4_1_0_] : [VARCHAR]) - [cm4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer5_1_0_] : [VARCHAR]) - [cd4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer6_1_0_] : [VARCHAR]) - [capm4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer7_1_0_] : [VARCHAR]) - [cap4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([carbon_n8_1_0_] : [VARCHAR]) - []
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consumer9_1_0_] : [VARCHAR]) - [ch4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([hosted_10_1_0_] : [VARCHAR]) - [chvm4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consume11_1_0_] : [VARCHAR]) - [cs4]
2022-07-13 21:13:25.812 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consume12_1_0_] : [VARCHAR]) - [cst4]
2022-07-13 21:13:25.813 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicExtractor : extracted value ([consume13_1_0_] : [VARCHAR]) - [null]
2022-07-13 21:13:25.818 DEBUG [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] org.hibernate.SQL : update consumer_table set consumer_auth_type=?, comments=?, consumer_app_director=?, consumer_app_manager=?, consumer_app_vp=?, carbon_namespace_ownership=?, consumer_hosted_on=?, hosted_vm_ownership=?, consumer_status=?, consumer_system_type=?, consumer_tps=? where api_name=? and consumer_cmdb=?
Hibernate: update consumer_table set consumer_auth_type=?, comments=?, consumer_app_director=?, consumer_app_manager=?, consumer_app_vp=?, carbon_namespace_ownership=?, consumer_hosted_on=?, hosted_vm_ownership=?, consumer_status=?, consumer_system_type=?, consumer_tps=? where api_name=? and consumer_cmdb=?
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [cat4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [cm5]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [cd4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [capm4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [VARCHAR] - [cap4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [VARCHAR] - []
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [7] as [VARCHAR] - [ch4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [8] as [VARCHAR] - [chvm4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [9] as [VARCHAR] - [cs4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [10] as [VARCHAR] - [cst4]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [11] as [VARCHAR] - [null]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [12] as [VARCHAR] - [a1]
2022-07-13 21:13:25.819 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [13] as [VARCHAR] - [cm1]
2022-07-13 21:13:26.533 DEBUG [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] org.hibernate.SQL : select provider0_.provider_cmdb as provider1_2_0_, provider0_.api_name as api_name2_2_0_, provider0_.provider_app_director as provider3_2_0_, provider0_.provider_app_vp as provider4_2_0_, provider0_.carbon_namespace_ownership as carbon_n5_2_0_, provider0_.comments as comments6_2_0_, provider0_.hosted_vm_ownership as hosted_v7_2_0_, provider0_.provider_status as provider8_2_0_, provider0_.upstream_service_hosted_on as upstream9_2_0_, provider0_.upstream_service_type as upstrea10_2_0_, provider0_.upstream_service_url as upstrea11_2_0_, provider0_.upstream_vm_ownership as upstrea12_2_0_ from provider_table provider0_ where provider0_.provider_cmdb=? and provider0_.api_name=? and provider0_.provider_app_director=? and provider0_.provider_app_vp=? and provider0_.carbon_namespace_ownership=? and provider0_.comments=? and provider0_.hosted_vm_ownership=? and provider0_.provider_status=? and provider0_.upstream_service_hosted_on=? and provider0_.upstream_service_type=? and provider0_.upstream_service_url=? and provider0_.upstream_vm_ownership=?
Hibernate: select provider0_.provider_cmdb as provider1_2_0_, provider0_.api_name as api_name2_2_0_, provider0_.provider_app_director as provider3_2_0_, provider0_.provider_app_vp as provider4_2_0_, provider0_.carbon_namespace_ownership as carbon_n5_2_0_, provider0_.comments as comments6_2_0_, provider0_.hosted_vm_ownership as hosted_v7_2_0_, provider0_.provider_status as provider8_2_0_, provider0_.upstream_service_hosted_on as upstream9_2_0_, provider0_.upstream_service_type as upstrea10_2_0_, provider0_.upstream_service_url as upstrea11_2_0_, provider0_.upstream_vm_ownership as upstrea12_2_0_ from provider_table provider0_ where provider0_.provider_cmdb=? and provider0_.api_name=? and provider0_.provider_app_director=? and provider0_.provider_app_vp=? and provider0_.carbon_namespace_ownership=? and provider0_.comments=? and provider0_.hosted_vm_ownership=? and provider0_.provider_status=? and provider0_.upstream_service_hosted_on=? and provider0_.upstream_service_type=? and provider0_.upstream_service_url=? and provider0_.upstream_vm_ownership=?
2022-07-13 21:13:26.534 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [pcm1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] - [a1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [p1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [p1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [VARCHAR] - [p1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [VARCHAR] - [pc5]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [7] as [VARCHAR] - [pw1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [8] as [VARCHAR] - [ps1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [9] as [VARCHAR] - [uh1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [10] as [VARCHAR] - [us1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [11] as [VARCHAR] - [us1]
2022-07-13 21:13:26.535 TRACE [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [12] as [VARCHAR] - [uo1]
2022-07-13 21:13:26.900 DEBUG [,ae80adb706f0a62d,ae80adb706f0a62d] 53825 --- [nio-8431-exec-3] org.hibernate.SQL : insert into provider_table (provider_cmdb, api_name, provider_app_director, provider_app_vp, carbon_namespace_ownership, comments, hosted_vm_ownership, provider_status, upstream_service_hosted_on, upstream_service_type, upstream_service_url, upstream_vm_ownership) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into provider_table (provider_cmdb, api_name, provider_app_director, provider_app_vp, carbon_namespace_ownership, comments, hosted_vm_ownership, provider_status, upstream_service_hosted_on, upstream_service_type, upstream_service_url, upstream_vm_ownership) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
As the service layer isn't given based on the question i would like to answer,considering providerRepository object is present
Provider provider=providerRepository.findByUpstreamServiceUrl("xyz"); //Assuming using this method
provider.setXYZ(..);///set the values needed to be updated
providerRepository.save(provider); // As JPA works on state of an object this would update the object instead in inserting in DB
As ID of Object is present in DB instead of inserting new it will merge by calling save method
Refer:How do I update an entity using spring-data-jpa?
#Modifying annotation is used to enhance the #Query annotation so that we can execute not only SELECT queries, also insert, update, delete, and even DDL queries.
For more detail go through this link.
You can also use #Modifying and #Query to write your custom JPA query
to update the Provider table.
#Modifying
#Query("your custom JPQL update query")
What you can also do is get the previous provider entity/data you want to update and do the changes in the same data and again save it.
I got the issue.Actually in Provider class , I was annotating with wrong class. I have made the changes and now It's working fine :)
Here is the latest Provider entity class
#Data
#Entity
#Table(name = "provider_table")
#IdClass(ProviderId.class)
public class Provider implements Serializable {
#Id
#Column(name = "api_name")
private String apiName;
#Id
#Column(name = "provider_cmdb")
private String providerCMDB;
#Column(name = "provider_app_vp")
private String providerAppVp;
#Column(name = "provider_app_director")
private String providerAppDirector;
#Column(name = "upstream_service_hosted_on")
private String upstreamServiceHost;
#Column(name = "upstream_service_url")
private String upstreamServiceUrl;
#Column(name = "upstream_vm_ownership")
private String upstreamVmOwnership;
#Column(name = "upstream_service_type")
private String upstreamServiceType;
#Column(name = "carbon_namespace_ownership")
private String providerCarbonNamespaceOwnership;
#Column(name = "hosted_vm_ownership")
private String providerHostedVmOwnership;
#Column(name = "provider_status")
private String providerStatus;
#Column(name = "comments")
private String providerComments;
}
Related
Hibernate JPA - Wrongly generated insert statement
Hibernate is generating wrong insert statement - wrong column binding - for the following entity model with single table inheritance and composite primary key using #IdClass. Wondering if this is a Hibernate bug. Stack: Spring Boot 2.7 / H2 Superclass base entity - AbstractMemberEvent: #Entity #Table(name = "MEMBER_EVENTS") #Getter #FieldDefaults(level = AccessLevel.PRIVATE) #Inheritance(strategy = InheritanceType.SINGLE_TABLE) #DiscriminatorColumn(name = "EVENT_TYPE") #NoArgsConstructor #IdClass(MemberEventId.class) public abstract class AbstractMemberEvent { #Id #Column(name = "USID") String usid; #Id #Column(name = "UPDATED") Long eventTime; #Id #Column(name = "EVENT_TYPE", insertable = false, updatable = false ) String eventType; Subclass entity - NewMemberJoined #Entity #Getter #Setter #FieldDefaults(level = AccessLevel.PRIVATE) #DiscriminatorValue("NEWMEMBERJOINED") #NoArgsConstructor public class NewMemberJoined extends AbstractMemberEvent{ #Column(name="PAYLOAD") NewMemberJoinedInfo newMemberJoinedInfo; The IdClass #Getter #FieldDefaults(level = AccessLevel.PRIVATE) #NoArgsConstructor #EqualsAndHashCode public class MemberEventId implements Serializable { String usid; Long eventTime; String eventType; } From the logs I see that the wrong values are bound to the parameters Hibernate: create table member_events ( event_type varchar(31) not null, updated bigint not null, usid varchar(255) not null, payload varchar(255), primary key (updated, event_type, usid) ) ... Hibernate: insert into member_events (payload, event_type, updated, usid) values (?, ?, ?, ?) 2022-11-25 21:52:13.789 DEBUG 527088 --- [ restartedMain] tributeConverterSqlTypeDescriptorAdapter : Converted value on binding : ... 2022-11-25 21:52:13.790 TRACE 527088 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [{"firstName":"Jasper" ...}] 2022-11-25 21:52:13.790 TRACE 527088 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BIGINT] - [1388534400000] 2022-11-25 21:52:13.790 TRACE 527088 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [NEWMEMBERJOINED] 2022-11-25 21:52:13.790 TRACE 527088 --- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [3060001234567] 2022-11-25 21:52:13.794 WARN 527088 --- [ restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 22018, SQLState: 22018 2022-11-25 21:52:13.794 ERROR 527088 --- [ restartedMain] o.h.engine.jdbc.spi.SqlExceptionHelper : Data conversion error converting "'NEWMEMBERJOINED' (MEMBER_EVENTS: ""UPDATED"" BIGINT NOT NULL)"; SQL statement: insert into member_events (payload, event_type, updated, usid) values (?, ?, ?, ?) [22018-214]7'
Error of "Duplicate entry '14' for key 'dishes.PRIMARY'" When saving a value in DB via Json file
I have a problem saving a row in the "Orders" table. Each order includes a list of dishes. When I saved through the code everything was fine. But when I send a JSON file, I see that Spring sends an update command to the DISH table. And I do not understand why, how can he be made not to update the value obtained? this is the orders class: #Data #NoArgsConstructor #AllArgsConstructor #Builder #Entity #Table(name="Orders") public class Orders { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private int orderId; #Column(name="customer_name") private String customerName; #ElementCollection #ManyToMany(mappedBy ="Orders",cascade = CascadeType.MERGE) #JoinColumn(name = "id") private List<Dish> dish; #Column(name="order_date") private Date orderDate; #Enumerated(value = EnumType.ORDINAL) #Column(name = "status_id") private Status status; #Enumerated(value = EnumType.ORDINAL) #Column(name = "table_id") private RTable table; #ManyToOne #JoinColumn(name = "waiter_id") private Waiter waiter; #Column(name="total_price") private double totalPrice; The Dish class: #Data #NoArgsConstructor #AllArgsConstructor #Builder #Entity #Table(name="dishes") public class Dish{ #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; #Column(name="preperation_Time_By_Minutes") private double preperationTimeByMinutes; private double price; } part from the trace: (including the unwanted update query) Hibernate: insert into orders (customer_name, order_date, status_id, table_id, total_price, waiter_id) values (?, ?, ?, ?, ?, ?) 2022-05-23 16:05:20.398 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [null] 2022-05-23 16:05:20.398 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [TIMESTAMP] - [Sun Nov 05 02:00:00 IST 2023] 2022-05-23 16:05:20.398 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [INTEGER] - [1] 2022-05-23 16:05:20.398 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [INTEGER] - [2] 2022-05-23 16:05:20.399 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [DOUBLE] - [0.0] 2022-05-23 16:05:20.399 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [INTEGER] - [null] 2022-05-23 16:05:20.404 DEBUG 19712 --- [nio-8080-exec-6] org.hibernate.SQL : update dishes set id=? where id=? Hibernate: update dishes set id=? where id=? 2022-05-23 16:05:20.404 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [INTEGER] - [14] 2022-05-23 16:05:20.405 TRACE 19712 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [INTEGER] - [1] 2022-05-23 16:05:20.406 WARN 19712 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000 2022-05-23 16:05:20.406 ERROR 19712 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '14' for key 'dishes.PRIMARY' 2022-05-23 16:05:20.406 INFO 19712 --- [nio-8080-exec-6] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2022-05-23 16:05:20.409 ERROR 19712 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [dishes.PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '14' for key 'dishes.PRIMARY' .... ...... .........
JPA #MapsId inserts 0 instead of correct value
I have these entities (unnecessary columns removed for brevity) Order #Entity #Table(name = "orders") public class Order { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private int id; #OneToOne(mappedBy = "order", cascade = CascadeType.ALL, optional = false) private Shipment shipment; public int getId() { return id; } public void setId(int id) { this.id = id; } public Shipment getShipment() { return shipment; } public void setShipment(Shipment shipment) { this.shipment = shipment; this.shipment.setOrder(this); } } Shipment #Entity #Table(name = "shipments") public class Shipment { #Id #Column(name = "order_id") private int id; #OneToOne #MapsId private Order order; #OneToOne(mappedBy = "shipment", cascade = CascadeType.ALL, optional = false) private ShippingAddress shippingAddress; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; this.shippingAddress.setShipment(this); } } ShippingAddress #Entity #Table(name = "shipping_address") public class ShippingAddress { #Id #Column(name = "shipment_id") private int id; #OneToOne #MapsId("shipment_id") private Shipment shipment; public int getId() { return id; } public void setId(int id) { this.id = id; } public Shipment getShipment() { return shipment; } public void setShipment(Shipment shipment) { this.shipment = shipment; } } The problem arises when I attempt to save a new Order. As you can see from the logs, Hibernate correctly sets the values to the Order and Shipment entities but assigns 0 to the shipment_id column in shipping_address, which of course causes a FK conflict. I believe I'm using #MapsId correctly, because like I said, it works for the Order and Shipment relationship, but it doesn't seem to work for the Shipment and ShippingAddress. These are the logs 2021-01-14 14:25:56,563 DEBUG [http-nio-8080-exec-3] org.hibernate.SQL: insert into orders (branch_office, coupon_code, customer_id, external_id, increment_id, interests, origin_channel, store_id, subtotal, total, total_discount, total_qty_ordered) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [1] as [VARCHAR] - [null] 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [2] as [VARCHAR] - [null] 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [3] as [INTEGER] - [20] 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [4] as [VARCHAR] - [5501505642] 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [5] as [VARCHAR] - [5501505642] 2021-01-14 14:25:56,564 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [6] as [NUMERIC] - [0.0000] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [7] as [VARCHAR] - [store] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [8] as [INTEGER] - [55] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [9] as [NUMERIC] - [2270.0000] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [10] as [NUMERIC] - [1580] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [11] as [NUMERIC] - [690] 2021-01-14 14:25:56,565 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [12] as [INTEGER] - [3] 2021-01-14 14:25:56,621 DEBUG [http-nio-8080-exec-3] org.hibernate.SQL: insert into shipments (carrier_id, pickup_id, shipment_id, shipping_cost, order_id) values (?, ?, ?, ?, ?) 2021-01-14 14:25:56,621 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [1] as [INTEGER] - [19] 2021-01-14 14:25:56,622 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [2] as [INTEGER] - [19] 2021-01-14 14:25:56,622 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [3] as [INTEGER] - [null] 2021-01-14 14:25:56,622 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [4] as [NUMERIC] - [0.0] 2021-01-14 14:25:56,622 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [5] as [INTEGER] - [20] 2021-01-14 14:25:56,623 DEBUG [http-nio-8080-exec-3] org.hibernate.SQL: insert into shipping_address (city, country_code, province_id, street_name, street_number, zip_code, shipment_id) values (?, ?, ?, ?, ?, ?, ?) 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [1] as [VARCHAR] - [Vicente López] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [2] as [VARCHAR] - [AR] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [3] as [INTEGER] - [21] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [4] as [VARCHAR] - [ramon melgar,Nro 8170] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [5] as [VARCHAR] - [] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [6] as [VARCHAR] - [1638] 2021-01-14 14:25:56,624 TRACE [http-nio-8080-exec-3] org.hibernate.type.descriptor.sql.BasicBinder: binding parameter [7] as [INTEGER] - [0] As you can see on the last insert, Hibernate attempts to insert a 0 instead of the shipment_id. Is there something I'm missing?
According to the documentation the value of the #MapsId annotation is referred to the name of the attribute within the composite key to which the relationship attribute corresponds. You do not use composite key. So, this: #OneToOne #MapsId("shipment_id") private Shipment shipment; should be corrected to this: #OneToOne #MapsId #JoinColumn(name = "shipment_id") private Shipment shipment; I can not find proof in the documentation, but hibernate ignore #Column(name = "shipment_id") on #Id when you use #MapsId, so you should specify PK column name of the ShippingAddress by adding #JoinColumn.
HttpMessageNotWritableException: Could not write JSON: Could not initialize proxy AFTER adding data into DB
Here's my question. I am unable to write the JSON after I send a POST request from POSTMAN to create/add a row into my SQL database. I need the server to send back a response of the added entry in order to retrieve the ID that SQL generates. I face this issue when the new Case entry is a child of two entities(User and Application) and a grandchild of one entity(Owner). *User(Owner) |\ | *Application |/ *Case I'm new and currently using the Spring Boot JPA package. I'm aware that many have asked questions related to the error above. There is none regarding my case to my knowledge. All of them refer to fixes over a HTTP GET method. If you found some please guide me to them. Or please help to answer my query. Any help is appreciated! I attach my codes here: User Entity package com.lightlce.CRUD.Entities; import javax.persistence.*; #Entity(name = "User") #Table(name = "User", schema = "dbo") public class User { #Id #GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; private String staffId; private String username; private String role; public User (){} public User(Integer id, String staffId, String username, String role) { this.id = id; this.staffId = staffId; this.username = username; this.role = role; } // Getters and Setters } Application Entity package com.lightlce.CRUD.Entities; import javax.persistence.*; #Entity(name = "Application") #Table(name = "InvApplication", schema = "dbo") public class Application { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String applicationName; #ManyToOne(fetch = FetchType.LAZY) #JoinColumn(name = "ownerId") private User owner; public Application(){} public Application(Integer id, String applicationName, User owner) { this.id = id; this.applicationName = applicationName; this.owner = owner; } // Getters and Setters } Case Entity package com.lightlce.CRUD.Entities; import com.lightlce.CRUD.AuditModel.Auditable; import javax.persistence.*; #Entity(name = "Case") #Table(name = "InvCase", schema = "dbo") public class Case extends Auditable { #Id #GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; #ManyToOne(fetch = FetchType.LAZY) #JoinColumn(name = "userId") private User user; #ManyToOne(fetch = FetchType.LAZY) #JoinColumn(name = "applicationId") private Application application; //redacted public Case() { } public Case(Integer id, User user, Application application) { this.id = id; this.user = user; this.application = application; } // Getters and Setters } Case Controller package com.lightlce.CRUD.Controllers; import com.lightlce.CRUD.Entities.Application; import com.lightlce.CRUD.Entities.Case; import com.lightlce.CRUD.Entities.User; import com.lightlce.CRUD.Repository.ApplicationRepository; import com.lightlce.CRUD.Repository.CaseRepository; import com.lightlce.CRUD.Repository.UserRepository; import com.lightlce.CRUD.Services.ApplicationService; import com.lightlce.CRUD.Services.CaseService; import com.lightlce.CRUD.Services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; #RestController public class CaseController { #Autowired private CaseService caseService; #Autowired private UserService userService; #Autowired private ApplicationRepository applicationRepository; #Autowired private UserRepository userRepository; #Autowired private CaseRepository caseRepository; #Autowired private UserController userController; #RequestMapping("cases") public Page<Case> getAllCases(Pageable pageable) { return caseService.getAllCases(pageable); } #PostMapping("cases/add") public Case addCase(#RequestBody Case aCase) { User staff = userService.searchUser(aCase.getUser()); //Finds the user based on ID provided Application application = applicationRepository.findById(aCase.getApplication().getId()).get(); //Finds the application based on ID provided aCase.setUser(staff); aCase.setApplication(application); return caseService.addCase(aCase); } } Case Service package com.lightlce.CRUD.Services; import com.fasterxml.jackson.annotation.JsonIgnore; import com.lightlce.CRUD.Entities.Application; import com.lightlce.CRUD.Entities.Case; import com.lightlce.CRUD.Entities.User; import com.lightlce.CRUD.Repository.CaseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.List; #Service public class CaseService { #Autowired private CaseRepository caseRepository; #Autowired private UserService userService; public Page<Case> getAllCases(Pageable pageable){ return caseRepository.customFindAll(pageable); } public Case addCase(Case aCase) { caseRepository.save(aCase); return aCase; } } Case Repository package com.lightlce.CRUD.Repository; import com.lightlce.CRUD.Entities.Case; import com.lightlce.CRUD.Entities.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.List; import java.util.Optional; #Repository public interface CaseRepository extends JpaRepository<Case, Integer>{ Page<Case> findAll(Pageable pageable); #Query(value = "SELECT c FROM com.lightlce.CRUD.Entities.Case c " + "JOIN FETCH c.user u " + "JOIN FETCH c.application a " + "JOIN FETCH a.owner o", countQuery = "SELECT COUNT(c) FROM com.lightlce.CRUD.Entities.Case c " + "JOIN c.user u " + "JOIN c.application a " + "JOIN a.owner o") Page<Case> customFindAll(Pageable pageable); } POST http://localhost:8080/cases/add { "user": { "staffId": "TEST123" }, "application":{ "id": 2 } } Expected Response { "created_at": "2020-05-13T09:34:04.093+0000", "modified_at": "2020-05-13T09:34:04.093+0000", "id": 1 "user": { "id": 1, "staffId": "TEST123", "username": "lightlce", "role": "admin" }, "application": { "id": 2, "applicationName": "ApplicationDemo", "owner": { "id": 1, "staffId": "TEST123", "username": "lightlce", "role": "admin" } } } Postman Exception { "timestamp": "2020-05-14T02:36:40.999+0000", "status": 500, "error": "Internal Server Error", "message": "Could not write JSON: could not initialize proxy [com.lightlce.CRUD.Entities.User#2] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.lightlce.CRUD.Entities.User#2] - no Session (through reference chain: com.lightlce.CRUD.Entities.Case[\"application\"]->com.lightlce.CRUD.Entities.Application[\"owner\"]->com.lightlce.CRUD.Entities.User$HibernateProxy$QRpaILkJ[\"staffId\"])", "path": "/cases/add" } Springboot Logs 2020-05-14 10:36:38.262 DEBUG 50878 --- [nio-8080-exec-6] org.hibernate.SQL : select user0_.id as id1_0_, user0_.role as role2_0_, user0_.staffId as staffId3_0_, user0_.username as username4_0_ from dbo.InvAllUser user0_ where user0_.staffId=? Hibernate: select user0_.id as id1_0_, user0_.role as role2_0_, user0_.staffId as staffId3_0_, user0_.username as username4_0_ from dbo.InvAllUser user0_ where user0_.staffId=? 2020-05-14 10:36:38.278 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [TEST123] 2020-05-14 10:36:38.808 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([id1_0_] : [INTEGER]) - [1] 2020-05-14 10:36:38.811 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([role2_0_] : [VARCHAR]) - [admin] 2020-05-14 10:36:38.812 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([staffId3_0_] : [VARCHAR]) - [TEST123] 2020-05-14 10:36:38.812 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([username4_0_] : [VARCHAR]) - [lightlce] 2020-05-14 10:36:38.837 DEBUG 50878 --- [nio-8080-exec-6] org.hibernate.SQL : select applicatio0_.id as id1_1_0_, applicatio0_.applicationName as applicat2_1_0_, applicatio0_.ownerId as ownerId3_1_0_ from dbo.InvApplication applicatio0_ where applicatio0_.id=? Hibernate: select applicatio0_.id as id1_1_0_, applicatio0_.applicationName as applicat2_1_0_, applicatio0_.ownerId as ownerId3_1_0_ from dbo.InvApplication applicatio0_ where applicatio0_.id=? 2020-05-14 10:36:38.839 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [INTEGER] - [2] 2020-05-14 10:36:39.427 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([applicat2_1_0_] : [VARCHAR]) - [ApplicationDemo] 2020-05-14 10:36:39.427 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicExtractor : extracted value ([ownerId3_1_0_] : [INTEGER]) - [2] 2020-05-14 10:36:39.546 DEBUG 50878 --- [nio-8080-exec-6] org.hibernate.SQL : insert into dbo.InvCase (created_at, modified_at, applicationId, approverId, caseDesc, caseTitle, caseType, status, userId) values (?, ?, ?, ?, ?, ?, ?, ?, ?) Hibernate: insert into dbo.InvCase (created_at, modified_at, applicationId, approverId, caseDesc, caseTitle, caseType, status, userId) values (?, ?, ?, ?, ?, ?, ?, ?, ?) 2020-05-14 10:36:39.553 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [TIMESTAMP] - [Thu May 14 10:36:39 SGT 2020] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [TIMESTAMP] - [Thu May 14 10:36:39 SGT 2020] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [INTEGER] - [2] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [INTEGER] - [1] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [VARCHAR] - [ApplicationDemo] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [6] as [VARCHAR] - [TEST123] 2020-05-14 10:36:39.555 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [7] as [VARCHAR] - [new] 2020-05-14 10:36:39.556 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [8] as [VARCHAR] - [Pending] 2020-05-14 10:36:39.557 TRACE 50878 --- [nio-8080-exec-6] o.h.type.descriptor.sql.BasicBinder : binding parameter [9] as [INTEGER] - [1] 2020-05-14 10:36:40.987 WARN 50878 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [com.lightlce.CRUD.Entities.User#2] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.lightlce.CRUD.Entities.User#2] - no Session (through reference chain: com.lightlce.CRUD.Entities.Case["application"]->com.lightlce.CRUD.Entities.Application["owner"]->com.lightlce.CRUD.Entities.User$HibernateProxy$QRpaILkJ["staffId"])]
There are as many problems with your code as i really don't know how to help to solve it. but as a quick fix try to create a new entity class for user object.
Solved it with this workaround. Since fooService.save(foo); also updates the foo object with the ID, I can simply return foo.getId() to achieve what I want without sending another find method. i.e. Case Service public Integer updateCase(Case aCase) { caseRepository.save(aCase); return aCase.getId(); }
How to update an item in one to many relationship
I am trying to update a one to many relationship but getting a insert into sw_standard_standard (sw_standard_id, standard_id) values (?, ?) [23505-192]]; nested exception is org.hibernate.exception.ConstraintViolationException Here is my code: SwStandard #Entity public class SwStandard implements Serializable { #Id #GeneratedValue(strategy = GenerationType.TABLE) private Long id; #OneToOne private DeviceType deviceType; #ElementCollection #OneToMany private List<Image> standard; #ElementCollection #OneToMany private List<Image> limited; #ElementCollection #OneToMany private List<Image> exception; public SwStandard() {} public SwStandard(DeviceType deviceType, List<Image> standard, List<Image> limited, List<Image> exception) { this.deviceType = deviceType; this.standard = standard; this.limited = limited; this.exception = exception; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public DeviceType getDeviceType() { return deviceType; } public void setDeviceType(DeviceType deviceType) { this.deviceType = deviceType; } public List<Image> getStandard() { return standard; } public void setStandard(List<Image> standard) { this.standard = standard; } public List<Image> getLimited() { return limited; } public void setLimited(List<Image> limited) { this.limited = limited; } public List<Image> getException() { return exception; } public void setException(List<Image> exception) { this.exception = exception; } } Image #Entity public class Image implements Serializable { #Id #GeneratedValue(strategy = GenerationType.TABLE) private Long id; private String name; public Image() {} public Image(String name) { this.name = name; } public Image(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Update code: #RequestMapping(value = "/swstandard/update", method = RequestMethod.POST) public SwStandard updateSwStandard(#RequestBody SwStandard request) { return swService.save(request); } SwService: #Autowired private SwStandardRepository swService; SwStandardRepository: public interface SwStandardRepository extends CrudRepository<SwStandard, Long> { SwStandard findByDeviceTypeId(Long id); } First I save a SwStandard with 1 standard item. Then I save want to replace the standard item with something else. When I do this it returns the error above. Edit Alan Hay help partially helped. Now I cannot save the same image across a SwStandard for example here is a SwStandard I'll save: { "id": 1, "deviceType": { "id": 1 }, "standard": [{"id": 1}], "limited": [], "exception": [] } and here is another SwStandard I'll save which will fail with the error above: { "id": 2, "deviceType": { "id": 2 }, "standard": [{"id": 1}], "limited": [], "exception": [] } As you can see both SwStandards have the same standard item. Here is the log output: 2016-11-08 16:19:12.060 INFO 15668 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2016-11-08 16:19:12.060 INFO 15668 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2016-11-08 16:19:12.092 INFO 15668 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms 2016-11-08 16:19:12.255 WARN 15668 --- [nio-8080-exec-1] org.hibernate.orm.deprecation : HHH90000015: Found use of deprecated [org.hibernate.id.MultipleHiLoPerTableGenerator] table-based id generator; use org.hibernate.id.enhanced.TableGenerator instead. See Hibernate Domain Model Mapping Guide for details. 2016-11-08 16:19:12.255 DEBUG 15668 --- [nio-8080-exec-1] org.hibernate.SQL : select sequence_next_hi_value from hibernate_sequences where sequence_name = 'sw_standard' for update 2016-11-08 16:19:12.256 DEBUG 15668 --- [nio-8080-exec-1] org.hibernate.SQL : insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('sw_standard', ?) 2016-11-08 16:19:12.258 DEBUG 15668 --- [nio-8080-exec-1] org.hibernate.SQL : update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'sw_standard' 2016-11-08 16:19:12.262 DEBUG 15668 --- [nio-8080-exec-1] org.hibernate.SQL : insert into sw_standard (device_type_id, id) values (?, ?) 2016-11-08 16:19:12.262 TRACE 15668 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [1] 2016-11-08 16:19:12.262 TRACE 15668 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BIGINT] - [1] 2016-11-08 16:19:12.264 DEBUG 15668 --- [nio-8080-exec-1] org.hibernate.SQL : insert into sw_standard_standard (sw_standard_id, standard_id) values (?, ?) 2016-11-08 16:19:12.270 TRACE 15668 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [1] 2016-11-08 16:19:12.271 TRACE 15668 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BIGINT] - [1] 2016-11-08 16:19:22.162 WARN 15668 --- [nio-8080-exec-2] org.hibernate.orm.deprecation : HHH90000015: Found use of deprecated [org.hibernate.id.MultipleHiLoPerTableGenerator] table-based id generator; use org.hibernate.id.enhanced.TableGenerator instead. See Hibernate Domain Model Mapping Guide for details. 2016-11-08 16:19:22.163 DEBUG 15668 --- [nio-8080-exec-2] org.hibernate.SQL : insert into sw_standard (device_type_id, id) values (?, ?) 2016-11-08 16:19:22.164 TRACE 15668 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [2] 2016-11-08 16:19:22.164 TRACE 15668 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BIGINT] - [2] 2016-11-08 16:19:22.165 DEBUG 15668 --- [nio-8080-exec-2] org.hibernate.SQL : insert into sw_standard_standard (sw_standard_id, standard_id) values (?, ?) 2016-11-08 16:19:22.166 TRACE 15668 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [2] 2016-11-08 16:19:22.166 TRACE 15668 --- [nio-8080-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [BIGINT] - [1] 2016-11-08 16:19:22.169 WARN 15668 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 23505, SQLState: 23505 2016-11-08 16:19:22.169 ERROR 15668 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Unique index or primary key violation: "UK_QM6PF2T2PB3DLYYLV44TQL40J_INDEX_2 ON PUBLIC.SW_STANDARD_STANDARD(STANDARD_ID) VALUES (1, 1)"; SQL statement: insert into sw_standard_standard (sw_standard_id, standard_id) values (?, ?) [23505-192] 2016-11-08 16:19:22.172 INFO 15668 --- [nio-8080-exec-2] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2016-11-08 16:19:22.194 ERROR 15668 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["UK_QM6PF2T2PB3DLYYLV44TQL40J_INDEX_2 ON PUBLIC.SW_STANDARD_STANDARD(STANDARD_ID) VALUES (1, 1)"; SQL statement: insert into sw_standard_standard (sw_standard_id, standard_id) values (?, ?) [23505-192]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause