java.lang.NoClassDefFoundError: Lorg/apache/myfaces/custom/fileupload/UploadedFile - maven

I want to upload files and show them in jsf page, for that I'm using tomahawk 1.1.12, jsf 2.0 and jpa 2, I'm following The BalusC tutorial but the project connot deploy and gives the error : java.lang.NoClassDefFoundError: Lorg/apache/myfaces/custom/fileupload/UploadedFile
pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maven.test</groupId>
<artifactId>mavenTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>oss.sonatype.org</id>
<name>OSS Sonatype Staging</name>
<url>https://oss.sonatype.org/content/groups/staging</url>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>apache-maven-snapshots</id>
<url>
http://people.apache.org/repo/m2-snapshot-repository
</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>myfaces-staging</id>
<url>
http://people.apache.org/builds/myfaces/m2-staging-repository
</url>
<releases>
<enabled>false</enabled>
<!--
Enable to test a MyFaces core release candidate with tomahawk
-->
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0-RC1</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>commonj.sdo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.11</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- <dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>-->
</dependencies>
</project>
my managed bean :
package mbeans;
//import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.faces.application.FacesMessage;
//import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
/*
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.commons.el.Logger;
//import org.apache.log4j.*;
//import org.apache.log4j.spi.LoggerFactory;
*/
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import daoImpl.DocDAO;
import entities.Document;
//import org.slf4j.*;
#ManagedBean
#RequestScoped
public class DocBean {
public DocDAO docDAO;
private Part file;
private String titreDocument;
private String descriptionDocument;
private String lien;
private String dateMise;
private String Categorie;
private Integer sizeDocument;
private String sousCategorie;
public DocBean(){
docDAO=new DocDAO();
}
private UploadedFile uploadedFile;
private String fileName;
// Actions ------------------------------------------------------------------------------------
public void submit() {
// Just to demonstrate what information you can get from the uploaded file.
System.out.println("File type: " + uploadedFile.getContentType());
System.out.println("File name: " + uploadedFile.getName());
System.out.println("File size: " + uploadedFile.getSize() + " bytes");
// Prepare filename prefix and suffix for an unique filename in upload folder.
String prefix = FilenameUtils.getBaseName(uploadedFile.getName());
String suffix = FilenameUtils.getExtension(uploadedFile.getName());
// Prepare file and outputstream.
File file = null;
OutputStream output = null;
try {
// Create file with unique name in upload folder and write to it.
file = File.createTempFile(prefix + "_", "." + suffix, new File("c:/data"));
output = new FileOutputStream(file);
IOUtils.copy(uploadedFile.getInputStream(), output);
fileName = file.getName();
// Show succes message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
} catch (IOException e) {
// Cleanup.
if (file != null) file.delete();
// Show error message.
FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
// Always log stacktraces (with a real logger).
e.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
}
}
// Getters ------------------------------------------------------------------------------------
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public String getFileName() {
return fileName;
}
// Setters ------------------------------------------------------------------------------------
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
//#EJB
//private DocDAO fileUploaderEJB;
//private final static Logger logger = LoggerFactory.getLogger(DocDAO.class);
//public void handleFileUpload(FileUploadEvent event) {
/* titreDocument = event.getFile().getFileName();
//String contentType = event.getFile().getContentType();
byte[] bytes = event.getFile().getContents();
Document garbage = new Document();
garbage.setDescriptionDocument(titreDocument);
garbage.setFile(bytes);
garbage.setDescriptionDocument("info about the file");
fileUploaderEJB.uploadGarbage(garbage);
//((Log) logger).info("Uploaded: {}");
FacesMessage msg = new FacesMessage("Succesful", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);*/
//}
public String upload() throws IOException{
file.write("C:\\data\\"+getFilename(file));
return"succes";
}
private static String getFilename(Part part){
for(String cd: part.getHeader("content-disposition").split(";")){
if(cd.trim().startsWith("filename")){
String filename=cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
/*public List<Document> getAlldoc(){
return docDAO.getAllDoc();
}
public String createdoc(){
docDAO.createDoc(titreDocument, descriptionDocument, sousCategorie, Categorie, sizeDocument, dateMise, lien);;
sizeDocument=null;
titreDocument="";
descriptionDocument="";
lien="";
sousCategorie="";
dateMise="";
Categorie="";
return "success";
}*/
public String getSousCategorie() {
return sousCategorie;
}
public void setSousCategorie(String sousCategorie) {
this.sousCategorie = sousCategorie;
}
public String getTitreDocument() {
return titreDocument;
}
public void setTitreDocument(String titreDocument) {
this.titreDocument = titreDocument;
}
public String getDescriptionDocument() {
return descriptionDocument;
}
public void setDescriptionDocument(String descriptionDocument) {
this.descriptionDocument = descriptionDocument;
}
public String getDateMise() {
return dateMise;
}
public void setDateMise(String dateMise) {
this.dateMise = dateMise;
}
public String getCategorie() {
return Categorie;
}
public void setCategorie(String categorie) {
Categorie = categorie;
}
public Integer getSizeDocument() {
return sizeDocument;
}
public void setSizeDocument(Integer sizeDocument) {
this.sizeDocument = sizeDocument;
}
public String getLien() {
return lien;
}
public void setLien(String lien) {
this.lien = lien;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
}
my entity :
package entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the document database table.
*
*/
#Entity
#Table(name="document")
#NamedQuery(name="Document.findAll", query="SELECT d FROM Document d")
public class Document {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="\"idDocument\"", unique=true, nullable=false)
private Integer idDocument;
#Column(length=45)
private String categorie;
#Column(name="\"dateMise\"", length=45)
private String dateMise;
#Column(name="\"descriptionDocument\"", length=60)
private String descriptionDocument;
#Lob
#Column
private byte[] file;
#Column(length=45)
private String lien;
#Column(name="\"sizeDocument\"")
private Integer sizeDocument;
#Column(name="\"sousCategorie\"", length=45)
private String sousCategorie;
#Column(name="\"titreDocument\"", length=45)
private String titreDocument;
public Document() {
}
public Integer getIdDocument() {
return this.idDocument;
}
public void setIdDocument(Integer idDocument) {
this.idDocument = idDocument;
}
public String getCategorie() {
return this.categorie;
}
public void setCategorie(String categorie) {
this.categorie = categorie;
}
public String getDateMise() {
return this.dateMise;
}
public void setDateMise(String dateMise) {
this.dateMise = dateMise;
}
public String getDescriptionDocument() {
return this.descriptionDocument;
}
public void setDescriptionDocument(String descriptionDocument) {
this.descriptionDocument = descriptionDocument;
}
public byte[] getFile() {
return this.file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getLien() {
return this.lien;
}
public void setLien(String lien) {
this.lien = lien;
}
public Integer getSizeDocument() {
return this.sizeDocument;
}
public void setSizeDocument(Integer sizeDocument) {
this.sizeDocument = sizeDocument;
}
public String getSousCategorie() {
return this.sousCategorie;
}
public void setSousCategorie(String sousCategorie) {
this.sousCategorie = sousCategorie;
}
public String getTitreDocument() {
return this.titreDocument;
}
public void setTitreDocument(String titreDocument) {
this.titreDocument = titreDocument;
}
}
and my web page xhtml:
<h:panelGrid columns="3">
<h:outputLabel for="file" value="Select file" />
<t:inputFileUpload id="file" value="#{docBean.uploadedFile}" required="true" />
<h:message for="file" style="color: red;" />
<h:panelGroup />
<h:commandButton value="Submit" action="#{docBean.submit}" />
<h:message for="uploadForm" infoStyle="color: green;" errorStyle="color: red;" />
</h:panelGrid>
</h:form>
<h:outputLink value="file/#{docBean.fileName}" rendered="#{docBean.fileName != null}">
Download back
</h:outputLink>
any idea ?

<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.12</version>
</dependency>
replace with
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk20</artifactId>
<version>1.1.12</version>
</dependency>

thanks Omar it was a matter of version I tried to upload using only jsf 2.2 with no tomahawk or primefaces.
resolved

Related

Optimistic locking Test in spring data JPA

I'm trying to test the optimistic locking mechanism in spring data jpa by loading a certain entity twice using findBy function, then updating the first one and asserting that when the second one is updated, it will throw an OptimisticLockingFailureException.
But the problem is that no exception is thrown and the second update is done successfully.
After investigation i found that findBy function hits the database only the first time and caches the returned entity. and when i call it again it returns cached entity. which means that both loaded entities are equal. so the first update reflects in both entities making the second entity does not have the stale data.
so, how do i force loading the second entity from the data base in the second findBy function call ?
Here is my code:-
Test class
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class PersistenceTests {
#Autowired
private ProductRepository repository;
private ProductEntity savedEntity;
#DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", () -> "jdbc:mysql://localhost:3306/code_snippet");
registry.add("spring.datasource.username", () -> "root");
registry.add("spring.datasource.password", () -> "System");
registry.add("spring.jpa.hibernate.ddl-auto", () -> "create-drop");
}
#BeforeEach
void setupDb() {
repository.deleteAll();
ProductEntity entity = new ProductEntity(1, "n", 1);
savedEntity = repository.save(entity);
assertEqualsProduct(entity, savedEntity);
}
#Test
void optimisticLockError() {
// Store the saved entity in two separate entity objects
ProductEntity entity1 = repository.findById(savedEntity.getId()).get();
ProductEntity entity2 = repository.findById(savedEntity.getId()).get();
// Update the entity using the first entity object
entity1.setName("n1");
repository.save(entity1);
// Update the entity using the second entity object.
// This should fail since the second entity now holds an old version number,
// i.e. an Optimistic Lock Error
assertThrows(OptimisticLockingFailureException.class, () -> {
entity2.setName("n2");
repository.save(entity2);
});
// Get the updated entity from the database and verify its new sate
ProductEntity updatedEntity = repository.findById(savedEntity.getId()).get();
assertEquals(1, (int) updatedEntity.getVersion());
assertEquals("n1", updatedEntity.getName());
}
private void assertEqualsProduct(ProductEntity expectedEntity, ProductEntity actualEntity) {
assertEquals(expectedEntity.getId(), actualEntity.getId());
assertEquals(expectedEntity.getVersion(), actualEntity.getVersion());
assertEquals(expectedEntity.getProductId(), actualEntity.getProductId());
assertEquals(expectedEntity.getName(), actualEntity.getName());
assertEquals(expectedEntity.getWeight(), actualEntity.getWeight());
}
}
Entity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
#Entity
#Table(name = "product")
public class ProductEntity {
#Id
#GeneratedValue
private Integer id;
#Version
private Integer version;
private int productId;
private String name;
private int weight;
public ProductEntity() {
}
public ProductEntity(int productId, String name, int weight) {
this.productId = productId;
this.name = name;
this.weight = weight;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
Repository
import java.util.Optional;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ProductRepository extends PagingAndSortingRepository<ProductEntity, Integer> {
Optional<ProductEntity> findByProductId(int productId);
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.javaworld.codesnippet</groupId>
<artifactId>writing-persistence-tests</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>writing-persistence-tests</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Main Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WritingPersistenceTestsApplication {
public static void main(String[] args) {
SpringApplication.run(WritingPersistenceTestsApplication.class, args);
}
}
The problem is that your test method is by default transactional. You can disable the transactional for this method by adding:
#Test
#Transactional(value = Transactional.TxType.NEVER)
Than you get in the second save ObjectOptimisticLockingFailureException

Upgrade from Spring Boot 2.7.2 to Spring Boot 3.0.0-SNAPSHOT: java: package javax.persistence does not exist

When I use Spring Boot 2.7.2 everything works ok. After upgrade to version 3.0.0-SNAPSHOT, I have
My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring_jwt</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>spring-boot-security-jwt</name>
<description>spring_jwt</description>
<properties>
<java.version>18</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-functions</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-metadata</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-chart-themes</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-annotation-processors</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-castor</artifactId>
<version>6.20.0</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>net.sf.jasperreports</groupId>-->
<!-- <artifactId>liberation-fonts</artifactId>-->
<!-- <version>1.0</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/com.mpobjects.jasperreports.font/jasperreports-fonts-liberation -->
<dependency>
<groupId>com.mpobjects.jasperreports.font</groupId>
<artifactId>jasperreports-fonts-liberation</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-chart-customizers</artifactId>
<version>6.20.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-custom-visualization</artifactId>
<version>6.20.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-report</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-web</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-base</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-viewer</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-samples</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-webviewer</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-lib</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>stimulsoft-reports-webdesigner</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.stimulsoft</groupId>-->
<!-- <artifactId>reports</artifactId>-->
<!-- <version>2022.3.3</version>-->
<!-- <type>pom</type>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>maven-central</id>
<name>Maven Central</name>
<url>https://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
Entity
package com.example.BLModel;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import java.time.OffsetDateTime;
#Entity
#Table(name = "account")
public class Account {
#EmbeddedId
private AccountId id;
#MapsId("tenantId")
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "tenant_id", nullable = false)
private Tenant tenant;
#Column(name = "account_number", nullable = false, length = 32)
private String accountNumber;
#Column(name = "account_name", nullable = false, length = 128)
private String accountName;
#Column(name = "account_name_english", length = 128)
private String accountNameEnglish;
#Column(name = "account_name_chinese", length = 128)
private String accountNameChinese;
#Column(name = "account_name_korean", length = 128)
private String accountNameKorean;
#Column(name = "description", length = 512)
private String description;
#Column(name = "parent_id")
private Short parentId;
#Column(name = "internal_code_id", length = 128)
private String internalCodeId;
#Column(name = "grade")
private Short grade;
#Column(name = "is_parent", nullable = false)
private Boolean isParent = false;
#Column(name = "account_category_kind", nullable = false)
private Short accountCategoryKind;
#Column(name = "is_postable_in_foreign_currency", nullable = false)
private Boolean isPostableInForeignCurrency = false;
#Column(name = "detail_by_account_object", nullable = false)
private Boolean detailByAccountObject = false;
#Column(name = "account_object_type")
private Short accountObjectType;
#Column(name = "detail_by_bank_account", nullable = false)
private Boolean detailByBankAccount = false;
#Column(name = "detail_by_job", nullable = false)
private Boolean detailByJob = false;
#Column(name = "detail_by_job_kind")
private Short detailByJobKind;
#Column(name = "detail_by_project_work", nullable = false)
private Boolean detailByProjectWork = false;
#Column(name = "detail_by_project_work_kind")
private Short detailByProjectWorkKind;
#Column(name = "detail_by_order", nullable = false)
private Boolean detailByOrder = false;
#Column(name = "detail_by_order_kind")
private Short detailByOrderKind;
#Column(name = "detail_by_contract", nullable = false)
private Boolean detailByContract = false;
#Column(name = "detail_by_contract_kind")
private Short detailByContractKind;
#Column(name = "detail_by_expense_item", nullable = false)
private Boolean detailByExpenseItem = false;
#Column(name = "detail_by_expense_item_kind")
private Short detailByExpenseItemKind;
#Column(name = "detail_by_department", nullable = false)
private Boolean detailByDepartment = false;
#Column(name = "detail_by_department_kind")
private Short detailByDepartmentKind;
#Column(name = "detail_by_list_item", nullable = false)
private Boolean detailByListItem = false;
#Column(name = "detail_by_list_item_kind")
private Short detailByListItemKind;
#Column(name = "active_status", nullable = false)
private Boolean activeStatus = false;
#Column(name = "created")
private OffsetDateTime created;
#Column(name = "created_by", length = 64)
private String createdBy;
#Column(name = "modified")
private OffsetDateTime modified;
#Column(name = "modified_by", length = 64)
private String modifiedBy;
#Column(name = "sort_internal_code_id", length = 128)
private String sortInternalCodeId;
#Column(name = "detail_by_pu_contract", nullable = false)
private Boolean detailByPuContract = false;
#Column(name = "detail_by_pu_contract_kind")
private Short detailByPuContractKind;
public AccountId getId() {
return id;
}
public void setId(AccountId id) {
this.id = id;
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountNameEnglish() {
return accountNameEnglish;
}
public void setAccountNameEnglish(String accountNameEnglish) {
this.accountNameEnglish = accountNameEnglish;
}
public String getAccountNameChinese() {
return accountNameChinese;
}
public void setAccountNameChinese(String accountNameChinese) {
this.accountNameChinese = accountNameChinese;
}
public String getAccountNameKorean() {
return accountNameKorean;
}
public void setAccountNameKorean(String accountNameKorean) {
this.accountNameKorean = accountNameKorean;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Short getParentId() {
return parentId;
}
public void setParentId(Short parentId) {
this.parentId = parentId;
}
public String getInternalCodeId() {
return internalCodeId;
}
public void setInternalCodeId(String internalCodeId) {
this.internalCodeId = internalCodeId;
}
public Short getGrade() {
return grade;
}
public void setGrade(Short grade) {
this.grade = grade;
}
public Boolean getIsParent() {
return isParent;
}
public void setIsParent(Boolean isParent) {
this.isParent = isParent;
}
public Short getAccountCategoryKind() {
return accountCategoryKind;
}
public void setAccountCategoryKind(Short accountCategoryKind) {
this.accountCategoryKind = accountCategoryKind;
}
public Boolean getIsPostableInForeignCurrency() {
return isPostableInForeignCurrency;
}
public void setIsPostableInForeignCurrency(Boolean isPostableInForeignCurrency) {
this.isPostableInForeignCurrency = isPostableInForeignCurrency;
}
public Boolean getDetailByAccountObject() {
return detailByAccountObject;
}
public void setDetailByAccountObject(Boolean detailByAccountObject) {
this.detailByAccountObject = detailByAccountObject;
}
public Short getAccountObjectType() {
return accountObjectType;
}
public void setAccountObjectType(Short accountObjectType) {
this.accountObjectType = accountObjectType;
}
public Boolean getDetailByBankAccount() {
return detailByBankAccount;
}
public void setDetailByBankAccount(Boolean detailByBankAccount) {
this.detailByBankAccount = detailByBankAccount;
}
public Boolean getDetailByJob() {
return detailByJob;
}
public void setDetailByJob(Boolean detailByJob) {
this.detailByJob = detailByJob;
}
public Short getDetailByJobKind() {
return detailByJobKind;
}
public void setDetailByJobKind(Short detailByJobKind) {
this.detailByJobKind = detailByJobKind;
}
public Boolean getDetailByProjectWork() {
return detailByProjectWork;
}
public void setDetailByProjectWork(Boolean detailByProjectWork) {
this.detailByProjectWork = detailByProjectWork;
}
public Short getDetailByProjectWorkKind() {
return detailByProjectWorkKind;
}
public void setDetailByProjectWorkKind(Short detailByProjectWorkKind) {
this.detailByProjectWorkKind = detailByProjectWorkKind;
}
public Boolean getDetailByOrder() {
return detailByOrder;
}
public void setDetailByOrder(Boolean detailByOrder) {
this.detailByOrder = detailByOrder;
}
public Short getDetailByOrderKind() {
return detailByOrderKind;
}
public void setDetailByOrderKind(Short detailByOrderKind) {
this.detailByOrderKind = detailByOrderKind;
}
public Boolean getDetailByContract() {
return detailByContract;
}
public void setDetailByContract(Boolean detailByContract) {
this.detailByContract = detailByContract;
}
public Short getDetailByContractKind() {
return detailByContractKind;
}
public void setDetailByContractKind(Short detailByContractKind) {
this.detailByContractKind = detailByContractKind;
}
public Boolean getDetailByExpenseItem() {
return detailByExpenseItem;
}
public void setDetailByExpenseItem(Boolean detailByExpenseItem) {
this.detailByExpenseItem = detailByExpenseItem;
}
public Short getDetailByExpenseItemKind() {
return detailByExpenseItemKind;
}
public void setDetailByExpenseItemKind(Short detailByExpenseItemKind) {
this.detailByExpenseItemKind = detailByExpenseItemKind;
}
public Boolean getDetailByDepartment() {
return detailByDepartment;
}
public void setDetailByDepartment(Boolean detailByDepartment) {
this.detailByDepartment = detailByDepartment;
}
public Short getDetailByDepartmentKind() {
return detailByDepartmentKind;
}
public void setDetailByDepartmentKind(Short detailByDepartmentKind) {
this.detailByDepartmentKind = detailByDepartmentKind;
}
public Boolean getDetailByListItem() {
return detailByListItem;
}
public void setDetailByListItem(Boolean detailByListItem) {
this.detailByListItem = detailByListItem;
}
public Short getDetailByListItemKind() {
return detailByListItemKind;
}
public void setDetailByListItemKind(Short detailByListItemKind) {
this.detailByListItemKind = detailByListItemKind;
}
public Boolean getActiveStatus() {
return activeStatus;
}
public void setActiveStatus(Boolean activeStatus) {
this.activeStatus = activeStatus;
}
public OffsetDateTime getCreated() {
return created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public OffsetDateTime getModified() {
return modified;
}
public void setModified(OffsetDateTime modified) {
this.modified = modified;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public String getSortInternalCodeId() {
return sortInternalCodeId;
}
public void setSortInternalCodeId(String sortInternalCodeId) {
this.sortInternalCodeId = sortInternalCodeId;
}
public Boolean getDetailByPuContract() {
return detailByPuContract;
}
public void setDetailByPuContract(Boolean detailByPuContract) {
this.detailByPuContract = detailByPuContract;
}
public Short getDetailByPuContractKind() {
return detailByPuContractKind;
}
public void setDetailByPuContractKind(Short detailByPuContractKind) {
this.detailByPuContractKind = detailByPuContractKind;
}
}
error
java: package javax.persistence does not exist
How to fix?
There is no need to add hibernate-entitymanager artifact as dependency in pom.xml.
spring-boot-starter-data-jpa artifact is enough. You shoud just consider the following points.
Replace Java EE 8 With Jakarta EE 9 APIs:
Spring Boot 3.0 will be the first version of Spring Boot that makes use of Jakarta EE 9 APIs (jakarta.) instead of EE 8 (javax.). This entails that we will have to look for EE 8 imports with javax.* and replace them with jakarta.*. Typical EE 8 packages used in Spring Boot microservices include the following:
javax.persistence.*
javax.validation.*
javax.servlet.*
javax.annotation.*
javax.transaction.*
etc.
Be aware that packages such as javax.sql.* and javax.crypto.* come from Java 17 JDK, not from EE 8, so they are safe to stay.
References:
Notes on Spring-Boot-3 Upgrade
Preparing for Spring-Boot-3-0
Change "JPA API from Java EE" --> "JPA API from Jakarta EE", and add
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>6.0.0.Alpha7</version>
<type>pom</type>
</dependency>
Just delete the jakarta dependency. Since it has its full content in the ultimate version of Intellij Idea. In your case, this one:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
And add these dependencies:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>

Jackson XML parsing MismatchedInputException

I want to parse Below XML file into Java Object using Jackson. But it shows MismatchedInputException message is become null. I specified feild that I need in Employee class. And using these fields I need to create Employee objects.
d.xml -> the input xml file
<Messages>
<Message>
<Uumid>45</Uumid>
<UumidSuffix>ER.79</UumidSuffix>
<CreationDate>20-05-2020</CreationDate>
<Data>FRHF#%^G</Data>
</Message>
<Message>
<Uumid>89</Uumid>
<UumidSuffix>RT.12</UumidSuffix>
<CreationDate>26-05-2020</CreationDate>
<Data>FGRH#%^</Data>
</Message>
</Messages>
Messages.java
package org.example;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.lang.annotation.Documented;
import java.util.Arrays;
#JacksonXmlRootElement(localName ="Messages")
public final class Messages {
#JacksonXmlElementWrapper(localName = "Message",useWrapping = true)
private Message[] message;
public Messages(){}
public Messages(Message[] message){
this.message=message;
}
public Message[] getMessage() {
return message;
}
public void setMessage(Message[] message) {
this.message = message;
}
#Override
public String toString() {
return "Messages{" +
"message=" + Arrays.toString(message) +
'}';
}
}
Message.java
package org.example;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import javax.xml.bind.annotation.XmlAccessorOrder;
public class Message {
#JacksonXmlProperty(localName = "Uumid")
private String uumid;
#JacksonXmlProperty(localName = "UumidSuffix")
private String uumidSuffix;
#JacksonXmlProperty(localName = "CreationDate")
private String creationDate;
public Message() {}
public Message(String uumid,String uumidSuffix,String creationDate){
this.uumid=uumid;
this.uumidSuffix=uumidSuffix;
this.creationDate=creationDate;
}
public String getUumid() {
return uumid;
}
public void setUumid(String uumid) {
this.uumid = uumid;
}
public String getUumidSuffix() {
return uumidSuffix;
}
public void setUumidSuffix(String uumidSuffix) {
this.uumidSuffix = uumidSuffix;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
#Override
public String toString() {
return "Message{" +
"uumid='" + uumid + '\'' +
", uumidSuffix='" + uumidSuffix + '\'' +
", CreationDate='" + creationDate + '\'' +
'}';
}
}
Parser.java
package org.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Parser {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper=new XmlMapper();
Messages messages=objectMapper.readValue(StringUtils.toEncodedString(Files.readAllBytes(Paths.get("disk/d.xml")), StandardCharsets.UTF_8),Messages.class);
System.out.println(messages);
}
}
when executes this error shows
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.example.Message` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('asdf')
at [Source: (StringReader); line: 3, column: 20] (through reference chain: org.example.Messages["Message"]->java.lang.Object[][0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1455)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1081)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1408)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:176)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4524)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3466)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
at org.example.Parser.main(Parser.java:17)
Process finished with exit code 1
maven dependencies
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.2</version>
</dependency>
</dependencies>
Your current code tells Jackson that your messages should be wrapped into a wrapper tag, so it expects XML that looks something like this:
<Messages>
<Message> <!-- this is the wrapper -->
<Message>
<Uumid>...</Uumid>
...
</Message>
<Message>
...
</Message>
</Message>
</Messages>
To fix this, you'll have to tell Jaskcon to not use the wrapper, and that the children are called "Message". In your Messages class you have to update annotations on the message field to the following:
#JacksonXmlElementWrapper(useWrapping = false)
#JacksonXmlProperty(localName = "Message")
private Message[] message;
(BTW, why not call this field messages?)

Springboot Jpa or hibernate updating records instead of inserting

Hi I have a normal working application which is inserting / deleting / updating correctly. However I am trying to implement receiving a json string from ajax and inserting it in a database (PostgreSQL 10.12)
The first 2 to 5 records get inserted correctly however then the application starts updating records instead of inserting and the primary keys get out of sequence.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dashboard</groupId>
<artifactId>sp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring </name>
<description>Spring boot </description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.13.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
#SuppressWarnings("hiding")
#MappedSuperclass
public abstract class AbstractModel<Long extends Serializable> implements Serializable {
private static final long serialVersionUID = -6323358535657100144L;
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractModel<?> other = (AbstractModel<?>) obj;
if (id == null) {
return other.id == null;
} else return id.equals(other.id);
}
}
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity
#Data
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class PurchaseOrderProducts extends AbstractModel<Long> {
/**
*
*/
private static final long serialVersionUID = -5927643103467927664L;
#Column(nullable = false)
private Integer productcode;
#Column(nullable = false)
private String manufacturer;
#Column(nullable = false)
private String model;
#Column(nullable = false)
private String supplier;
#Column(nullable = false)
private String supplierproductcode;
#Column(nullable = false)
private Integer orderno;
public Integer getProductcode() {
return productcode;
}
public void setProductcode(Integer productcode) {
this.productcode = productcode;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getSupplierproductcode() {
return supplierproductcode;
}
public void setSupplierproductcode(String supplierproductcode) {
this.supplierproductcode = supplierproductcode;
}
public Integer getOrderno() {
return orderno;
}
public void setOrderno(Integer orderno) {
this.orderno = orderno;
}
#Override
public String toString() {
return "PurchaseOrderProducts [productcode=" + productcode + ", manufacturer=" + manufacturer + ", model="
+ model + ", supplier=" + supplier + ", supplierproductcode=" + supplierproductcode + ", orderno="
+ orderno + "]";
}
}
#Service
public class PurchaseOrdersProductsService extends AbstractService<PurchaseOrderProducts, Long> {
#Autowired
private PurchaseOrdersProductsRepository purchaseOrdersProductsRepository;
#Override
protected JpaRepository<PurchaseOrderProducts, Long> getRepository() {
return purchaseOrdersProductsRepository;
}
public List<PurchaseOrderProducts> getAllPurchaseOrdersProducts() {
return getRepository().findAll();
}
#Transactional
public boolean checkIfExists(Integer productcode, Integer orderno) {
boolean val = false;
Integer test = purchaseOrdersProductsRepository.checkIfExists(productcode,orderno);
if(test == 0) {
val = false;
} else {
val = true;
}
return val;
}
public void saveAll(List<PurchaseOrderProducts> purchaseOrderProducts) {
purchaseOrdersProductsRepository.saveAll(purchaseOrderProducts);
}
}
#Repository
public interface PurchaseOrdersProductsRepository extends JpaRepository<PurchaseOrderProducts, Long> {
#Query(value = "SELECT count(productcode) FROM purchase_order_products m WHERE m.productcode = ?1 AND m.orderno=?2" , nativeQuery=true)
Integer checkIfExists(long productcode, long orderno);
}
#PostMapping(value = "/submitpoproducts", consumes = "application/json", produces = "application/json")
#ResponseBody
public List<String> savePurchaseOrderProductList(#RequestBody PurchaseOrderProducts[] purchaseOrderProducts) {
List<String> response = new ArrayList<String>();
for (int i = 0; i < purchaseOrderProducts.length; i++) {
// if (purchaseOrderProducts[i].getProductcode() != null) {
// if
// (purchaseOrdersProductsService.checkIfExists(purchaseOrderProducts[i].getProductcode(),
// purchaseOrderProducts[i].getOrderno()) == false) {
purchaseOrdersProductsService.save(purchaseOrderProducts[i]);
System.out.println(purchaseOrderProducts[i].toString());
// }
// }
// response.add("Saved product: " + purchaseOrderProducts[i]);
}
return response;
}
PurchaseOrderProducts [productcode=10000004, manufacturer=FS, model=CL 20cl, supplier=Fs, supplierproductcode=FAR001, orderno=10000003]
id |
----+
1 |
2 |
3 |
4 |
id |
----+--------------
1 |
3 |
4 |
2 |
5 |
It is hard to test your issue as you didn't provide the JSON. As a best pratice, you should check the client is not sending PurchaseOrderProducts with id, this may be your issue.
For anyone else that might come across this. I removed the json key value pair being sent having the key id and it worked. (with javascript )
delete row['id'];

How to generate json by using lombok+gson using builder() method?

I have a json like this, how can I generate it by using lombok expression + gson library? It has a mixture of array and list. Is there any readymade tool available?
{
"transactions": [
{
"transactionIds": 123456,
"test": 3000,
"amount": {
"currency": "USD",
"value": 10
}
}
]
}
Define the values like you always do and rather generating the getters / setters you would be adding the #Data attribute, Complete code below along with the dependencies
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
public class Stack32 {
public static #Data class Amount {
private String currency;
private int value;
}
public static #Data class Child {
private int transactionIds;
private int test;
private Amount amount;
}
public static #Data class Parent {
private List<Child> transactions = new ArrayList<Child>();
}
public static void main(String[] args) throws JsonProcessingException {
Amount a1 = new Amount();
a1.setCurrency("USD");
a1.setValue(10);
Child a2 = new Child();
a2.setTransactionIds(123456);
a2.setTest(3000);
a2.setAmount(a1);
Parent a3 = new Parent();
a3.getTransactions().add(a2);
ObjectMapper mapper = new ObjectMapper();
String payload = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a3);
System.out.println(payload);
}
}
Depdendencies :
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>

Resources