getting null when reading csv values - spring

I need to import a csv file and get all its data but when I'm running this code, Im getting null as values but In the same time when Im printing number of rows, it's giving me the right number
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(#RequestParam(value = "file") MultipartFile file){
CsvToBean<Person> csvToBean = new CsvToBeanBuilder(reader)
.withType(Person.class)
.withIgnoreLeadingWhiteSpace(true)
.build();
List<Person> records = csvToBean.parse();
System.out.println(records.size());
if(records.size() ==0) {
model.addAttribute("message_file", "Aucune donnée trouvée dans le fichier importé");
model.addAttribute("code_file", "000");
}
for(int i = 0; i<records.size(); i++){
System.out.println(records.get(i).getid());
}
.....
}
Person class :
#Entity
#Table(name = "Person", schema = "MXP")
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "person_id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XPerson")
private Long id;
#Column(name = "PERSON_NAME")
private String name;
//..getters and setters
Do you have any Idea, how to extract data ?

Related

Sending file and JSON in a many-to-many relationship

I have a model called EPI that has a many to many relationship with Model Images, I am not able to do the #PostMapping for this object.
see my code
EPI Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "EPI")
public class EPI implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id_EPI")
private UUID id;
#Column(name = "Nome", nullable = false, length = 100)
private String nome;
#Column(name = "Marca", nullable = false, length = 100)
private String marca;
#Column(name = "CA", nullable = false, length = 100)
private String ca;
#Column(name = "Descricao", nullable = false)
private String descricao;
#Column(name = "Foto")
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "epi_images",
joinColumns = {
#JoinColumn(name = "epi_id")
},
inverseJoinColumns = {
#JoinColumn(name = "image_id")
})
private Set<ImageModel> foto;
#Column(name = "Quantidade", nullable = false)
private Integer quantidade;
}
Image Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "image_model")
public class ImageModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
private String name;
#Column(name = "type")
private String type;
#Column(name = "image_data", unique = false, nullable = false, length = 100000)
private byte[] imageData;
}
Controller EPI:
#PostMapping("/addNewEPI")
public ResponseEntity<Object> salvarFEPI(#RequestPart("image")MultipartFile file,
#RequestPart("epiModel") EPI epi) throws IOException {
try {
ImageModel foto = productImageService.uploadImage(file);
epi.setFoto((Set<ImageModel>) foto);
return ResponseEntity.status(HttpStatus.CREATED).body(epiService.save(epi));
} catch (Exception e){
System.out.println(e.getMessage());
return null;
}
Service Image:
public ImageModel uploadImage(MultipartFile file) throws IOException {
ImageModel image = new ImageModel();
image.setName(file.getOriginalFilename());
image.setType(file.getContentType());
image.setImageData(ImageUtility.compressImage(file.getBytes()));
return image;
}
As I am passing the parameters in Postman:
enter image description here
Return from Spring Boot:
enter image description here
If anyone can help me I would be very grateful!
I tried passing the parameters in different ways. I just want it to populate my tables passing the parameters of the EPI entity and the Image file.
enter image description here

Hibernate - Spring - ConstraintViolationException - UniqueConstraint

I'm trying to make some fixtures for my Profile model but every time I'm trying to save it "again" after I did an update, I get this message:
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
This is my Profile class:
#Entity
#Data
#Builder
#ToString(of = {"birthday", "discordId", "description", "spokenLanguages"})
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "profile", uniqueConstraints = #UniqueConstraint(columnNames = "discordId"))
public class Profile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idProfile;
private Date birthday;
#Column(name="discordId", insertable=true, updatable=false)
private String discordId;
private String description;
#ElementCollection(fetch = FetchType.EAGER)
private Set<String> spokenLanguages = new LinkedHashSet<String>();
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER)
private Set<ProfileGame> profileGames = new LinkedHashSet<>();
#OneToOne(mappedBy = "profile", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
private User user;
#ManyToOne
private TimeSlot timeSlot;
}
Here is the call:
#Order(7)
#Test
void fillProfileGame() {
List<Profile> profileList = this.profileRepository.findAll();
for (Profile profile : profileList) {
List<Game> gameList = this.gameRepository.findAll();
Collections.shuffle(gameList);
int rndNbGame = new Random().ints(1, 5).findFirst().getAsInt();
for (int i = 1; i <= rndNbGame; i++) {
int rndLevel = new Random().ints(1, 100).findFirst().getAsInt();
int rndRanking = new Random().ints(1, 3000).findFirst().getAsInt();
Game rndGame = gameList.get(0);
gameList.remove(0);
ProfileGame profileGames = new ProfileGame(profile, rndGame, "level-" + rndLevel,
"ranking-" + rndRanking);
this.profileGameRepository.save(profileGames);
this.gameRepository.save(rndGame);
}
this.profileRepository.save(profile);
}
}
So what I understand is that Hibernate won't let me update this object because it has a unique contraint field ?
How do we proceed when we want a field to be unique and still being able to update other fields ?
From the code snippet, what I see is that there are some unique constraints applied on the column 'discordId'.
#Table(name = "profile", uniqueConstraints = #UniqueConstraint(columnNames = "discordId"))
and
#Column(name="discordId", insertable=true, updatable=false)
private String discordId;
As you can see, there is a parameter 'updatable' which is set to false. Therefore, when you are trying to update an already existing object, hibernate is throwing UniqueConstraintViolationException.
To fix this, set 'updatable=true' or remove it altogether and it should work fine.
#Column(name="discordId", insertable=true, updatable=true)
private String discordId;

JpaSystemException when trying to fetch null values from Database

for some cases the master Id is null in DB and when I am fetching it it is giving me JPA system exception
So is there any annotation that would help to ignore the null values.
Method threw 'org.springframework.orm.jpa.JpaSystemException' exception.
got it when trying to fetch details from the database.
package com.merchant.orderDahsBoard.controller;
#RestController
#RequestMapping(value = "Dashboard")
public class OrderDashboardController {
#Autowired
private DashBoardService service;
ObjectMapper mapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
#PostMapping(value = "/getOrderDetails")
public OrderResponse getOrder(#PathParam(value = "id") Long id) {
OrderResponse response = new OrderResponse();
List<OrderMapping> orderMapping;
Sale sale= new Sale();
Purchase purchase = new Purchase();
long saleId = 0;
long purchaseId = 0;
try{
orderMapping = service.getOrderMapping(id);
response.setOrderMapping(orderMapping);
if (orderMapping != null) {
for (OrderMapping order : orderMapping) {
switch (order.getORDERTYPE()) {
case CART:
break;
case SALE:
saleId = order.getORDERID();
break;
case PURCHASE:
purchaseId = order.getORDERID();
break;
}
}
if(saleId!=0){
sale = service.getSale(saleId);
response.setSale(sale);
}
}
}
catch(Exception e){
log.error("Exception occured "+e);
}
return response;
}
}
below is the #Entity Class used in my project
#Entity
#Table(name = "ORDERMAPPING")
#Getter
#Setter
#ToString
public class OrderMapping {
#Id
#Column(name = "ORDERMAPPINGID")
private long ORDERMAPPINGID;
#Column(name = "MASTERID")
private long MASTERID;
#Column(name = "ORDERID")
private long ORDERID;
#Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;
#Column(name = "ADDEDDATE")
private String ADDEDDATE;
#Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;
#Column(name = "CARTID")
private long CARTID;
#Column(name = "PCARTID")
private long PCARTID;
}
Instead of primitive data types try using the wrapper classes for the same. The following code can help you better.
Use Long isntead of long
#Entity
#Table(name = "ORDERMAPPING")
#Getter
#Setter
#ToString
public class OrderMapping {
#Id
#Column(name = "ORDERMAPPINGID")
private Long ORDERMAPPINGID;
#Column(name = "MASTERID")
private Long MASTERID;
#Column(name = "ORDERID")
private Long ORDERID;
#Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;
#Column(name = "ADDEDDATE")
private String ADDEDDATE;
#Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;
#Column(name = "CARTID")
private Long CARTID;
#Column(name = "PCARTID")
private Long PCARTID;
}

JPA Specification filtering nested object

I am trying to fetch nested object property but getting illegalArgument exception.
AuditTestingPlanSpecification name = new AuditTestingPlanSpecification(new SearchCriteria("auditPlanId.auditPlanEntity", ":",dates));
Page<AuditTestingPlanMaster> a = auditTestingPlanMasterRepository.findAll(name, ten);
Please find below code,
public class AuditTestingPlanSpecification implements Specification<AuditTestingPlanMaster> {
private SearchCriteria criteria;
public AuditTestingPlanSpecification(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
}
#Override
public Predicate toPredicate(Root<AuditTestingPlanMaster> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(root.<String>get(criteria.getKey()), "%" + criteria.getValue().get(0).toString() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue().get(0).toString());
}
return null;
}
}
Class SearchCriteria.java
public class SearchCriteria {
public SearchCriteria(String key, String operation, List<Object> value) {
super();
this.key = key;
this.operation = operation;
this.value = value;
}
private String key;
private String operation;
private List<Object> value;
// getters & setters
}
Class AuditTestingPlanMaster.java
#Entity
#Table(name = "audit_testing_plan_master")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuditTestingPlanMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "risk_area_id")
private Long riskAreaId;
#Column(name = "expected_revert_date")
private Instant expectedRevertDate;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private Instant lastModifiedDate;
#JoinColumn(name = "audit_plan_id", referencedColumnName = "id")
private AuditPlanMaster auditPlanId;
//getters & setters
}
Class AuditPlanMaster.java
#Entity
#Table(name = "audit_plan_master")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuditPlanMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "remarks", length = 255)
private String remarks;
#Column(name = "audit_plan_entity", length = 50)
private String auditPlanEntity;
#Column(name = "start_date")
private Instant startDate;
#Column(name = "end_date")
private Instant endDate;
//getters & setters
}
I want to fetch all the AuditTestingPlanMaster objects whose AuditPlanMaster.auditPlanEntity string is matching with provided filter value.
Thank you for your time and help in advance.
I had the same problem, here is a snippet of how I handled it. My problem was when accessing id field from inner usuario object, in my case, id would be like your auditPlanEntity, and usuario would be like auditplanMaster:
public static Specification<UsuarioErrorEquipo> usuarioContains(String codigoUsuario) {
return (root, query, builder) -> {
Path<Usuario> u = root.get("usuario");
return builder.equal(u.get("id"), codigoUsuario);
};
}
I believe, that in your case it should be something like:
Path<AuditPlanMaster> u = root.get("auditPlanId");
return builder.equal(u.get("auditPlanEntity"), "the value you want to compare");

Spring-Data-Jpa OneToMany query duplicate ids in the info log?

I don't understand why the ids are duplicated (id_msg, id_pers_acct), that's what's in my Springboot log :
select personneco0_.id_pers_acct as id_pers_1_2_0_,
…
from test.person_account personacc0_ where personacc0_.id_pers_acct=?
select messages0_.id_pers_acct as id_pers_5_1_0_,
messages0_.id_msg as id_msg1_1_0_,
messages0_.id_msg as id_msg1_1_1_,
messages0_.content as content2_1_1_,
messages0_.date as date3_1_1_,
messages0_.id_pers_acct_person_account as id_pers_4_1_1_,
messages0_.id_pers_acct as id_pers_5_1_1_
from test.message messages0_ where messages0_.id_pers_acct=?
In my entity PersonAccount i have this code :
#OneToMany(mappedBy = "sender", fetch = FetchType.LAZY)
public Set<Message> messages = new HashSet <Message>();
In my entity Message i have this code :
#Entity
#Table(name = "MESSAGE", catalog = "TEST")
public class Message implements Serializable{
/**
*
*/
private static final long serialVersionUID = -602563072975023074L;
#Id
#GeneratedValue
#Column(name = "ID_MSG")
Long idMsg;
#Column(name = "CONTENT")
String content;
#Column(name = "DATE")
Date date;
#Column(name = "ID_PERS_ACCT", nullable = false)
Long sender;
#Column(name = "ID_PERS_ACCT_PERSON_ACCOUNT", nullable = false)
Long receiver;
In my RestController, i call this :
#RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public PersonAccount getUser(#PathVariable Long id) {
return userRepository.getOne(id);
}

Resources