Passing a class object as a parameter in Postman - java

i am developing an API application, however I am having difficulties with a particular method.
The getCertificationPOJO method, is responsible for taking in a Store as a parameter and searching if that store exists in the database.
Now the problem here is how do I pass a Store object as a parameter in Postman. I have tried passing it in as a JSON string, but that is not working.
Apologies for the bad edit
Certification Controller
#Controller
public class CertController {
#Autowired
private CertificationRepository certRepo;
#Autowired
private StoreRepository StoreRepository;
#GetMapping(value = "/getCertObject")
public #ResponseBody
Optional<Certification> getCertificationPOJO(#RequestParam Store store)
{return Lists.newArrayList(certRepo.findAll()).stream().filter(e->e.getStore() == store).findFirst();}
}
Store Class
#Entity
#Table(name = "store")
public class Store implements com.halal.abstractions.Entity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#JsonIgnore
#OneToOne(optional = true) // By default this is set to true so technically this is redundant but, yea lets
// just keep it there
private Certification certification;
#NotNull
#Column(nullable = false)
private String name;
private String phoneNumber;
#NotNull
#Column(nullable = false)
private String address;
#NotNull
#Column(nullable = false)
private double latitude;
#NotNull
#Column(nullable = false)
private double longitude;
#NotNull
#Column(nullable = false)
private Date dateAdded;
static final DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
protected Store() {
}
public Store(String name, String phoneNumber, String address, double latitude, double longitude) {
this.name = name;
this.setPhoneNumber(phoneNumber);
this.setAddress(address);
this.latitude = latitude;
this.longitude = longitude;
this.dateAdded = new Date(System.currentTimeMillis());
}
#Override
public Long getId() {
return this.id;
}
#Override
public void setId(long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Double getLatitude() {
return this.latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return this.longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
#Override
public String getDateAdded() {
return DF.format(dateAdded);
}
#Override
public void setCertification(Certification certification) {
this.certification = certification;
}
#Override
public Certification getCertification() {
return this.certification;
}
#Override
public String toString() {
return "Store{" + "id=" + id + ", certification=" + certification + ", name='" + name + '\'' + ", phoneNumber='"
+ phoneNumber + '\'' + ", address='" + address + '\'' + ", latitude=" + latitude + ", longitude="
+ longitude + ", dateAdded=" + dateAdded + '}';
}
}
Certification Class
#Entity
#Table(name = "certification")
public class Certification {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(nullable = false)
private boolean isCertified;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "id")
#JsonIgnore
private Store store;
public Certification() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Store getStore() {
return this.store;
}
public void setStore(Store store) {
this.store = store;
}
public boolean isIsCertified() {
return this.isCertified;
}
public void setIsCertified(boolean isCertified) {
this.isCertified = isCertified;
}
#Override
public String toString() {
return "Certification{" + "id=" + id + ", isCertified= " + isCertified + '}';
}
}

I would advise against sending a body in a GET request, see similar answer here
The query param route that #Murilo suggests is one way but if the way of determining whether a getCertificationPOJO already exists in the database depends solely on the id then you may only need to send the id in which case a path variable would be best like below where {id} can be replaced with the actual ID
GET /getCertObject/{id}
and then in the controller
#GetMapping("/getCertObject/{id}")
#ResponseBody
Optional<Certification> getCertificationPOJO(#PathVariable String id) {
...
}

You don't use Params section in this case. You use Body. Click on that tab and put your JSON OBJECT in the textbox that will appear. You also need to set CONTENT TYPE to JSON by selecting the proper value in the COMBO that appears farthest to the right of the attached image.
Check this out:

If you are using queryParams you have to pass individually each key/param, in your Postman you fill like it:
key: id value: 1
key: name value "asdasd"
key: phoneNumber value: "000"
(...)
Another option is you change your strategy and pass the entire json in your Body, but you will have to change your RestController to receive a #RequestBody instead of #RequestParam

Related

JSON parse error, unable to deserialize value of type `java.time.LocalDate` in STS 4.15.3 windows version

I'm new to this tool and I'm having trouble with this specific issue. I looked for an example But could not find something similar, better, I found a possible solution, but in my case It doesn't work.
I have this narrow project that resembles our famous CRUD, and I'm trying to reference the primary key from one table to another.
Client Entity:
#Entity
#Table(name = "client")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "cpf", length = 14)
private String cpf;
#Column(name = "name", length = 100)
private String name;
#Column(name = "birth_date")
private LocalDate birthDate;
#Column(name = "address", length = 255)
private String address;
#Column(name = "telephone", length = 14)
private String telephone;
#Column(name = "email", length = 200)
private String email;
#Column(name = "date_register", insertable = true, updatable = false)
private LocalDate dateRegister;
public Client() {
super();
}
public Client(Long id, String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.id = id;
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
public Client(String cpf, String name, LocalDate birthDate, String address, String telephone, String email, LocalDate dateRegister) {
super();
this.cpf = cpf;
this.name = name;
this.birthDate = birthDate;
this.address = address;
this.telephone = telephone;
this.email = email;
this.dateRegister = dateRegister;
}
#PrePersist
public void prePersist() {
setDateRegister(LocalDate.now());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDateRegister() {
return dateRegister;
}
public void setDateRegister(LocalDate dateRegister) {
this.dateRegister = dateRegister;
}
#Override
public String toString() {
return "Client [id=" + id + ", cpf=" + cpf + ", name=" + name + ", birthDate=" + birthDate + ", address="
+ address + ", telephone=" + telephone + ", email=" + email + ", dateRegister=" + dateRegister + "]";
}
}
Sale Entity:
#Entity
#Table(name = "sale")
public class Sale {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToMany(mappedBy = "sale")
private List<SaleItem> items;
#Column(name = "payment_type", length = 10)
#Enumerated(EnumType.STRING)
private PaymentType paymentType;
#Column(name = "amount")
private BigDecimal amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<SaleItem> getItems() {
return items;
}
public void setItems(List<SaleItem> items) {
this.items = items;
}
public PaymentType getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentType paymentType) {
this.paymentType = paymentType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
#Override
public String toString() {
return "Sale [id=" + id + ", client=" + client + ", items=" + items + ", paymentType=" + paymentType
+ ", amount=" + amount + "]";
}
}
The objective is to link the client to a sale through its primary key. These two codes refer to the sales repository and its controller:
SaleRepository:
public interface SaleRepository extends JpaRepository<Sale, Long> {
}
SaleController:
#RestController
#RequestMapping("/api/sales")
#CrossOrigin("*")
public class SaleController {
#Autowired
private SaleRepository repository;
#Autowired
private SaleItemRepository saleItemrepository;
#PostMapping
#Transactional
public void save(#RequestBody Sale sale) {
repository.save(sale);
sale.getItems().stream().forEach(saleItem -> saleItem.setSale(sale));
saleItemrepository.saveAll(sale.getItems());
}
}
And the problem is exactly how this reference is being made. In the current private Client client; way , the client object is being passed in full instead of its id, that's why it throws this following error when I try to register the sale.
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "31/05/1968": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '31/05/1968' could not be parsed at index 0<EOL> at [Source: (PushbackInputStream); line: 1, column: 87] (through reference chain: MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Sale["client"]->MyNameIsRafaelSampaio.github.com.bruxo_vendas_ltda_api.model.Client["birthDate"])]
As was to be expected, since the column birthDate present in the client entity is not being treated correctly in the sale entity. I did research on a possible solution but none made much sense to me, I believe for being a newbie, one of the solutions that I found more understandable was the use of the #MapsId tag. I tried to make changes to adapt, but I was not successful, if you can help I will be grateful.

How to handle message error in Entity when using #MockMvc

I using #MockMvc test in spring controller but i have a question.
How to handle message error when MockMvc test not pass method.
Entity:
#Entity
#ApiModel(description = "All details about the Product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO,generator = "system-uuid")
#GenericGenerator(name = "system-uuid",strategy = "uuid2")
private String id;
#NotNull(message = "name can not null")
#ApiModelProperty(notes = "The name is product")
private String name;
#ApiModelProperty(notes = "The type is product")
private String type;
#NotNull(message = "category can not null")
private String category;
private String description;
private Double prince;
public Product() {
}
public Product(String name, String type, String category, String description, Double prince) {
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.prince = prince;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrince() {
return prince;
}
public void setPrince(Double prince) {
this.prince = prince;
}
#Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
", category='" + category + '\'' +
", description='" + description + '\'' +
", prince=" + prince +
'}';
}
}
StudentController:
#RestController
#RequestMapping("/products")
public class ProductController {
#PostMapping
public ResponseEntity<ProductDto> createProduct(#RequestBody Product product) {
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
return ResponseEntity.created(location).body(productService.createProduct(product));
}
}
In above entity, I want using #MockMvc test createProduct. If name in product is null, i want show message in #MockMvc . It look like: "name can not null" . If pass, i don't want show it. Bellow my test:
#Test
public void givenProductURIWithPost_whenMockMVC_thenVerifyResponse() {
this.mockMvc.perform(post("/products")).andDo(print())
.andExpect(status().isOk()).andExpect(content()
.contentType("application/json;charset=UTF-8"))
}
I have two question:
1.How to show message "name can not null" if name in product is
null in #mockmvc.
2. If my project in 20 field in Products entity : Example: name,category.. I can test sequence field in Products or only test
one time contain all field.

My Spring jpaRepository throws a TransactionRequiredException when i'm trying to delete an object

I have a RESTcontroller that has a delete mapping like so:
#DeleteMapping("/deleterequest/{custId}")
//#Transactional
public ResponseEntity<?> delete(#PathVariable long custId) {
log.info("entering deleterequest");
LeaveQuery deleteLeaveQuery = leaveQueryRepository.findOne(custId);
log.info("condition" + deleteLeaveQuery.getStatus().equals("Onbehandeld"));
// if (!deleteLeaveQuery.getStatus().equals("Onbehandeld"))
// return ResponseEntity.badRequest().build();
//deleteLeaveQuery.setAccount(null);
//leaveQueryRepository.save(deleteLeaveQuery);
log.info("is deleteLeaveQuery null? " + (deleteLeaveQuery == null));
//leaveQueryRepository.delete(deleteLeaveQuery);
//leaveQueryRepository.delete(deleteLeaveQuery.getId());
leaveQueryRepository.deleteById(deleteLeaveQuery.getId());
accountService.sendLeaveRequestCanceledNotification(deleteLeaveQuery);
return ResponseEntity.ok().build();
}
When I use the regular (built-in) delete function of my leaveQueryRepository, I get no error, not during log INFO mode nor with log DEBUG mode on. However the object doesn't get deleted either. Its still in the database after the delete method was called. When I make a custom spring repository method called deleteById I get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
at
I have no idea what is causing this error. The jparepository looks like this:
#Repository
public interface LeaveQueryRepository extends JpaRepository<LeaveQuery, Long> {
//#Modifying
public void deleteById(long id);
}
The LeaveRequest object looks like this:
#Entity
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
scope = LeaveQuery.class)
public class LeaveQuery implements Serializable {
#Id
#GeneratedValue
private Long id;
private Date startDate;
private Date endDate;
private String status = "Onbehandeld";
private String reason ="";
private int totalHours;
private String processedBy;
#ManyToOne(fetch = FetchType.EAGER) //, cascade = CascadeType.PERSIST
#JoinColumn(name = "FK_account", nullable = true)
private Account account;
public String getProcessedBy() {
return processedBy;
}
public void setProcessedBy(String processedBy) {
this.processedBy = processedBy;
}
public int getTotalHours() {
return totalHours;
}
public void setTotalHours(int totalHours) {
this.totalHours = totalHours;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "LeaveQuery{" +
"id=" + id +
", startDate=" + startDate +
", endDate=" + endDate +
", denialReason='" + reason + '\'' +
'}';
}
}
It has a relation with an Account object which looks like this:
#Entity
//#JsonIgnoreProperties
//#JsonIdentityInfo(
// generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id",
// scope = Account.class)
public class Account implements Serializable {
#Id
#GeneratedValue
private Long id;
private String username;
private String password;
private String name;
private boolean admin;
private boolean enabled;
private int remainingStatutoryLeaveHours = 240;
private int remainingNonStatutoryLeaveHours = 60;
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL)
List<LeaveQuery> leaveQueryList;
//
#OneToMany(fetch = FetchType.LAZY, mappedBy = "account", cascade = CascadeType.ALL)
List<LaborPeriod> laborperiods = new ArrayList<>();
#OneToOne
private Person person;
#Enumerated
UserRole userRole = UserRole.USER;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(UserRole userRole) {
this.userRole = userRole;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<LaborPeriod> getLaborperiods() {
return laborperiods;
}
public void setLaborperiods(List<LaborPeriod> laborperiods) {
this.laborperiods = laborperiods;
}
public List<LeaveQuery> getLeaveQueryList() {
return leaveQueryList;
}
public void setLeaveQueryList(List<LeaveQuery> leaveQueryList) {
this.leaveQueryList = leaveQueryList;
}
public int getRemainingStatutoryLeaveHours() {
return remainingStatutoryLeaveHours;
}
public void setRemainingStatutoryLeaveHours(int remainingStatutoryLeaveHours) {
this.remainingStatutoryLeaveHours = remainingStatutoryLeaveHours;
}
public int getRemainingNonStatutoryLeaveHours() {
return remainingNonStatutoryLeaveHours;
}
public void setRemainingNonStatutoryLeaveHours(int remainingNonStatutoryLeaveHours) {
this.remainingNonStatutoryLeaveHours = remainingNonStatutoryLeaveHours;
}
#Override
public String toString() {
return "Account{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", admin=" + admin +
", enabled=" + enabled +
", remainingStatutoryLeaveHours=" + remainingStatutoryLeaveHours +
", remainingNonStatutoryLeaveHours=" + remainingNonStatutoryLeaveHours +
", userRole=" + userRole +
'}';
}
}
Does anyone know what could be causing this error?
Any help would be appreciated.
All controller methods should be none transactional.
You should add one more layer between Controller and Repository (Service layer) and put #Transactional on Service class or put this annotation on your method in this Service class.
It should be Controller -> Service -> Repository
To let #Transactional work you should init TransactionalManager.
You can add something like this in your Persistence Configuration
#Bean
public JpaTransactionManager transactionManager() throws IOException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
Use orphanRemoval = true.
Try to update your Account class like so
#JsonIgnore
#OneToMany(fetch = FetchType.EAGER, mappedBy = "account", cascade = CascadeType.ALL, orphanRemoval = true)
List<LeaveQuery> leaveQueryList;
Also check out this question.

Conditional update in Dynamo Db using mapper

I am trying to do a conditional update on a field Score in my table based on the condition that marks to be updated are greater than the current score.
I have written following code ,
StudentDO temp = mapper.load(StudentDO.class, student.getId());
temp.setScore(marks);
ArrayList<AttributeValue> list = new ArrayList<AttributeValue>();
list.add(new AttributeValue().withN(Oldmarks.toString()));
Map<String,ExpectedAttributeValue> expectedAttributes = new
HashMap<String,ExpectedAttributeValue>();
ExpectedAttributeValue expectedAttributeValue = new
ExpectedAttributeValue().withAttributeValueList(list)
.withComparisonOperator("GT");
expectedAttributes.put("Score",expectedAttributeValue);
mapper.save(temp, new DynamoDBSaveExpression().withExpected(expectedAttributes));
This is failing with this runtime exception
com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException: The conditional request failed (Service: null; Status Code: 400; Error Code: ConditionalCheckFailedException; Request ID: null)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.amazonaws.services.dynamodbv2.local.embedded.DDBExceptionMappingInvocationHandler.handleDynamoDBLocalServiceException(DDBExceptionMappingInvocationHandler.java:87)
at com.amazonaws.services.dynamodbv2.local.embedded.DDBExceptionMappingInvocationHandler.invoke(DDBExceptionMappingInvocationHandler.java:66)
at com.sun.proxy.$Proxy19.updateItem(Unknown Source)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.doUpdateItem(DynamoDBMapper.java:854)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$2.executeLowLevelRequest(DynamoDBMapper.java:594)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:733)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:623)
at com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.save(AbstractDynamoDBMapper.java:128)
I am not able to debug why is it throwing Conditional Check Failed Exception.
I could make out the request is not properly formed , but not sure where is it malformed ?
I have tried to align it to these docs
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBSaveExpression.html
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/model/ExpectedAttributeValue.html
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/model/AttributeValue.html
My DB schema is this
#DynamoDBTable(tableName = "Student")
public class StudentDO {
#DynamoDBHashKey(attributeName = "Id")
private Integer id;
#DynamoDBAttribute(attributeName = "Name")
private String name;
#DynamoDBAttribute(attributeName = "Score")
private Integer score;
#Override
public String toString() {
return "Student [Name=" + name + ", id=" + id + ", score=" + score + "]";
}
}
Each DynamoDB attribute must have a public getter and setter, since DynamoDBMapper works on JavaBeans (a class with a no argument constructor, and getters + setters for each private var). Modify your class to this:
#DynamoDBTable(tableName = "Student")
public class StudentDO {
private Integer id;
private String name;
private Integer score;
#DynamoDBAttribute(attributeName = "Id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#DynamoDBAttribute(attributeName = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#DynamoDBAttribute(attributeName = "Score")
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
#Override
public String toString() {
return "Student [Name=" + name + ", id=" + id + ", score=" + score + "]";
}
}

java - Hibernate doesn't read object from database correctly

I am having some issues according Hibernate.
I have a more or less complex object structure that I want to save / load using the Hibernate EntityManager (version 4.3.5.Final). I managed to save it, but if I attempt to read the obejct, only the PK will be read. The EntityManager's find method returns null even with the correct PK so I am using its getReference method.
I still have troubles using the correct relationship (ManyToOne and such) so I most likely made a mistake there and I guess that is causing the problem.
Anyways.
My question is: How do i persist an object structure like this using Hibernate?
Here are the POJOs i am using:
EDIT: Updated the Code
CalculationList:
#Entity(name = "calculation")
public class CalculationList implements EntityList {
#Id
private Date created;
#OneToMany(mappedBy = "", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Product> products;
public CalculationList(Date created) {
this.created = created;
this.products = new LinkedList<>();
}
public CalculationList(Date created, List<Product> products) {
this.created = created;
this.products = products;
}
public CalculationList() {
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> entities) {
this.products = entities;
}
#Override
public String toString() {
return "CalculationList{" +
"created=" + created +
", products=" + products +
'}';
}
}
CalulatorEntity:
#Entity(name = "calculator_entity")
public class CalculatorEntity implements Serializable {
#Id
private int id;
private CalculatorEntityType type;
private String name;
private int number;
#ManyToOne(cascade = CascadeType.ALL)
private Product product;
public CalculatorEntity(CalculatorEntityType type) {
this.type = type;
}
protected CalculatorEntity() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public CalculatorEntityType getType() {
return type;
}
public void setType(CalculatorEntityType type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public enum CalculatorEntityType {
GAS_PUMP, DELIVERY_BILL;
}
#Override
public String toString() {
return "CalculatorEntity{" +
"id=" + id +
", type=" + type +
", name='" + name + '\'' +
", product=" + product +
", number=" + number +
'}';
}
}
Product:
#Entity(name = "product")
public class Product implements Serializable {
#Id
private int id;
private String name;
private ProductType type;
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CalculatorEntity> entities;
public Product(String name, ProductType type) {
this.name = name;
this.type = type;
this.entities = new LinkedList<>();
}
/**
* JPA - Konstruktor
*/
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
public List<CalculatorEntity> getEntities() {
return entities;
}
public void setEntities(List<CalculatorEntity> entities) {
this.entities = entities;
}
#Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", type=" + type +
", entities=" + entities +
'}';
}
public enum ProductType {
FUEL("Treibstoff"), OIL("Öl"), OTHER("Verschiedenes");
private String name;
private ProductType(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
}
You are using the #OneToMany mapping with the wrong entity, instead of mapping Product class you are mapping CalculationList class, move the following configuration:
#OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CalculatorEntity> entities;
to the Product class.

Categories

Resources