I just started a new project and would like to use Sprint Boot 2.1 and ran into a problem at the very beginning. What I would like to do is use Spring Boot Mongo to manage the database. I would like to have an optimistic lock with #Version annotation. However, I found that it seems like #Version would affect the save() behavior in MongoRepository, which means, dup key error.
The following is the sample code.
POJO
#Data
#AllArgsConstructor
#NoArgsConstructor
#Document
public class Person {
#Id public ObjectId id;
#CreatedDate public LocalDateTime createOn;
#LastModifiedDate public LocalDateTime modifiedOn;
#Version public long version;
private String name;
private String email;
public Person(String name, String email) {
this.name = name;
this.email = email;
}
#Override
public String toString() {
return String.format("Person [id=%s, name=%s, email=%s, createdOn=%s, modifiedOn=%s, version=%s]", id, name, email, createOn, modifiedOn, version);
}
}
MongoConfig
#Configuration
#EnableMongoRepositories("com.project.server.repo")
#EnableMongoAuditing
public class MongoConfig {
}
Repository
public interface PersonRepo extends MongoRepository<Person, ObjectId> {
Person save(Person person);
Person findByName(String name);
Person findByEmail(String email);
long count();
#Override
void delete(Person person);
}
As indicated in Official Doc, I have my version field in long, but the dup key error occurs at the second save, which means it tried to insert again, even with the id in the object.
I also tried with Long in version field, which has no dup key occurred and save as update as expected, but the createdOn become null in the first save (which means insert)
Controller
Person joe = new Person("Joe", "aa#aa.aa");
System.out.println(joe.toString());
this.personRepo.save(joe);
Person who = this.personRepo.findByName("Joe");
System.out.println(who.toString());
who.setEmail("bb#bb.bb");
this.personRepo.save(who);
Person who1 = this.personRepo.findByName("Joe");
Person who2 = this.personRepo.findByEmail("bb#bb.bb");
System.out.println(who1.toString());
System.out.println(who2.toString());
log with dup key (long version)
2018-11-11 02:09:31.435 INFO 4319 --- [on(6)-127.0.0.1] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:186}] to localhost:27017
Person [id=null, name=Joe, email=aa#aa.aa, createdOn=null, modifiedOn=null, version=0]
2018-11-11 02:09:37.254 DEBUG 4319 --- [nio-8080-exec-1] o.s.data.auditing.AuditingHandler : Touched Person [id=null, name=Joe, email=aa#aa.aa, createdOn=2018-11-11T02:09:37.252, modifiedOn=2018-11-11T02:09:37.252, version=0] - Last modification at 2018-11-11T02:09:37.252 by unknown
2018-11-11 02:09:37.259 DEBUG 4319 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : Inserting Document containing fields: [createOn, modifiedOn, version, name, email, _class] in collection: person
2018-11-11 02:09:37.297 DEBUG 4319 --- [nio-8080-exec-1] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "name" : "Joe" }, Fields: { }, Sort: { }
2018-11-11 02:09:37.304 DEBUG 4319 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : find using query: { "name" : "Joe" } fields: Document{{}} for class: class com.seedu.server.model.Person in collection: person
Person [id=5be71ee11ad34410df06852c, name=Joe, email=aa#aa.aa, createdOn=2018-11-11T02:09:37.252, modifiedOn=2018-11-11T02:09:37.252, version=0]
2018-11-11 02:09:37.323 DEBUG 4319 --- [nio-8080-exec-1] o.s.data.auditing.AuditingHandler : Touched Person [id=5be71ee11ad34410df06852c, name=Joe, email=bb#bb.bb, createdOn=2018-11-11T02:09:37.323, modifiedOn=2018-11-11T02:09:37.323, version=0] - Last modification at 2018-11-11T02:09:37.323 by unknown
2018-11-11 02:09:37.324 DEBUG 4319 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : Inserting Document containing fields: [_id, createOn, modifiedOn, version, name, email, _class] in collection: person
org.springframework.dao.DuplicateKeyException: E11000 duplicate key error collection: seedu.person index: _id_ dup key: { : ObjectId('5be71ee11ad34410df06852c') }; nested exception is com.mongodb.MongoWriteException: E11000 duplicate key error collection: seedu.person index: _id_ dup key: { : ObjectId('5be71ee11ad34410df06852c') }
log with createdDate null (Long version)
2018-11-11 02:07:28.858 INFO 4310 --- [on(6)-127.0.0.1] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:183}] to localhost:27017
Person [id=null, name=Joe, email=aa#aa.aa, createdOn=null, modifiedOn=null, version=null]
2018-11-11 02:07:31.519 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.auditing.AuditingHandler : Touched Person [id=null, name=Joe, email=aa#aa.aa, createdOn=null, modifiedOn=2018-11-11T02:07:31.518, version=0] - Last modification at 2018-11-11T02:07:31.518 by unknown
2018-11-11 02:07:31.525 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : Inserting Document containing fields: [modifiedOn, version, name, email, _class] in collection: person
2018-11-11 02:07:31.564 DEBUG 4310 --- [nio-8080-exec-1] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "name" : "Joe" }, Fields: { }, Sort: { }
2018-11-11 02:07:31.571 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : find using query: { "name" : "Joe" } fields: Document{{}} for class: class com.seedu.server.model.Person in collection: person
Person [id=5be71e631ad34410d6a3b123, name=Joe, email=aa#aa.aa, createdOn=null, modifiedOn=2018-11-11T02:07:31.518, version=0]
2018-11-11 02:07:31.590 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.auditing.AuditingHandler : Touched Person [id=5be71e631ad34410d6a3b123, name=Joe, email=bb#bb.bb, createdOn=null, modifiedOn=2018-11-11T02:07:31.590, version=1] - Last modification at 2018-11-11T02:07:31.590 by unknown
2018-11-11 02:07:31.598 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : Calling update using query: { "_id" : { "$oid" : "5be71e631ad34410d6a3b123" }, "version" : { "$numberLong" : "0" } } and update: { "modifiedOn" : { "$date" : 1541873251590 }, "version" : { "$numberLong" : "1" }, "name" : "Joe", "email" : "bb#bb.bb", "_class" : "com.seedu.server.model.Person" } in collection: person
2018-11-11 02:07:31.602 DEBUG 4310 --- [nio-8080-exec-1] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "name" : "Joe" }, Fields: { }, Sort: { }
2018-11-11 02:07:31.602 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : find using query: { "name" : "Joe" } fields: Document{{}} for class: class com.seedu.server.model.Person in collection: person
2018-11-11 02:07:31.603 DEBUG 4310 --- [nio-8080-exec-1] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "email" : "bb#bb.bb" }, Fields: { }, Sort: { }
2018-11-11 02:07:31.604 DEBUG 4310 --- [nio-8080-exec-1] o.s.data.mongodb.core.MongoTemplate : find using query: { "email" : "bb#bb.bb" } fields: Document{{}} for class: class com.seedu.server.model.Person in collection: person
Person [id=5be71e631ad34410d6a3b123, name=Joe, email=bb#bb.bb, createdOn=null, modifiedOn=2018-11-11T02:07:31.590, version=1]
Person [id=5be71e631ad34410d6a3b123, name=Joe, email=bb#bb.bb, createdOn=null, modifiedOn=2018-11-11T02:07:31.590, version=1]
As I know, the spring use id existence as the save behavior control, which means if the id exists then save would be like the insert for mongo. However, in here, version seems also affect the save behavior or affect the way that spring recognize the id existence.
Question: How can I use MongoAudit with MongoRepository together? Is there any mistake/bug I made?
For working with #Version, You have to retrieve the data model first from the database and after updating the data, you have to save the same data to the database.
For example:
personRepo.findByName(name).ifPresent(person-> {
person.setEmail("email#gamil.com");
personRepo.save(person);
log.info("Updated Data: {}", person);
});
#CreatedDate will always be null if you didn't add the #Version to your model class. It works with #Version
One more point to add here if you didn't add #Version to your model class and you're trying to update the same with having model class #Version, it will again give you duplicate id error.
I still can't figure out the problem. However, even though I have the exactly the same setting as the post above, since I upgrade Spring Boot from 2.1.0 to 2.1.1, everything works fine now(no matter what type of version I am using, Long/long)
Following is the library version I'm using right now.
spring-boot-starter-data-mongodb:2.1.1.RELEASE:
-> spring-data-mongo:2.1.3.RELEASE
-> mongodb-driver:3.8.2
Related
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'
I am currently learning spring cloud microservices and I follow a really simple example.
So I have 2 services 1 for currency exchange and 1 for currency conversion. those two services talk to each other using 'resttemplate', however, when I try to get an object from currency exchange service I get all fields apart from the integer one, which return 0.
Beans:
CurrencyExchange:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class CurrencyExchange {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "currency_from")
private String from;
#Column(name = "currency_to")
private String to;
private int convertionMultiple;
private String environment;
CurrencyConversion:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class CurrencyConversion {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "from_currency")
private String from;
#Column(name = "to_currency")
private String to;
private int conversionMultiple;
private int quantity;
private int totalCalculatedAmount;
private String environment;
}
Controllers:
CurrencyExchange Controller:
#RestController
#RequestMapping("/exchange")
public class exchangeCurrencyController {
#Autowired
private Environment environment;
#Autowired
private CurrencyExchangeService currencyExchangeService;
#GetMapping("/currency-exchange/from/{from}/to/{to}")
public CurrencyExchange exchangeCurrency(#PathVariable String from, #PathVariable String to) {
CurrencyExchange currencyExchange = currencyExchangeService.findByFromAndTo(from, to);
String port = environment.getProperty("local.server.port");
System.out.println(currencyExchange);
currencyExchange.setEnvironment(port);
return currencyExchange;
}
CurrencyConversion Controller:
#RestController
#RequestMapping("/conversion")
public class CurrencyConversionController {
#GetMapping("/currency-conversion/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversion getCurrencyConversion(#PathVariable String from, #PathVariable String to, #PathVariable int quantity) {
HashMap<String, String> uriVariables = new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
ResponseEntity<CurrencyConversion> responseEntity = new RestTemplate().getForEntity("http://localhost:8000/exchange/currency-exchange/from/{from}/to/{to}", CurrencyConversion.class, uriVariables);
CurrencyConversion currencyConversion1 = responseEntity.getBody();
System.out.println(currencyConversion1);
return new CurrencyConversion(currencyConversion1.getId(), currencyConversion1.getFrom(), currencyConversion1.getTo(), currencyConversion1.getConversionMultiple(), quantity, currencyConversion1.getConversionMultiple(), currencyConversion1.getEnvironment());
}
}
I have 3 object in my data base.
id conversion_multiple environment currency_from currency_to
1 12 8000 AUS ILS
2 65 8000 USD ILS
3 424 8000 INR ILS
**Web debuging log:
ExchangeCurrency Class:
2021-12-16 21:39:00.550 DEBUG 6648 --- [nio-8000-exec-3] o.s.web.servlet.DispatcherServlet : GET "/exchange/currency-exchange/from/USD/to/ILS", parameters={}
2021-12-16 21:39:00.551 DEBUG 6648 --- [nio-8000-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.in28minutes.microservices.currencyexchangeservice.controllers.exchangeCurrencyController#exchangeCurrency(String, String)
2021-12-16 21:39:00.552 DEBUG 6648 --- [nio-8000-exec-3] org.hibernate.SQL : select currencyex0_.id as id1_0_, currencyex0_.conversion_multiple as conversi2_0_, currencyex0_.environment as environm3_0_, currencyex0_.currency_from as currency4_0_, currencyex0_.currency_to as currency5_0_ from currency_exchange currencyex0_ where currencyex0_.currency_from=? and currencyex0_.currency_to=?
2021-12-16 21:39:00.557 DEBUG 6648 --- [nio-8000-exec-3] org.hibernate.SQL : select currencyex0_.id as id1_0_, currencyex0_.conversion_multiple as conversi2_0_, currencyex0_.environment as environm3_0_, currencyex0_.currency_from as currency4_0_, currencyex0_.currency_to as currency5_0_ from currency_exchange currencyex0_ where currencyex0_.currency_from=? and currencyex0_.currency_to=?
PrintCurrencyExchange{id=2, from='USD', to='ILS', convertionMultiple=65, environment='8000'}
2021-12-16 21:39:00.561 DEBUG 6648 --- [nio-8000-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2021-12-16 21:39:00.562 DEBUG 6648 --- [nio-8000-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Writing [CurrencyExchange{id=2, from='USD', to='ILS', convertionMultiple=65, environment='8000'}]
2021-12-16 21:39:00.564 DEBUG 6648 --- [nio-8000-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK
CurrencyConversion Class**
2021-12-16 21:37:39.776 DEBUG 10736 --- [nio-8100-exec-9] o.s.web.servlet.DispatcherServlet : GET "/conversion/currency-conversion-feign/from/USD/to/ILS/quantity/1123123", parameters={}
2021-12-16 21:37:39.777 DEBUG 10736 --- [nio-8100-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.in28minutes.microservices.currencyconversionservice.controllers.CurrencyConversionController#getCurrencyConversionFeign(String, String, int)
2021-12-16 21:37:39.795 DEBUG 10736 --- [nio-8100-exec-9] o.s.w.c.HttpMessageConverterExtractor : Reading to [com.in28minutes.microservices.currencyconversionservice.beans.CurrencyConversion]
CurrencyConversion(id=2, from=USD, to=ILS, conversionMultiple=0, quantity=0, totalCalculatedAmount=0, environment=8000)
2021-12-16 21:37:39.798 DEBUG 10736 --- [nio-8100-exec-9] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json;q=0.8', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json]
2021-12-16 21:37:39.798 DEBUG 10736 --- [nio-8100-exec-9] m.m.a.RequestResponseBodyMethodProcessor : Writing [CurrencyConversion(id=2, from=USD, to=ILS, conversionMultiple=0, quantity=1123123, totalCalculatedAm (truncated)...]
2021-12-16 21:37:39.800 DEBUG 10736 --- [nio-8100-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK
when I print to console the response. I get
CurrencyConversion(id=2, from=USD, to=ILS, conversionMultiple=0, quantity=0, totalCalculatedAmount=0, environment=8000)
which shows String returning but int showing 0.
help me understand this.
THANKS
you need to add a #Column configuration:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class CurrencyExchange {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "currency_from")
private String from;
#Column(name = "currency_to")
private String to;
#Column(name = "conversion_multiple")
private int convertionMultiple;
private String environment;
}
otherwise Spring does not know which column to load the data from as the field name does not match your column name.
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();
}
I'm getting around 10 errors when I start my Spring Boot app using Hibernate and postgresql. How can I fix them? WHat's the problem?
Here are my entities:
Customer.java
#Entity
#Access(AccessType.FIELD) // so I can avoid using setters for fields that won't change
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long customerId;
#Embedded
private FirstName firstName;
#Embedded
private LastName lastName;
#Embedded
private PhoneNumber phoneNumber;
#ManyToOne
#JoinColumn(name = "ADDRESS_ID")
private Address address;
#OneToOne
#JoinColumn(name = "USER_ID")
private User user;
// jpa requirement
public Customer() {
}
public Customer(FirstName firstName, LastName lastName,
PhoneNumber phoneNumber, Address address, User user) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.address = address;
this.user = user;
}
public Long getCustomerId() {
return customerId;
}
public FirstName getFirstName() {
return firstName;
}
public LastName getLastName() {
return lastName;
}
public PhoneNumber getPhoneNumber() {
return phoneNumber;
}
// setter for phone number is needed because customer can change his phone number
public void setPhoneNumber(PhoneNumber phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Address getAddress() {
return address;
}
// setter for address is needed because customer can change his address
public void setAddress(Address address) {
this.address = address;
}
public User getUser() {
return user;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Customer customer = (Customer) o;
if (firstName != null ? !firstName.equals(customer.firstName) : customer.firstName != null) {
return false;
}
if (lastName != null ? !lastName.equals(customer.lastName) : customer.lastName != null) {
return false;
}
return user != null ? user.equals(customer.user) : customer.user == null;
}
#Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (user != null ? user.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Customer{" +
"firstName=" + firstName +
", lastName=" + lastName +
", phoneNumber=" + phoneNumber +
'}';
}
}
User.java
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
#Embedded
private EmailAddress emailAddress;
#Embedded
private Password password;
#OneToOne
#JoinColumn(name = "CUSTOMER_ID")
private Customer customer;
#Column
#Enumerated(EnumType.STRING)
private UserRole userRole;
// jpa requirement
public User() {
}
public User(EmailAddress emailAddress, Password password) {
this.emailAddress = emailAddress;
this.password = password;
this.userRole = UserRole.USER; // on creation everyone is just a user
}
public Long getUserId() {
return userId;
}
public EmailAddress getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
public Password getPassword() {
return password;
}
public void setPassword(Password password) {
this.password = password;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(UserRole userRole) {
this.userRole = userRole;
}
}
And Book.java:
#Entity
#Access(AccessType.FIELD) // so I can avoid using setters for fields that won't change
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;
#Embedded
private Isbn isbn;
#Embedded
private Title title;
#Embedded
private Author author;
#Embedded
private Genre genre;
private Year publicationYear;
private BigDecimal price;
// jpa requirement
public Book() {
}
public Book(Isbn isbn, Title title, Author author, Genre genre, Year publicationYear,
BigDecimal price) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.genre = genre;
this.publicationYear = publicationYear;
this.price = price;
}
public Long getBookId() {
return bookId;
}
public Isbn getIsbn() {
return isbn;
}
public Title getTitle() {
return title;
}
public Author getAuthor() {
return author;
}
public Genre getGenre() {
return genre;
}
public BigDecimal getPrice() {
return price;
}
public Year getPublicationYear() {
return publicationYear;
}
// setter for price is needed because price of the book can change (discounts and so on)
public void setPrice(BigDecimal price) {
this.price = price;
}
}
My application.properties for postgresql settings:
spring.datasource.url= jdbc:postgresql://localhost:5432/bookrest
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create-drop
And here is the stack trace for hibernate part (ommitted all the controoller mapping):
2017-02-27 11:03:05.481 INFO 6563 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-02-27 11:03:05.555 INFO 6563 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-02-27 11:03:05.556 INFO 6563 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-02-27 11:03:05.558 INFO 6563 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-02-27 11:03:05.609 INFO 6563 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-02-27 11:03:05.819 INFO 6563 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-02-27 11:03:05.997 INFO 6563 --- [ restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-02-27 11:03:05.999 INFO 6563 --- [ restartedMain] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#c866efb
2017-02-27 11:03:06.228 WARN 6563 --- [ restartedMain] org.hibernate.orm.deprecation : HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.
2017-02-27 11:03:06.580 INFO 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-02-27 11:03:06.584 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table customer drop constraint FKglkhkmh2vyn790ijs6hiqqpi
2017-02-27 11:03:06.584 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: relation "customer" does not exist
2017-02-27 11:03:06.584 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table customer drop constraint FKidmyb2vdwmk3o502u0rg8g32h
2017-02-27 11:03:06.585 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: relation "customer" does not exist
2017-02-27 11:03:06.585 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table user drop constraint FK2q989f4c89rv2b9xvtomfc0fs
2017-02-27 11:03:06.586 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: syntax error at or near "user"
Position: 13
2017-02-27 11:03:06.587 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: drop table if exists user cascade
2017-02-27 11:03:06.587 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: syntax error at or near "user"
Position: 22
2017-02-27 11:03:06.588 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: drop sequence hibernate_sequence
2017-02-27 11:03:06.588 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: sequence "hibernate_sequence" does not exist
2017-02-27 11:03:06.607 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: create table user (user_id bigserial not null, email_address varchar(255), password varchar(255), user_role varchar(255), customer_customer_id int8, primary key (user_id))
2017-02-27 11:03:06.607 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: syntax error at or near "user"
Position: 14
2017-02-27 11:03:06.610 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table customer add constraint FKidmyb2vdwmk3o502u0rg8g32h foreign key (user_user_id) references user
2017-02-27 11:03:06.610 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: syntax error at or near "user"
Position: 103
2017-02-27 11:03:06.610 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table user add constraint FK2q989f4c89rv2b9xvtomfc0fs foreign key (customer_customer_id) references customer
2017-02-27 11:03:06.610 ERROR 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: syntax error at or near "user"
Position: 13
2017-02-27 11:03:06.611 INFO 6563 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-02-27 11:03:06.673 INFO 6563 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
EDIT 1:
After changing my User to AppUser (table name user is prohibited) I'm still getting few errors:
2017-02-27 11:45:44.253 INFO 9560 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-02-27 11:45:44.255 INFO 9560 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-02-27 11:45:44.256 INFO 9560 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-02-27 11:45:44.298 INFO 9560 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-02-27 11:45:44.621 INFO 9560 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2017-02-27 11:45:44.825 INFO 9560 --- [ restartedMain] o.h.e.j.e.i.LobCreatorBuilderImpl : HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
2017-02-27 11:45:44.828 INFO 9560 --- [ restartedMain] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#35c0ac4e
2017-02-27 11:45:45.370 INFO 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-02-27 11:45:45.373 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table app_user drop constraint FKf8cjd2mkc4tu1u5nhju0clae7
2017-02-27 11:45:45.374 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: relation "app_user" does not exist
2017-02-27 11:45:45.374 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table customer drop constraint FKglkhkmh2vyn790ijs6hiqqpi
2017-02-27 11:45:45.374 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: relation "customer" does not exist
2017-02-27 11:45:45.375 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000389: Unsuccessful: alter table customer drop constraint FKslkyb5dphxe4c7au3hqx3la6m
2017-02-27 11:45:45.375 ERROR 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: relation "customer" does not exist
2017-02-27 11:45:45.408 INFO 9560 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-02-27 11:45:45.467 INFO 9560 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
user is a reserved keyword in postgresql. I would suggest renaming your entity class to some other name, or just use hibernate annotations #Table to specify postgresql friendly table name, like this:
#Entity
#Table(name = "library_user")
public class User {...}
User is reserved word in most if not all of the databases. Use some other name for this purpose.
Words
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