Able to persist data using entitymanager.persist() but unable to get using entitymanager.find() in spring hibernate application - spring

This is my customer entity
#Entity
public class Customer
{
#Id
private String account_no;
private String customer_name,father_name,gender, phone, email, aadhaar; // phone no is varchar because I'll do validation in angular.
private double salary;
// one customer can have one loan. Relation is unidirectional
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="account_no")
private Loan loan;
public Customer() {}
#Override
public String toString() {
return "CustomerInfo [account_no=" + account_no + ", customer_name=" + customer_name + ", phone=" + phone
+ ", email=" + email + ", aadhaar=" + aadhaar + ", salary="
+ salary + ", loan=" + loan + "]";
}
}
Now this is my Loan entity
#Entity
public class Loan
{
#Id
#Column(name="account_no")
private String account_no; // making this as foreign key will not allow any holder to take loan again.
private String type;
private String issue_date;
private String last_payment;
private double loan_amount;
private double emi_amount;
private int emi_balance;
public Loan() {
}
#Override
public String toString() {
return "LoanInfo [account_no=" + account_no + ", type=" + type + ", loan_amount=" + loan_amount
+ ", emi_amount=" + emi_amount + ", emi_balance=" + emi_balance + ", issue_date=" + issue_date + "]";
}
}
Now the code of Dao layer
The findCustomer() function is returning null.
In dao findLoan() and addCustomer() is working fine.Even I've checked database , it is persisting data to database.
Database which I'm using is mysql and hibernate is used to implement the application. Spring mvc is used .
#Repository("bankDao")
#Transactional
public class BankDao {
#PersistenceContext
EntityManager em;
// It add customer details and loan details like emi while sanctioning any loan.
public void addCustomer(Customer customer) throws RevokeLoanException
{
try {
em.persist(customer);
}
catch(Exception e) {
throw new RevokeLoanException();
}
}
// for customer details
public Customer findCustomer(String accNo) throws LoanNotFoundException{
System.out.println(em.find(Customer.class, accNo));
Customer customer=em.find(Customer.class, accNo);
if(customer==null)
throw new LoanNotFoundException();
return customer;
}
// useful while paying emi
public Loan findLoan(String acc_no) throws LoanNotFoundException{
// TODO Auto-generated method stub
Loan loan=em.find(Loan.class, acc_no);
if(loan==null)
throw new LoanNotFoundException();
return loan;
}
Problem arising in controller . Controller is not working in the specific way for id=2020-04-30T23:22:00.210
Api call = http://localhost:8082/LoanBackEnd/loan/loanStatus/2020-04-30T23:22:00.210
#GetMapping("/loanStatus/{id}")
public ResponseEntity<Map<String, String>> loanStatus(#PathVariable String id) throws LoanNotFoundException{
System.out.println(id+" which got");
Map<String,String> response=bankService.loanStatus(id);
return new ResponseEntity<Map<String,String>>(response,HttpStatus.OK);
}
That print line is returning me 2020-04-30T23:22:00 in place of 2020-04-30T23:22:00.210

Related

I can't get an entity ID in spring boot

I am learning Spring-Boot and I'm doing a little project to practice, but I have a problem.
This is a simple authentication app, you can register and log in. My aim is: If you log in your username should be appeared, and for further functions I need the ID as well.
So I have this code:
#PostMapping("/main")
public String login(#ModelAttribute Users user, Model model) {
time = sdf.format(new Date());
Users correctUser = serv.selectUser(user.getName(), user.getPassword());
if (correctUser != null) {
//Users data
login_name = user.getName();
actual_user_id = user.getId();
model.addAttribute("given_name", login_name);
System.out.println("DEBUG: " + user);
System.out.println(time + " Successful");
return "main_screen";
} else {
System.out.println(time + " Log in failed");
return "error_page";
}
}
I can get and storage the name well in login_name, but with the ID I have some problems. As you can see I use user.getId() same as with name, but either way I get null and can't storage the ID in my actual_user_id variable.
Here is my repository:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Optional<Users> findFirstByName(String name);
Optional<Users> findUserByNameAndPassword(String name, String password);
}
And my service method:
public Users authentication(String name, String password) {
return repo.findUserByNameAndPassword(name, password).orElse(null);
}
EDIT: And this is my Users class
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String password;
private String email;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", passowrd='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
I think it should work, but I can't find the problem.
Can anyone help me?
As I can see, I get the name and the password with the findUserByNameAndPassword() and nothing else, however I should I suppose.
You look to be trying to get your id from the user passed to you in the post request:
actual_user_id = user.getId();
Try getting your information from the user you retrieved from the database:
actual_user_id = correctUser.getId();

Updating a table to contain an image

I have successfully created an entity and can post to it. I wish to be able to update a column of the table with a blob file. When I do the post request I get a success response however the row is not updated
This is the entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Service
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long categoryId;
#NotNull
#Column(unique=true)
#Size(min = 5, max = 20)
private String categoryName;
#Column(columnDefinition = "MEDIUMBLOB")
private byte[] categoryImage;
#NotNull
#Size(min = 10, max = 50)
private String categoryDescription;
}
The PUT request for the image upload
#PutMapping("/categories/{categoryId}/upload")
public ResponseEntity<ResponseMessage> uploadImage(#PathVariable("categoryId") long catID,
#RequestParam() MultipartFile file) {
Optional<Category> category = catService.listCategoryById(catID);
if (category.isPresent()) {
try {
Category _category = category.get();
_category.setCategoryImage(imgService.storeImage(file));
return new ResponseEntity<>(
new ResponseMessage("Uploaded " + file.getOriginalFilename() + " successfully!"),
HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(new ResponseMessage("Failed to upload " + file.getOriginalFilename() + "!"),
HttpStatus.EXPECTATION_FAILED);
}
} else {
return new ResponseEntity<>(new ResponseMessage("Category Does not exist"), HttpStatus.NOT_FOUND);
}
}
The image service
#Service
public class ImageService {
public byte[] storeImage(MultipartFile file) throws IOException {
return file.getBytes();
}
}
When I do the PUT request I get this
However the database is not updated. The image column remains null
Do you have an idea why?
I don't see service.save() call in your controller code. Are you persisting that _category entity?
try {
Category _category = category.get();
_category.setCategoryImage(imgService.storeImage(file));
categoryService.save(_category);
return new ResponseEntity<>(
new ResponseMessage("Uploaded " + file.getOriginalFilename() + " successfully!"),
HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(new ResponseMessage("Failed to upload " + file.getOriginalFilename() + "!"),
HttpStatus.EXPECTATION_FAILED);
}

Not persisting entity with thymeleaf, spting data and r2dbc

Im trying to create Skill entity through Thymeleaf form and post it:
controller's endpoint
#PostMapping("/add")
public String addSkill(#ModelAttribute Skill skill){
log.info( " orly? "+ (skill== null));
log.info(skill.getName() + " name was set");
log.info(skill.getId() + " i<--d");
log.info(skill.getLevel() + " level was set");
log.info(skill.getPriority() + " prior was set");
log.info(skill.getSkillGroupName() + " group id was set");
service.add(skill);
return TEMPLATE;
}
service's method
#Override
public Mono<Skill> add(Skill skill) {
log.debug("SKILL IS ______ "+ skill.getName() + " ____WAS SAVED");
return repository.save(skill);
}
repo
#Repository
public interface SkillRepository extends ReactiveCrudRepository<Skill, UUID> {
Mono<UUID> removeById(UUID id);
}
entity implements Persistable
#Data
#Table
#NoArgsConstructor
#AllArgsConstructor
public class Skill implements Persistable<UUID> {
#Id
private UUID id;
#Column("skill_name")
private String name;
private Level level;
private Priority priority;
#Column("skill_group_name")
private String skillGroupName;
#Override
public boolean isNew() {
boolean result = Objects.isNull(id);
this.id = result ? UUID.randomUUID() : this.id;
return result;
}
}
Main class is annotated with #EnableR2dbcRepositories.
When I submit form, I get the log, confirming that entity is not null, all fields but id aren't nulls. And that's all, service's method add(Skill skill) never produce logs, neither postgres shows tuple. Any ideas?

DAO instance not working in service class - NullPointerException

In my spring boot project I created a Repository interface (which extends CRUDRepository) and an Entity class of the Table in my DB.
This is my Repo:
#Repository
public interface AuthPaymentDao extends CrudRepository<TFraudCard,String> {
#Query("SELECT t FROM TFraudCard t where t.tokenNumber = (?1)")
TFraudCard findByTokenNumber(String tokenNumber);
}
This is my Entity Class (TOKEN_NUMBER is the primary Key in the TFRAUDCARD TABLE):
#Entity
#Table(name = "TFRAUDCARD")
public class TFraudCard {
#Id
#Column(name="TOKEN_NUMBER")
private String tokenNumber;
#Column(name="TRANSACTIONNUMBER")
private int transactionNumber;
#Column(name="CARDNUMBER")
private int cardNumber;
#Column(name="DATEADDED", insertable = false, updatable = false, nullable = false)
private Timestamp dateAdded;
#Column(name="CALLINGENTITY", nullable = false)
private String callingEntity;
#Column(name="ACCOUNTID")
private String accountId;
#Column(name="ROUTINGNUMBER")
private String routingNumber;
#Column(name="BANKACCOUNTNUMBER")
private String bankAccountNumber;
#Column(name="COMMENTS")
private String comments;
#Column(name="USERID")
private String userId;
#Column(name="REMOVEDATE")
private Timestamp removeDate;
public String getTokenNumber() {
return tokenNumber;
}
public void setTokenNumber(String tokenNumber) {
this.tokenNumber = tokenNumber;
}
public int getTransactionNumber() {
return transactionNumber;
}
public void setTransactionNumber(int transactionNumber) {
this.transactionNumber = transactionNumber;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public Timestamp getDateAdded() {
return dateAdded;
}
public void setDateAdded(Timestamp dateAdded) {
this.dateAdded = dateAdded;
}
public String getCallingEntity() {
return callingEntity;
}
public void setCallingEntity(String callingEntity) {
this.callingEntity = callingEntity;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRoutingNumber() {
return routingNumber;
}
public void setRoutingNumber(String routingNumber) {
this.routingNumber = routingNumber;
}
public String getBankAccountNumber() {
return bankAccountNumber;
}
public void setBankAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getRemoveDate() {
return removeDate;
}
public void setRemoveDate(Timestamp removeDate) {
this.removeDate = removeDate;
}
public TFraudCard() {
super();
}
public TFraudCard(String tokenNumber, int transactionNumber, int cardNumber, Timestamp dateAdded,
String callingEntity, String accountId, String routingNumber, String bankAccountNumber, String comments,
String userId, Timestamp removeDate) {
super();
this.tokenNumber = tokenNumber;
this.transactionNumber = transactionNumber;
this.cardNumber = cardNumber;
this.dateAdded = dateAdded;
this.callingEntity = callingEntity;
this.accountId = accountId;
this.routingNumber = routingNumber;
this.bankAccountNumber = bankAccountNumber;
this.comments = comments;
this.userId = userId;
this.removeDate = removeDate;
}
#Override
public String toString() {
return "TFraudCard [tokenNumber=" + tokenNumber + ", transactionNumber=" + transactionNumber + ", cardNumber="
+ cardNumber + ", dateAdded=" + dateAdded + ", callingEntity=" + callingEntity + ", accountId="
+ accountId + ", routingNumber=" + routingNumber + ", bankAccountNumber=" + bankAccountNumber
+ ", comments=" + comments + ", userId=" + userId + ", removeDate=" + removeDate + "]";
}
}
My Service Class:
Autowiring the DAO instance inside my Service Class:
Implementing the DAO instance inside a Method in the Service Class:
private void fraudCheck(PaymentDetail paymentDetail) throws RegularPaymentBusinessException {
logger.info("INSIDE FRAUD CHECK METHOD");
String pmtInd=paymentDetail.getPmtInd();
logger.info("pmtInd: " + pmtInd);
String tokenizedCardNum=paymentDetail.getTokenizedCardNum();
logger.info("tokenizedCardNum: " + tokenizedCardNum);
if(pmtInd.equalsIgnoreCase(VepsConstants.GIFT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.CREDIT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.DEBIT_CARD_IDENTIFIER)) {
logger.info("INSIDE CARD CHECK");
TFraudCard fraudCard = authPaymentDao.findByTokenNumber(tokenizedCardNum);
logger.info("fraudCard Details: " + fraudCard.toString());
if(fraudCard!=null) {
logger.info("INSIDE EXCEPTION FLOW FOR CARD FRAUD CHECK");
throw new RegularPaymentBusinessException(VepsConstants._9966, VepsConstants._9966_MESSAGE, VepsConstants.FAILURE);
}
}
}
Even though I pass the same token Number (tokenizedCardNumber) in my method as the data in the TOKEN_NUMBER column of my TFRAUDCARD table I still get a NullPointerException when I try to print a toString() of the Entity Object.
Here is the NullPointerException on my cloudFoundry logs (Click on it to see zoomed image) :
I'm providing the DB details in my dev properties file:
I have gone over every scenario in my head for why it breaks but I still can't come up with an answer. I'm using my variable marked with #Id i.e. the Primary Key for my find() method in the Repository.
I'm also adding a #Query annotation just to be even more specific.
It still does not work.

Freemarker and Spring Validation Error Message Doesn't show up error messages

Hi I am working on spring boot 1.5.9.RELEASE and added spring-webmvc (4.3.13.RELEASE) dependency.
When I hit the submit button with some form data, it goes to server and checks if there're some errors, and prints it on console, and return back to form input page. but there is no error messages printed.
I submit the form with ModelAttribute object and the object is defined like below:
#Entity
#Table(name="MEMBER", uniqueConstraints={
#UniqueConstraint(columnNames={"USER_SEQ"}),
#UniqueConstraint(columnNames={"USER_EMAIL"}),
#UniqueConstraint(columnNames={"NICKNAME"})
})
#Data
#NoArgsConstructor
#RequiredArgsConstructor(staticName="of")
public class Member implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_SEQ", unique=true, nullable=false)
private Long userSeq;
#Email
#NotNull
#NonNull
#Column(name="USER_EMAIL", unique=true, nullable=false, length=50)
private String userEmail;
#NotNull
#NonNull
#Column(name="USER_PW", nullable=false, length=255)
private String userPw;
#NotNull
#Size(min=2, max=10)
#NonNull
#Column(name="NICKNAME", unique=true, nullable=false, length=20)
private String nickname;
#OneToOne(mappedBy="member", cascade=CascadeType.ALL)
private MemberSecurity security;
#Override
public String toString() {
return "Member [userSeq=" + userSeq + ", userEmail=" + userEmail + ", userPw=" + userPw + ", nickname="
+ nickname + "]";
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Member other = (Member) obj;
if (userSeq == null) {
if (other.userSeq != null)
return false;
} else if (!userSeq.equals(other.userSeq))
return false;
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userSeq == null) ? 0 : userSeq.hashCode());
return result;
}
}
In Controller which the submit goes through, I coded like below:
#RequestMapping(value="/join", method=RequestMethod.POST)
public String join(Model model, #Valid #ModelAttribute("join") Member member, BindingResult bindingResult, RedirectAttributes redirect){
if(bindingResult.hasErrors()){
viewNameChooser.joinForm(model);
System.err.println("ERROR COUNT: " + bindingResult.getErrorCount());
System.err.println("ERROR FIELD: " + bindingResult.getFieldError().getField());
System.err.println("ERROR CODE: " + bindingResult.getFieldError().getCode());
return go();
}
redirect.addFlashAttribute("joinSuccess", String.valueOf(memberService.save(member)) );
return "redirect:/member/login-form";
}
and the console output is :
ERROR COUNT: 1
ERROR FIELD: nickname
ERROR CODE: Size
Now I registered my custom error messages in classpath:META-INF/messages.properties:
Email.member.userEmail=It is not email type text.
NotNull.member.userEmail=Please, type your email id.
NotNull.member.userPw=Please, type your password.
NotNull.member.nickname=Please, type your nickname.
Size.member.nickname=The length of nickname must be greater than or equal 2 and less than or equal 10.
So far so good, but in my freemarker template, there is no error message displayed. I have coded like below:
<#assign form=JspTaglibs["http://www.springframework.org/tags/form"] />
<form id="join-form" action="<#spring.url '/member/join' />" method="post" style="width:600px; margin:0 auto;">
<#spring.bind "join" />
<#-- skipped -->
<#form.errors "*" />
<#-- skipped -->
</form>
<#form.errors "*" />
should contain error messages but it's not. Where am I missing? Help me please.
EDIT: I modified my controller method.
#RequestMapping(value="/join", method=RequestMethod.POST)
public ModelAndView join(#Valid #ModelAttribute("join") Member member, BindingResult bindingResult, RedirectAttributes redirect){
if(bindingResult.hasErrors()){
//viewNameChooser.joinForm(bindingResult);
ModelAndView modelAndView = new ModelAndView("template", bindingResult.getModel());
modelAndView.addObject("viewName", "joinForm");;
System.err.println("ERROR COUNT: " + bindingResult.getErrorCount());
System.err.println("ERROR FIELD: " + bindingResult.getFieldError().getField());
System.err.println("ERROR CODE: " + bindingResult.getFieldError().getCode());
return modelAndView;
}
ModelAndView modelAndView = new ModelAndView("redirect:/member/login-form");
redirect.addFlashAttribute("joinSuccess", String.valueOf(memberService.save(member)) );
return modelAndView;
}
Now I am using ModelAndView.

Resources