Model mapper Converter failed to convert Object to java.lang.Integer with java.lang.NullPointerException - spring-boot

perhaps someone can give me an insite. Ok i have Purchase Entity with nested Transaction set of Entities. What i'm trying to do is convert additional DTO property Integer paymentStatus using custom method but getting NullPointerException for ModelMapper Converter
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "purchase")
public class Purchase {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "purchase_id", nullable = false)
private Integer purchaseId;
#Column(name = "purchase_total_cost")
private Double purchaseTotalCost;
#Column(name = "purchase_company_id", nullable = false)
private Integer purchaseCompanyId;
#Column(name = "purchase_user_id", nullable = false)
private Integer purchaseUserId;
#Column(name = "purchase_stock_id", nullable = false)
private Integer purchaseStockId;
#Column(name = "purchase_supplier_contact_id")
private Integer purchaseSupplierContactId;
#Column(name = "purchase_supplier_id")
private Integer purchaseSupplierId;
#Column(name = "purchase_inventory_id")
private Integer purchaseInventoryId;
#Column(name = "purchase_date")
private LocalDateTime purchaseDate;
#Column(name = "date_created")
#CreationTimestamp
public LocalDateTime dateCreated;
#Column(name = "date_updated")
#UpdateTimestamp
public LocalDateTime dateUpdated;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne
#JoinColumn(name = "purchase_user_id", referencedColumnName = "user_id", insertable = false, updatable = false)
private User purchaseUser;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne
#JoinColumn(name = "purchase_stock_id", referencedColumnName = "stock_id", insertable = false, updatable = false)
private Stock purchaseStock;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne
#JoinColumn(name = "purchase_supplier_id", referencedColumnName = "supplier_id", insertable = false, updatable = false)
private Supplier purchaseSupplier;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "purchase_supplier_contact_id", referencedColumnName = "contact_id", insertable = false, updatable = false)
private SupplierContact purchaseSupplierContact;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne
#JoinColumn(name = "purchase_company_id", referencedColumnName = "company_id", insertable = false, updatable = false)
private Company purchaseCompany;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#ManyToOne
#JoinColumn(name = "purchase_inventory_id", referencedColumnName = "inventory_id", insertable = false, updatable = false)
private Inventory purchaseInventory;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#OneToMany(fetch = FetchType.LAZY,
mappedBy = "costLogPurchase")
#Cascade({org.hibernate.annotations.CascadeType.MERGE,
org.hibernate.annotations.CascadeType.DELETE,
org.hibernate.annotations.CascadeType.REMOVE
})
private Set<CostLog> purchaseCostLogs;
#ToString.Exclude
#EqualsAndHashCode.Exclude
#OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "ingredientPurchase")
private Set<PurchaseHasIngredient> purchaseIngredients;
// #ToString.Exclude
#EqualsAndHashCode.Exclude
#OneToMany(fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "transactionPurchase")
private Set<Transaction> purchaseTransactions;
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "transaction")
public class Transaction {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "transaction_id", nullable = false)
private Integer transactionId;
#Column(name = "transaction_status")
private Byte transactionStatus;
#Column(name = "transaction_amount", nullable = false)
private Double transactionAmount;
#Column(name = "transaction_code", length = 100)
private String transactionCode;
#Column(name = "transaction_payment_point_id")
private Integer transactionPaymentPointId;
#Column(name = "transaction_user_id")
private Integer transactionUserId;
#Column(name = "transaction_order_id")
private Integer transactionOrderId;
#Column(name = "transaction_purchase_id")
private Integer transactionPurchaseId;
#Column(name = "transaction_date")
public LocalDateTime transactionDate;
#Column(name = "date_created")
#CreationTimestamp
public LocalDateTime dateCreated;
#Column(name = "date_updated")
#UpdateTimestamp
public LocalDateTime dateUpdated;
#EqualsAndHashCode.Exclude
#ToString.Exclude
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "transaction_payment_point_id", referencedColumnName = "payment_point_id", insertable = false, updatable = false)
private PaymentPoint transactionPaymentPoint;
#EqualsAndHashCode.Exclude
#ToString.Exclude
#ManyToOne
#JoinColumn(name = "transaction_user_id", referencedColumnName = "user_id", insertable = false, updatable = false)
private User transactionUser;
#EqualsAndHashCode.Exclude
#ToString.Exclude
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
#JoinColumn(name = "transaction_order_id", referencedColumnName = "order_id", insertable = false, updatable = false)
private Order transactionOrder;
#EqualsAndHashCode.Exclude
#ToString.Exclude
#ManyToOne(fetch = FetchType.EAGER)
#Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
#JoinColumn(name = "transaction_purchase_id", referencedColumnName = "purchase_id", insertable = false, updatable = false)
private Purchase transactionPurchase;
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class TransactionDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer transactionId;
private Byte transactionStatus;
private Double transactionAmount;
private String transactionCode;
private Integer transactionPaymentPointId;
private String transactionPaymentPointName;
private Integer transactionUserId;
private String transactionUserName;
private Integer transactionOrderId;
private Integer transactionPurchaseId;
public LocalDateTime transactionDate;
public LocalDateTime dateCreated;
public LocalDateTime dateUpdated;
}
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class PurchaseDTO {
private static final long serialVersionUID = 1L;
private Integer purchaseId;
private Integer purchaseUserId;
private String purchaseUserName;
private Integer purchaseCompanyId;
private Integer purchaseStockId;
private String purchaseStockName;
private Integer purchaseSupplierId;
private String purchaseSupplierName;
private Integer paymentStatus; // this is additional property
private Integer purchaseInventoryId;
private Double purchaseTotalCost;
private Integer purchaseSupplierContactId;
private LocalDateTime purchaseDate;
private LocalDateTime dateCreated;
private LocalDateTime dateUpdated;
private Set<PurchaseHasIngredientDTO> purchaseIngredients;
private Set<TransactionDTO> purchaseTransactions;
#Configuration
public class ModelMapperConfig {
#Bean
public ModelMapper modelMapper() {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setPreferNestedProperties(false)
.setSkipNullEnabled(true)
.setMatchingStrategy(MatchingStrategies.STANDARD);
mapper.createTypeMap(Purchase.class, PurchaseDTO.class)
.addMappings(purchaseDTOPropertyMapUsingPaymentStatusConverter);
return mapper;
}
PropertyMap<Purchase, PurchaseDTO> purchaseDTOPropertyMapUsingPaymentStatusConverter = new PropertyMap<>() {
#Override
protected void configure() {
using(ctx->mapSpecificFields(source.getPurchaseTransactions(), source.getPurchaseTotalCost())).
map(source, destination.getPaymentStatus());
}
};
public Integer mapSpecificFields(Set<Transaction> set, Double total) {
int b;
if(set==null){
b = 0;
}
double result = 0;
for(Transaction transaction: set) {
double sum = transaction.getTransactionAmount();
sum++;
result = sum/total;
}
if(result==0){
b=0;
}else if (result==1){
b=2;
}else{
b=1;
}
return b;
}
}
#Service
public class PurchaseService extends EntityMapperService<PurchaseDTO, Purchase> implements EntityService<Purchase> {
#PersistenceContext
private EntityManager entityManager;
private final PurchaseRepository repository;
private final PurchaseHasIngredientRepository purchaseIngredientsRepository;
private final ModelMapper mapper;
#Override
public PurchaseDTO toDto(Purchase entity) {
return Objects.isNull(entity)
? null
: mapper.map(entity, PurchaseDTO.class);
}
}
test set up
#SpringBootTest
class PurchaseServiceTest {
#Autowired
private ModelMapper mapper;
#Autowired
private PurchaseService service;
Transaction t1;
Transaction t2;
Set<Transaction> transactions;
TransactionDTO td1;
TransactionDTO td2;
Set<TransactionDTO> transactionDTOS;
Purchase purchase;
PurchaseDTO dto;
#BeforeEach
void setUp() {
t1 = Transaction.builder()
.transactionId(11)
.transactionAmount(12.00)
.transactionPurchaseId(1)
.build();
t2 = Transaction.builder()
.transactionId(12)
.transactionAmount(10.00)
.transactionPurchaseId(1)
.build();
transactions = Sets.newHashSet(t1,t2);
td1 = TransactionDTO.builder()
.transactionPurchaseId(1)
.transactionId(11)
.transactionAmount(12.00)
.build();
td2 = TransactionDTO.builder()
.transactionId(12)
.transactionPurchaseId(1)
.transactionAmount(10.00)
.build();
transactionDTOS = Sets.newHashSet(td1,td2);
purchase = Purchase.builder()
.purchaseId(1)
.purchaseCompanyId(2)
.purchaseUserId(3)
.purchaseStockId(4)
.purchaseTransactions(transactions)
.purchaseTotalCost(22.00)
.build();
dto = PurchaseDTO.builder()
.purchaseId(1)
.purchaseUserId(3)
.purchaseCompanyId(2)
.purchaseStockId(4)
.paymentStatus(0)
.purchaseTotalCost(22.00)
.purchaseTransactions(transactionDTOS)
.build();
}
#DisplayName("JUnit test for toDto method for <Purchase, PurchaseDTO> typemap using paymentStatus converter")
#Test
void toDtoUsingConverterForPurchaseTypeMap() {
PurchaseDTO testedDto = service.toDto(purchase);
assertThat(testedDto).isEqualTo(dto);
}
}
stack trace of error
org.modelmapper.MappingException: ModelMapper mapping errors:
1) Converter com.hrc.hrcweb.ModelMapperConfig$1$$Lambda$1240/0x00000008013e8ea0#5f5efbfc failed to convert com.hrc.hrcweb.entities.Purchase to java.lang.Integer.
1 error
at org.modelmapper.internal.Errors.throwMappingExceptionIfErrorsExist(Errors.java:380)
at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:80)
at org.modelmapper.ModelMapper.mapInternal(ModelMapper.java:573)
at org.modelmapper.ModelMapper.map(ModelMapper.java:406)
at com.hrc.hrcweb.servises.PurchaseService.toDto(PurchaseService.java:139)
at com.hrc.hrcweb.servises.PurchaseService$$FastClassBySpringCGLIB$$ffc82405.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386)
at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704)
at com.hrc.hrcweb.servises.PurchaseService$$EnhancerBySpringCGLIB$$485f630d.toDto(<generated>)
at com.hrc.hrcweb.servises.PurchaseServiceTest.toDtoUsingConverterForPurchaseTypeMap(PurchaseServiceTest.java:93)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.NullPointerException: Cannot invoke "com.hrc.hrcweb.entities.Purchase.getPurchaseTransactions()" because "this.source" is null
at com.hrc.hrcweb.ModelMapperConfig$1.lambda$configure$0(ModelMapperConfig.java:68)
at org.modelmapper.internal.MappingEngineImpl.convert(MappingEngineImpl.java:306)
at org.modelmapper.internal.MappingEngineImpl.setDestinationValue(MappingEngineImpl.java:243)
at org.modelmapper.internal.MappingEngineImpl.propertyMap(MappingEngineImpl.java:187)
at org.modelmapper.internal.MappingEngineImpl.typeMap(MappingEngineImpl.java:151)
at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:105)
at org.modelmapper.internal.MappingEngineImpl.map(MappingEngineImpl.java:71)
... 77 more
What am i doing wrong?

After meny hours, i couldn't find any solution to map additional properties or map some expressions to perform some custom calculations for DTO objects properties using model mapper, i had to switch to Mapstuct for these kind of operations, it has some nice custom mapping of target property to expression=java(anymethod) and u can use any method to map target, it's very convenient. example perhaps someone will find this information usefull.
I solved everything with this piece of code
#Mapping(target = "paymentStatus", expression = "java(getPaymentStatus(purchase))")
PurchaseDTO toDto(Purchase purchase);
and this custom method calculating status
default Integer getPaymentStatus(Purchase purchase){
Integer status;
if(purchase.getPurchaseTransactions()==null){
status = 0;
}
double result = 0;
double sum = 0;
double total = purchase.getPurchaseTotalCost();
for(Transaction transaction: purchase.getPurchaseTransactions()) {
sum += transaction.getTransactionAmount();
result = sum/total;
}
if(result==0){
status=0;
}else if (result==1){
status=2;
}else{
status=1;
}
return status;
}

Related

Spring Data persisting Phantom Child with Null value - not null property references a null or transient value

I have the following Entities in my Project:
#Getter
#Setter
#Entity
#Table(uniqueConstraints = #UniqueConstraint(columnNames = { "purchaseId" }))
public class Purchase {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long purchaseId;
#Column(unique = true, nullable = false, length = 15)
private String purchaseNo;
#Column(nullable = false, length = 15)
private String batchCode;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "supplier.supplierId", foreignKey = #ForeignKey(name = "FK_purchase_supplier"), nullable = false)
private Supplier supplier;
#Column(nullable = false)
private LocalDate purchaseDate;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "purchaseId", nullable = false)
private List<PurchaseItem> purchaseItems;
private Double totalAmount;
#ManyToOne
#JoinColumn(name = "userId", nullable = false, foreignKey = #ForeignKey(name = "FK_invoice_purchases"))
private User staff;
#Column(length = 100)
private String remarks;
#Column(nullable = false, updatable = false)
#CreationTimestamp
private LocalDateTime createdAt;
private boolean isDeleted = false;
}
#Getter
#Setter
#Entity
#Table(uniqueConstraints = #UniqueConstraint(columnNames = {"purchaseItemId"}))
public class PurchaseItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long purchaseItemId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "purchaseId", insertable = false, updatable = false, foreignKey = #ForeignKey(name="FK_purchase_item"))
private Purchase purchase;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "productId", foreignKey = #ForeignKey(name="FK_product_item"), nullable = false)
private Product product;
private Double itemAmount;
#Column(nullable = false)
private Double quantity;
private Double itemTotalAmount;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn(foreignKey = #ForeignKey(name = "FK_purchacase_item_batch"))
private PurchaseProductBatch productPurchaseBatch;
public void setPurchaseProductBatch() {
PurchaseProductBatch productPurchaseBatch = new PurchaseProductBatch();
productPurchaseBatch.setProduct(this.product);
productPurchaseBatch.setQuantity(this.quantity);
productPurchaseBatch.setPurchaseItem(this);
this.productPurchaseBatch = productPurchaseBatch;
}
}
#Getter
#Setter
#Entity
#Table()
public class PurchaseProductBatch{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long productBatchId;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name = "productId", foreignKey = #ForeignKey(name = "FK_product_purch"))
private Product product;
private Double quantity;
#OneToOne(fetch = FetchType.EAGER)
#MapsId
private PurchaseItem purchaseItem;
private boolean isDeleted = false;
#OneToMany(cascade = CascadeType.PERSIST)
#JoinColumn(name = "productBatchId", foreignKey = #ForeignKey(name = "FK_purchase_batch_qty"))
private Set<InvoicePurchaseBatchQuantity> invoicePurchaseBatchQuantities;
}
During Purchase Insert, everything works fine. However, if I update the Purchase record in the database and add new PurchaseItem entry, I encounter the issue below:
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.be.entity.PurchaseItem.product; nested
I have debugged my application and I see that there is a Product instance inside all of the PurchaseItem. When I commented out the PurchaseProductBatch inside PurchaseItem, everything works fine so I conclude that it is the causing the issue. However, I don't understand how and why JPA seems to create phantom PurchaseItem Records with no value.
Also, if I only update an existing PurchaseItem entry in Purchase, I don't encounter any issues.

Need to save/update child 500 or more rows in parent-child relationship with-in 10sec using Spring-Data-JPA

I have a scenario where I need to save or update 500 or more item in postgres db within 10sec using spring-data-jpa. below are my domain and service class.
GroupingForm.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Table(name = "GroupingForm")
public class GroupingForm implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "grouping_form_id",unique = true, nullable = false)
private UUID groupingFormId;
#Column(name = "grouping_form_name")
private String groupingFormName;
#Column(name = "vid")
private String vid;
#Column(name = "vendor_name")
private String vendorName;
#Column(name = "hovbu")
private String hovbu;
#Column(name = "fid")
private String fid;
#Column(name = "factory_name")
private String factoryName;
#Column(name = "item_count")
private Integer itemCount;
#CreationTimestamp
#Column(name = "creation_date")
private Timestamp creationDate;
#Column(name = "created_by")
private String createdBy;
#UpdateTimestamp
#Column(name = "modified_date")
private Timestamp modifiedDate;
#Column(name = "modified_by")
private String modifiedBy;
#Column(name = "product_engineer")
private String productEngineer;
#Column(name = "status")
private String status;
#Column(name = "sourcing_type")
private String sourcingType;
#Column(name = "total_comments")
private Integer totalComments;
#Column(name = "factory_name_chinese")
private String factoryNameChinese;
#Column(name = "grouping_form_type")
private String groupingFormType;//to save as Product/transit/Product_transit
#Column(name = "ref_id")
private String refId;
#JsonManagedReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonManagedReference
#OneToMany(mappedBy = "groupingForm", cascade = CascadeType.ALL, orphanRemoval = true)
private List<TransitItemsMapping> transitItems = new ArrayList<>();
#Column(name = "pdf_status")
private String pdfStatus;
}
ProductItemsMapping.java
#Data
#Entity
#Table(name = "ProductItemsMapping")
public class ProductItemsMapping implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "product_item_id",unique = true, nullable = false)
private UUID productItemId;
#ToString.Exclude
#JsonBackReference
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "grouping_form_id")
private GroupingForm groupingForm;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(referencedColumnName = "dim_Item_ID",name = "item_id")
private Item item;
#Column(name ="item_relationship_id", insertable = false,updatable = false)
private String itemRelationshipId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "item_relationship_id",referencedColumnName = "dim_item_relationship_id")
private VendorFactoryItem vendorFactoryItem;
#Column(name = "edam_id")
private String edamId;
#Column(name = "model_number")
private String modelNumber;
#Column(name = "description")
private String description;
#Column(name = "material")
private String material;
#Column(name = "finishing_colour")
private String finishingColour;
#Column(name = "dimensions")
private String dimensions;
#Column(name = "product_net_weight")
private String productNetWeight;
#Column(name = "insertion_order")
private Integer insertionOrder;
#Column(name = "comments")
private String comments;
#Column(name = "item_unique_id")
private String itemUniqueId;
}
TransitItemsMapping.java
#Data
#Entity
#Table(name = "TransitItemsMapping")
public class TransitItemsMapping implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name = "uuid", strategy = "uuid2")
#GeneratedValue(generator = "uuid")
#Column(name = "transit_Item_id",unique = true, nullable = false)
private UUID transitItemId;
#ToString.Exclude
#JsonBackReference
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "grouping_form_id")
private GroupingForm groupingForm;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(referencedColumnName = "dim_Item_ID",name = "item_id")
private Item item;
#Column(name ="item_relationship_id", insertable = false,updatable = false)
private String itemRelationshipId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "item_relationship_id",referencedColumnName = "dim_item_relationship_id")
private VendorFactoryItem vendorFactoryItem;
#Column(name = "edam_id")
private String edamId;
#Column(name = "model_number")
private String modelNumber;
#Column(name = "description")
private String description;
#Column(name = "packaging_details")
private String packagingDetails;
#Column(name = "packaging_method")
private String packagingMethod;
#Column(name = "is_side_stack")
private String isSideStack;
#Column(name = "quantity")
private Integer quantity;
#Column(name = "dimensions")
private String dimensions;
#Column(name = "product_net_weight")
private String productNetWeight;
#Column(name = "plastic_bag_ind")
private String plasticBagInd;
#Column(name = "insertion_order")
private Integer insertionOrder;
#Column(name = "comments")
private String comments;
#Column(name = "item_unique_id")
private String itemUniqueId;
#Column(name = "itm_pak_qty")
private Integer itemPackQuantity;
}
Item.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Table(name = "Item")
public class Item implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//#GenericGenerator(name = "uuid", strategy = "uuid2")
//#GeneratedValue(generator = "uuid")
#JsonIgnore
#Column(name = "dim_Item_ID", unique = true, nullable = false)
private UUID dimItemId;
//mdm columns start
#Valid
#EmbeddedId
private ItemId itemId;
#Column(name = "model")
private String model;
#Column(name = "description")
private String description;
#CreationTimestamp
#Column(name="effective_date")
private Timestamp effectiveDate;
#JsonIgnore
#Column(name="expiration_date")
private Timestamp expirationDate;
#JsonIgnore
#Column(name="business_area_number")
private Integer businessAreaNumber;
#JsonIgnore
#Column(name="business_area_desc")
private String businessAreaDesc;
#JsonIgnore
#Column(name="division_number")
private Integer divisionNumber;
#JsonIgnore
#Column(name="division_desc")
private String divisionDesc;
#JsonIgnore
#Column(name="sub_division_number")
private Integer subDivisionNumber;
#JsonIgnore
#Column(name="sub_division_desc")
private String subDivisionDesc;
#JsonIgnore
#Column(name="product_group_number")
private Integer productGroupNumber;
#JsonIgnore
#Column(name="product_group_desc")
private String productGroupDesc;
#JsonIgnore
#Column(name="assortment")
private Integer assortment;
#JsonIgnore
#Column(name="assortment_desc")
private String assortmentDesc;
#JsonIgnore
#Column(name="status")
private Integer status;
#JsonIgnore
#Column(name="status_desc")
private String statusDesc;
#Column(name = "origin_country")
private String originCountry;
#Column(name = "destination_country")
private String destinationCountry;
#Column(name = "is_private_brand")
private String isPrivateBrand;
#Column(name = "brand")
private String brandName;
#Column(name = "item_weight")
private Double itemWeight;
#Column(name = "in_box_height")
private Double inBoxHeight;
#Column(name = "in_box_width")
private Double inBoxWidth;
#Column(name = "in_box_depth")
private Double inBoxDepth;
#Column(name = "primary_image")
private String primaryImage;
#Column(name = "component_materials")
private String componentMaterials;
#Column(name = "product_detail")
private String productDetail;
#Column(name = "finishing_color")
private String finishingColor;
#Column(name = "packaging_method")
private String packagingMethod;
#Column(name = "packaging_quantity")
private Integer packagingQuantity;
#Column(name = "out_box_depth")
private Double outBoxDepth;
#Column(name = "out_box_height")
private Double outBoxHeight;
#Column(name = "out_box_width")
private Double outBoxWidth;
#Column(name = "net_weight")
private Double netWeight;
#Column(name = "plastic_bag_ind")
private String plasticBagInd;
//mdm columns ends
//Adhoc specific start
#JsonIgnore
#Column(name="is_current")
private Integer isCurrent;
#JsonIgnore
#Column(name="remark")
private String remark;
#JsonIgnore
#Column(name="is_valid")
private String isValid;
#CreationTimestamp
#Column(name="creation_date")
private Timestamp creationDate;
#JsonIgnore
#Column(name="created_by")
private String createdBy;
#JsonIgnore
#UpdateTimestamp
#Column(name="last_modified_date")
private Timestamp lastModifiedDate;
#Column(name = "is_adhoc_item")
private String isAdhocItem;
//Adhoc specific ends
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<VendorFactoryItem> vendorFactoryItems;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "item")
private List<TransitItemsMapping> transitItems = new ArrayList<>();
#Transient
#JsonIgnore
private Integer itemNumber;
#Transient
#JsonIgnore
private String itemRelationshipId;
#Transient
#JsonIgnore
private String vendorId;
#Transient
#JsonIgnore
private String retailer;
#Transient
#JsonIgnore
private String fid;
#Transient
#JsonIgnore
private String hovbu;
#Column(name="sourcing_type")
private String sourcingType;
#Column(name = "itm_pak_qty")
private Integer itemPackQuantity;
#Column(name = "barcode")
private String barcode;
#Column(name = "item_type")
private String itemType;
#Column(name = "item_cube")
private String itemCube;
}
VendorFactoryItem.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode
#Entity
#Builder
#Table(name = "vendorfactoryitem")
public class VendorFactoryItem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private VendorFactoryItemId vendorFactoryItemId;
#JsonIgnore
#Column(name = "dim_item_relationship_id")
private String itemRelationshipId;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "hovbu",updatable = false,insertable = false),
#JoinColumn(name = "item_number",updatable = false,insertable = false),
#JoinColumn(name = "retailer",updatable = false,insertable = false)
})
private Item item;
#Column(name = "item_id")
private String itemIdRel;
#Column(name = "is_adhoc_rel")
private String isAdHocRel;
#Column(name = "dim_factory_import_id")
private String dimFactoryImportId;
#Column(name = "factory_short_name")
private String factoryShortName;
#Column(name = "company_id")
private String companyId;
#Column(name = "vendor_short_name")
private String vendorShortName;
#Column(name = "remark")
private String remark;
#Column(name = "is_valid")
private String isValid;
#Column(name = "created_on")
private Timestamp createdOn;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_date")
private Timestamp lastModifiedDate;
#Column(name = "effective_date")
private Timestamp effectiveDate;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "vendorFactoryItem")
private List<ProductItemsMapping> productItems = new ArrayList<>();
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL, mappedBy = "vendorFactoryItem")
private List<TransitItemsMapping> transitItems = new ArrayList<>();
}
GroupingFormRepository.java
#Repository
public interface GroupingFormRepository
extends JpaRepository<GroupingForm, UUID>, GroupingFormRepositoryCustom {
}
GroupingFormService.java
#Transactional
public GroupingFormDto saveGroupingFormV1(GroupingFormDto groupingFormDto) {
//do the mapping DTO to DOMAIN..remove the code ..
**GroupingForm groupingFormSaved = groupingFormRepository.save(groupingForm);**
}
With in the GroupingForm object I am setting the transitItem and productItem to save or update. And also adding Item and VendorfactoryItems not for save or update. what are the best way I can optimize this save and update with in 10 sec while I am passing more than 500 productItem and 500 transitItem.
Thanks in advance.

TransactionSystemException when #Scheduled is used

When I want to use #Scheduled, it throws org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
When I tried to use noRollbackFor=TransactionSystemException - it does not help either...
I even tried to use propagation=NEVER and then the code does not work,because it needs to be transactional. Iam getting those documents ok, but I cannot do blockDocument(document).
How to make it work?
Thank you in advance
#Component
public class ScheduleService {
#Autowired
private DocumentService documentService;
#Scheduled(cron = "0 33 13 * * ?")
public void blockPassedDocuments() {
List<Document> passedDocuments = documentService.getAllPassedDocuments();
if (passedDocuments != null) {
System.out.println("blocked docs "+ passedDocuments.size());
passedDocuments.forEach(document -> documentService.blockDocument(document));
}
}
}
#Service
#Transactional
public class DocumentService {
#Autowired
private DocumentRepository documentRepository;
#Autowired
private UserService userService;
#Autowired
private EmailService emailService;
#Transactional(noRollbackFor = TransactionSystemException.class)
public void blockDocument(Document document){
documentRepository.blockDocument(document);
}
// repository
#Override
public void blockDocument(Document document) {
DocumentState documentState = getDocumentState(3);
document.setDocumentState(documentState);
entityManager.merge(document);
}
#Entity
#Table(name = "document_state")
public class DocumentState {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotBlank(message = "State is mandatory")
#Size(min=1, max=60)
#Column(length = 60)
private String state;
#JsonIgnore
#OneToMany(mappedBy = "documentState", cascade= CascadeType.ALL)
private List<Document> documents;
public DocumentState(){
}
#Entity
public class Document {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(unique = true, length = 60, nullable = false)
#NotBlank(message = "Name is mandatory")
private String name;
#NotBlank(message = "Title is mandatory")
#Size(min = 3, max = 15)
#Column(length = 15, nullable = false)
private String title;
#NotBlank(message = "Description is mandatory")
#Size(min = 3, max = 255)
#Column(length = 255, nullable = false)
private String description;
#ManyToOne
#JoinColumn(name = "document_state_id", nullable = false)
private DocumentState documentState;
#JsonIgnore
#Column(name = "resource_path", length = 255, nullable = false)
private String resourcePath;
#Column(name = "upload_datetime", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "UploadDateTime is mandatory")
private Date uploadDatetime;
#Column(name = "approval_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Approval end time is mandatory")
private Date approvalEndTime;
#Column(name = "active_start_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active start time is mandatory")
private Date activeStartTime;
#Column(name = "active_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active end time is mandatory")
private Date activeEndTime;
#OneToMany(mappedBy = "document", cascade= CascadeType.ALL, orphanRemoval = true)
private Set<UsersDocuments> documentsForUsers = new HashSet<>();
#ManyToOne
#JoinColumn(name="user_id")
private User user;
public DocumentState getDocumentState() {
return documentState;
}
EDIT STACK:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:541) ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at com.patrikmaryska.bc_prace.bc_prace.service.ScheduleService$$EnhancerBySpringCGLIB$$68ed607b.blockPassedDocuments(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]
Add the #Transactional annotation on blockPassedDocuments method.
Add the #Transactional annotation on ScheduleService class.

How to fix Error ManyToMany in #RestController?

I'm an entity Story:
#Entity
#Table(name = "story", schema = "")
#Data
public class Story implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "sID", unique = true, nullable = false)
private Long sID;
#Column(name = "vnName", nullable = false)
private String vnName;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "_scategory",
joinColumns = {#JoinColumn(name = "sID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "cID", nullable = false)})
private List<Category> categoryList;
}
And Entity Category:
#Entity
#Table(name = "category", schema = "", uniqueConstraints = {#UniqueConstraint(columnNames = {"cMetatitle"}),
#UniqueConstraint(columnNames = {"cName"})})
#Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cID", unique = true, nullable = false)
private Integer cID;
#Column(name = "cName", unique = true, nullable = false, length = 150)
private String cName;
#ManyToMany(mappedBy = "categoryList")
private List<Story> storyList;
}
But when I grab the Story in RestController, I get the following error message:
WARN http-nio-8080-exec-9
o.s.w.s.m.s.DefaultHandlerExceptionResolver:234 - Failure while trying
to resolve exception
[org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the
response has been committed
Can anybody show me how to fix it? Thank you!

Spring JpaRepository manyToMany bidirectional should save instead of update

if got a language table and a system table with a many-to-many relationship:
Language:
#JsonAutoDetect
#Entity
#Table(name = "language")
public class Language implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "language_id", nullable = false)
private int languageId;
#Column(name = "language_name", nullable = false)
private String languageName;
#Column(name = "language_isocode", nullable = false)
private String languageIsoCode;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "system_language", joinColumns = {#JoinColumn(name = "language_id", updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "system_id", updatable = false)}, uniqueConstraints = {
#UniqueConstraint(columnNames = {
"language_id",
"system_id"
})})
private List<System> systems;
public Language() {
}
// GETTER & SETTERS
// ....
}
System
#JsonAutoDetect
#Entity
#Table(name = "system")
public class System implements Serializable {
#Id
#Column(name = "system_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer systemId;
#Column(name = "system_name", nullable = false, unique = true)
private String systemName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "university_id", nullable = false)
private University university;
#JoinColumn(name = "calender_id", nullable = false)
#OneToOne(fetch = FetchType.EAGER)
private Calendar calender;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<SystemUserRole> systemUserRoleList;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Role> roleList;
#OneToOne(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private CsmUserEntity csmUserEntity;
#ManyToMany(mappedBy = "systems")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Language> languages;
public System() {
}
// GETTER & SETTERS
// ....
}
When im writing a first dataset (systemId=1, language_id=20) into the table, everything works fine. But when i try to write a second dataset with the same language_id but with other system_id (systemId=2, language_id=20), then the existing dataset gets updated. But i want to have a new dataset instead. What can i do?
Thanks in advance!

Resources