How to check response of HTTP GET method using ID - spring

Here is my controller code:
#RequestMapping(value = RestURIConstants.GET_APP_MENU_LIST, method = RequestMethod.GET)
public #ResponseBody ComListMaster getCommonMasterByMasterId(#PathVariable("listid") Integer listId)
{
ComListMaster commonMaster = commonService.getCommonMasterList(listId);
logger.debug("Calling master list");
return commonMaster;
}
Above code give me the exception:
Caused by: java.lang.NumberFormatException: For input string: "{listid}"
Please tell me how to get GET response of above code.
Thanks in advance.
here is ComListMaster
public class ComListMaster extends BaseModel implements java.io.Serializable
{
private static final long serialVersionUID = 5408136749548491686L;
#Id
#Column(name = "LIST_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer listId;
#Column(name = "LIST_DESC")
private String description;
#Column(name = "LIST_VALUE")
private String value;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "comListMaster")
private Set<ComListDetails> comListDetails = new HashSet<ComListDetails>();
public Integer getListId()
{
return listId;
}
public void setListId(Integer listId)
{
this.listId = listId;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
public Set<ComListDetails> getComListDetails()
{
return comListDetails;
}
public void setComClientAddresses(Set<ComListDetails> comListDetails)
{
this.comListDetails = comListDetails;
}
#Override
public String toString()
{
return "ComListMaster [listId=" + listId + ", description=" + description + ", value=" + value
+ ", comListDetails=" + comListDetails + "]";
}
}
My exception is: java.lang.NumberFormatException: For input string: "{listid}"
API: public static final String GET_APP_MENU_LIST = "/api/app/common/master/{listid}";

You can remove ("listid")-its not mandatory , then it wont java.lang.NumberFormatException: For input string: "{}".
#RequestMapping(value = "/{listId}", method = RequestMethod.GET)
public #ResponseBody ComListMaster getCommonMasterByMasterId(#PathVariable Integer listId)
{
ComListMaster commonMaster = commonService.getCommonMasterList(listId);
logger.debug("Calling master list");
return commonMaster;
}

The code you posted is correct.
The error seems to indicate you are trying to go to the /api/app/common/master/{listid} url. Instead you should substitute the {listid} with a real id, for example /api/app/common/master/1

Related

Spring Data Elasticsearch Inheritance

Is there any way to make a super-class document (e.g. index name = user) and create two child classes (Admin, Guest) to save all this to user index but with different fields? E.g. Add to super-class field type and based on this field fetch right entity? ELK 7.19, Spring Data 4.3.1.
You can do that. Make the base class abstract. I have this in a test setup with the following classes:
#Document(indexName = "type-hints")
public abstract class BaseClass {
#Id
private String id;
#Field(type = FieldType.Text)
private String baseText;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBaseText() {
return baseText;
}
public void setBaseText(String baseText) {
this.baseText = baseText;
}
#Override
public String toString() {
return "BaseClass{" +
"id='" + id + '\'' +
", baseText='" + baseText + '\'' +
'}';
}
}
public class DerivedOne extends BaseClass {
#Field(type = FieldType.Text)
private String derivedOne;
public String getDerivedOne() {
return derivedOne;
}
public void setDerivedOne(String derivedOne) {
this.derivedOne = derivedOne;
}
#Override
public String toString() {
return "DerivedOne{" +
"derivedOne='" + derivedOne + '\'' +
"} " + super.toString();
}
}
public class DerivedTwo extends BaseClass {
#Field(type = FieldType.Text)
private String derivedTwo;
public String getDerivedTwo() {
return derivedTwo;
}
public void setDerivedTwo(String derivedTwo) {
this.derivedTwo = derivedTwo;
}
#Override
public String toString() {
return "DerivedTwo{" +
"derivedTwo='" + derivedTwo + '\'' +
"} " + super.toString();
}
}
interface TypeHintRepository extends ElasticsearchRepository<BaseClass, String> {
SearchHits<? extends BaseClass> searchAllBy();
}
#RestController
#RequestMapping("/typehints")
public class TypeHintController {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeHintController.class);
private final TypeHintRepository repository;
public TypeHintController(TypeHintRepository repository) {
this.repository = repository;
}
#GetMapping
public void test() {
List<BaseClass> docs = new ArrayList<>();
DerivedOne docOne = new DerivedOne();
docOne.setId("one");
docOne.setBaseText("baseOne");
docOne.setDerivedOne("derivedOne");
docs.add(docOne);
DerivedTwo docTwo = new DerivedTwo();
docTwo.setId("two");
docTwo.setBaseText("baseTwo");
docTwo.setDerivedTwo("derivedTwo");
docs.add(docTwo);
repository.saveAll(docs);
SearchHits<? extends BaseClass> searchHits = repository.searchAllBy();
for (SearchHit<? extends BaseClass> searchHit : searchHits) {
LOGGER.info(searchHit.toString());
}
}
}

Foregine key is not updating in spring boot Jpa

Basically, I am trying to establish a relationship between my two tables using spring boots.
And the relationship which I had used was the #onetoone and #onetomany relationship.
But after building the relationship and creating the table in MySQL whenever I run the program my foreign key is not updating.
The relationship is one user can have many contacts. I have tried unidirectional as well as bidirectional mapping but it is not working.
I want in contact table there will be a separate column for the foreign key. Based on that key I will show all contacts for that particular user.
This is my contact entity...
package com.example.jpa.contactEntities;
#Entity
#Table(name = "Contact")
public class ContactEntities {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long c_id;
private String c_name;
private String second_c_name;
private String c_work;
private String c_emali;
private String c_phone;
private String c_image;
#Column(length = 5000)
private String c_description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "contact_id")
private UserEntities userEntities;
public ContactEntities() {
super();
}
public ContactEntities(long c_id, String c_name, String second_c_name, String c_work, String c_emali,
String c_phone, String c_image, String c_description, UserEntities userEntities) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.second_c_name = second_c_name;
this.c_work = c_work;
this.c_emali = c_emali;
this.c_phone = c_phone;
this.c_image = c_image;
this.c_description = c_description;
this.userEntities = userEntities;
}
public long getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getSecond_c_name() {
return second_c_name;
}
public void setSecond_c_name(String second_c_name) {
this.second_c_name = second_c_name;
}
public String getC_work() {
return c_work;
}
public void setC_work(String c_work) {
this.c_work = c_work;
}
public String getC_emali() {
return c_emali;
}
public void setC_emali(String c_emali) {
this.c_emali = c_emali;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getC_image() {
return c_image;
}
public void setC_image(String c_image) {
this.c_image = c_image;
}
public String getC_description() {
return c_description;
}
public void setC_description(String c_description) {
this.c_description = c_description;
}
public UserEntities getUserEntities() {
return userEntities;
}
public void setUserEntities(UserEntities userEntities) {
this.userEntities = userEntities;
}
#Override
public String toString() {
return "ContactEntities [c_id=" + c_id + ", c_name=" + c_name + ", second_c_name=" + second_c_name + ", c_work="
+ c_work + ", c_emali=" + c_emali + ", c_phone=" + c_phone + ", c_image=" + c_image + ", c_description="
+ c_description + ", userEntities=" + userEntities + "]";
}
}
this is my user entity...
package com.example.jpa.userEntities;
#Entity
#Table(name = "UserEntities")
public class UserEntities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#NotBlank
#Size(min = 2, max = 20)
private String userName;
#NotBlank
#Column(unique = true)
#Email(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
private String userEmail;
#NotNull(message = "password should not be blank")
private String userPass;
private boolean enable;
private String role;
#Column(length = 500)
private String userAbout;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntities", orphanRemoval = true)
private List<ContactEntities> contactList = new ArrayList<>();
public UserEntities() {
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getRoll() {
return role;
}
public void setRoll(String role) {
this.role = role;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public List<ContactEntities> getContactList() {
return contactList;
}
public void setContactList(List<ContactEntities> contactList) {
this.contactList = contactList;
}
#Override
public String toString() {
return "UserEntities [userId=" + userId + ", userName=" + userName + ", userEmail=" + userEmail + ", userPass="
+ userPass + ", enable=" + enable + ", role=" + role + ", userAbout=" + userAbout + ", contactList="
+ contactList + "]";
}
}
Repository of Contact
package com.example.jpa.repo;
import java.util.List;
import com.example.jpa.contactEntities.ContactEntities;
public interface ContactRepo extends JpaRepository<ContactEntities, Integer> {
#Query("from ContactEntities as c where c.userEntities.userId=:u_Id")
public List<ContactEntities> findContactsByUser(#Param("u_Id") long l);
}
Repository of User
package com.example.jpa.repo;
import com.example.jpa.userEntities.UserEntities;
#EnableJpaRepositories
public interface UserRepository extends JpaRepository<UserEntities, Integer> {
#Query("select u from UserEntities u where u.userEmail=:userEmail")
public UserEntities getUserByUserName(#Param("userEmail") String userEmail);
}
User controller
package com.example.jpa.controller;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private ContactRepo contactRepo;
#ModelAttribute
public void addCommonData(Model model, Principal principal) {
String username = principal.getName();
System.out.println("UserName:-" + username);
UserEntities userEntities = this.userRepository.getUserByUserName(username);
System.out.println("User:- " + userEntities);
model.addAttribute("userEntities", userEntities);
}
//dash board home
#RequestMapping("/index")
public String dashboard(Model model, Principal principal) {
return "normal/user_dashboard";
}
// open add form handler
#GetMapping("/add-contact")
public String openAddContactForm(Model model) {
model.addAttribute("title", "Add contact");
model.addAttribute("contactEntitie", new ContactEntities());
return "normal/add_contact";
}
// processing and contact form
#PostMapping("/upload")
public String processContact(#ModelAttribute ContactEntities contactEntitie,
#RequestParam("userImage") MultipartFile multipartFile, Principal principal, Model model,
HttpSession session) {
try {
model.addAttribute("contactEntitie", new ContactEntities());
String name = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(name);
userEntities.getContactList().add(contactEntitie);
// processing and uploading file....
if (multipartFile.isEmpty()) {
System.out.println("File is empty");
} else {
// upload the the file and update
contactEntitie.setC_image(multipartFile.getOriginalFilename());
File saveFile = new ClassPathResource("static/img").getFile();
// bring the folder path...
Path path = Paths
.get(saveFile.getAbsolutePath() + File.separator + multipartFile.getOriginalFilename());
Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image is uploaded");
}
userRepository.save(userEntities);
System.out.println("Datas are :" + contactEntitie);
// message success
session.setAttribute("message", new Messages("Your Contact is added !!! Add more...", "success"));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
// error message
session.setAttribute("message", new Messages("Something went wrong !!! Try Again", "danger"));
}
return "normal/add_contact";
}
// show Contact handler
#GetMapping("/show-contacts")
public String showContact(Model model, Principal principal) {
model.addAttribute("title", "Show Contacts");
String userName = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(userName);
List<ContactEntities> contactList = contactRepo.findContactsByUser(userEntities.getUserId());
model.addAttribute("contactList", contactList);
return "normal/show_contacts";
}
}
All configuration class
User Details configuration
package com.example.jpa.Myconfiguration;
public class UserDetailsServiceImple implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// fetching data from DB
UserEntities userEntities = userRepository.getUserByUserName(username);
if (userEntities == null) {
throw new UsernameNotFoundException("Could not found user !!!");
}
CustomUserDetails customUserDetails = new CustomUserDetails(userEntities);
return customUserDetails;
}
}
package com.example.jpa.Myconfiguration;
public class CustomUserDetails implements UserDetails {
private UserEntities userEntities;
public CustomUserDetails(UserEntities userEntities) {
super();
this.userEntities = userEntities;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userEntities.getRoll());
return List.of(simpleGrantedAuthority);
}
#Override
public String getPassword() {
return userEntities.getUserPass();
}
#Override
public String getUsername() {
return userEntities.getUserEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Application property:-
#Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/smartcontact
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.NonRegisteringDriver
spring.jpa.properties.hibernate.dilact=org.hibernate.dialect.Mysql8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Count number of Item using Hibernate/JPA or JdbcTemplate

I am new to Spring/Hibernate/JPA. I have an entity class MovieEntity and MovieVersionEntity. MovieEntity has few details about the movie (like genre of movie) but MovieVersionEntity has more details about it (name, director...). So I want to count the number of movies (MovieVersionEntity) associated to the MovieEntity for the given type.
MovieEntity:
#Entity(name="MovieEntity")
#Table(name="Movie")
public class MovieEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="Id")
private long id;
#Column(name="IsDeleted")
private boolean isDeleted;
#Column(name="ModifiedDate")
#Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
#OneToOne()
#JoinColumn(name="MovieTypeId")
private MovieTypeEntity movieTypeEntity;
#OneToMany(mappedBy="movieEntity",optional = false)
private List<MovieVersionEntity> movieVersionEntity;
#Transient
//#Formula("select count(*) from movie_version mv where mv.id=id")
private int childCount;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public MovieTypeEntity getMovieTypeEntity() {
return movieTypeEntity;
}
public void setMovieTypeEntity(MovieTypeEntity movieTypeEntity) {
this.movieTypeEntity = movieTypeEntity;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public MovieVersionEntity getMovieVersionEntity() {
return movieVersionEntity;
}
public void setMovieVersionEntity(MovieVersionEntity movieVersionEntity) {
this.movieVersionEntity = movieVersionEntity;
}
public int getChildCount() {
return childCount;
}
public void setChildCount(int childCount) {
this.childCount = childCount;
}
}
MovieVersionEntity
#Entity(name = "MovieVersionEntity")
#Table(name="MovieVersion")
//#EntityListeners(AuditingEntityListener.class)
public class MovieVersionEntity {
#Id()
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="MovieId")
private long movieId;
#NotBlank
#Column(name="MovieName")
private String movieName;
#NotBlank
#Column(name="DirectorName")
private String directorName;
#NotBlank
#Column(name="Description")
private String description;
#Column(name="StopDate")
#Temporal(TemporalType.TIMESTAMP)
private Date stopDate;
#Column(name="DoneWatching")
private boolean doneWatching;
#Column(name="WatchDate")
#Temporal(TemporalType.TIMESTAMP)
//#CreatedDate
private Date watchDate;
#Column(name="ModifiedDate")
#Temporal(TemporalType.TIMESTAMP)
//#LastModifiedDate
private Date modifiedDate;
#ManyToOne(optional = false)
#JoinColumn(name="Id")
private MovieEntity movieEntity;
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getDirectorName() {
return directorName;
}
public void setDirectorName(String directorName) {
this.directorName = directorName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStopDate() {
return stopDate;
}
public void setStopDate(Date stopDate) {
this.stopDate = stopDate;
}
public boolean isDoneWatching() {
return doneWatching;
}
public void setDoneWatching(boolean doneWatching) {
this.doneWatching = doneWatching;
}
public Date getWatchDate() {
return watchDate;
}
public void setWatchDate(Date watchDate) {
this.watchDate = watchDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public long getMovieId() {
return movieId;
}
public void setMovieId(long movieId) {
this.movieId = movieId;
}
public MovieEntity getMovieEntity() {
return movieEntity;
}
public void setMovieEntity(MovieEntity movieEntity) {
this.movieEntity = movieEntity;
}
}
I have written a query but I am getting sql error for it
#Query(value = "select m.*, ct.ChildCount" +
"from (" +
"select mv.id, count(movie_id) as ChildCount " +
"from movie_version mv " +
"group by mv.id" +
") as ct join movie m " +
"on ct.id = m.id;",nativeQuery = true)
List<MovieEntity> getMoviesWithCount();
Error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select mv.id, count(movie_id) as ChildCount from movie_version mv group by mv.id' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_60]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_60]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_60]
at java.lang.reflect.Constructor.newInstance(Constructor.java:422) ~[na:1.8.0_60]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at
Also, I am not sure if this is a right way to do it. Is there any other way I can save the count in the Transient variable. I tried using #Formuala too, but that does not give me 0 count.
Formula:
#Formula("select count(*) from movie_version mv where mv.id=id")
This is the first time I am dealing with Transient variable and I am not sure how it maps to the entity if its not persisted in the db.
However, #Formula worked for me. #Transient and #Formula cannot go together. #Formula is read only so I do not have to worry about the data being persisted.
http://outbottle.com/hibernate-populating-an-unmapped-entity-field-with-count-using-formula/

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.

Null value returned from jsp form:options to controller

The value returned by the JSP page for the path constituency is NULL. I have opted for a drop down list to display all the possible constituencies that can be selected. I have elaborated on the problem below.
Here is the Person Class:
#Entity
#Table(name="person")
public class person{
#Id
#Column(name = "NIC")
private Integer NIC;
#Column(name= "firstname")
private String fname;
#Column(name= "lastname")
private String lname;
#ManyToOne
#JoinColumn(name= "constituency_id")
private constituency constituency;
#OneToOne
#JoinColumn(name="NIC")
private login log;
public person(){
this.NIC = 1234;
this.fname = "Undefined";
this.lname = "Undefined";
}
public person(String fname, String lname, Integer NIC) {
this.fname = fname;
this.lname = lname;
this.NIC = NIC;
}
public Integer getNIC() {
return this.NIC;
}
public void setNIC(Integer NIC) {
this.NIC = NIC;
}
public String getfname() {
System.out.println(this.fname);
return this.fname;
}
public void setfname(String name) {
this.fname = name;
}
public String getlname() {
return this.lname;
}
public void setlname(String lname) {
this.lname = lname;
}
public constituency getConstituency() {
return this.constituency;
}
public void setConstituency(constituency id) {
this.constituency = id;
}
public login getlogin() {
return this.log;
}
public void setlogin(login log) {
this.log = log;
}
#Override
public String toString() {
return this.lname + " : " + this.fname;
}
}
Here is the Constituency Class:
#Entity
#Table(name="constituency")
public class constituency {
#Column(name="address")
private String address;
#Column(name="name")
private String name;
#Id
#Column(name="constituency_id")
private Integer constituency_id;
#Column(name="noofvoters")
private Integer voters;
#OneToMany(mappedBy="constituency", cascade = {CascadeType.ALL})
private Set <person> persons;
public constituency(){
this.constituency_id = 0;
this.name = "Undefined";
this.address = "Undefined";
this.voters = 0;
}
public constituency(String name, String address, Integer voters, Integer id) {
this.name = name;
this.address = address;
this.voters = voters;
this.constituency_id = id;
}
public String getname() {
System.out.println(this.name);
return this.name;
}
public void setname(String name) {
this.name = name;
}
public String getaddress() {
System.out.println(this.address);
return this.address;
}
public void setaddress(String name) {
this.address = name;
}
public Integer getvoters() {
return this.voters;
}
public void setvoters(Integer voters) {
this.voters = voters;
}
public Integer getconstituency_id() {
return this.constituency_id;
}
public void setconstituency_id(Integer id) {
this.constituency_id = id;
}
#Override
public String toString() {
return this.name;
}
}
Here is the portion of the controller responsible for handling the operation:
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String add(Model model){
List <constituency> constit = constituencyDAO.details();
model.addAttribute("message", "Add a person for voting");
model.addAttribute("per", new person());
model.addAttribute("constituency", constit);
return "Add";
}
#RequestMapping(value="/Add", method=RequestMethod.POST)
public ModelAndView addperson(#ModelAttribute("per") person per, BindingResult bind){
System.out.println("In controller");
System.out.println(per.getfname()+" First-name");
System.out.println(per.getConstituency()+" constituency");
return hello();
}
Finally, this is the portion of the JSP page with the form:select tag:
<div class = "form-group">
<label for = "element1" class="control-label col-xs-2">Constituency ID</label>
<div class="col-xs-10">
<form:select path="constituency" name="constituency">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${constituency}" itemValue="constituency_id" itemLabel="name" />
</form:select>
<p>Constituency ID</p>
</div>
</div>
Now, the problem is that even though the JSP page is able to successfully display the constituency attribute in the form:options, when the "per" model attribute is retrieved in the controller, the value for constituency and only constituency is NULL.
Below is the output in Eclipse.
The Form:
The output in the RequestMethod.POST:

Resources