Hibernate Named Query Error IllegalArgumentException and QueryParameterException - java

While I try to hit the table Data, I always get error. Here is my POJO:
public class Data extends BaseObject {
private String numb;
private String nip;
private String name;
private Timestamp startDate;
private Timestamp endDate;
private String status;
public String getNumb() {
return numb;
}
public void setNumb(String numb) {
this.numb = numb;
}
public String getNip() {
return nip;
}
public void setNip(String nip) {
this.nip = nip;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getStartDate() {
return startDate;
}
public void setStartDate(Timestamp startDate) {
this.startDate = startDate;
}
public Timestamp getEndDate() {
return endDate;
}
public void setEndDate(Timestamp endDate) {
this.endDate = endDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Data [numb=" + numb + ", nip=" + nip + ", name=" + name
+ ", startDate=" + startDate + ", endDate=" + endDate + ", status=" + status + "]";
}
}
Here are the errors I got:
By this, I get IllegalArgumentException: Parameter NIP does not exist as a named parameter:
This is in the Java file
Query query = getCurrentSession().createQuery("select dc.nip, dc.name, dc.startDate, dc.endDate, dc.status from com.model.Data dc where dc.nip = :NIP");
q.setString("NIP", NIP);
When I use the query.setParameter, I got the error org.hibernate.QueryParameterException: could not locate named parameter [NIP]:
Query query = getCurrentSession().createQuery("select dc.nip, dc.name, dc.startDate, dc.endDate, dc.status from com.model.Data dc where dc.nip = :NIP");
query.setParameter("NIP", NIP);
So I am currently lost and not knowing what should I fix and what's wrong with those. Any help is greatly appreciated.

Related

Having an issue retrieving list from database using Ecplise

I'm currently working on a coupon project. While working on my facade class, I encounter an issue getting a list of coupons that customer has purchased by entering his ID from a table with foreign keys.
The method I was using:
#Override
public List<Coupon> getPurchasedCoupons(int customerID) throws SQLException {
{
Connection connection = pool.getConnection();
ArrayList<Coupon> customerCoupon = new ArrayList<>();
ArrayList<Long> customerCouponID = new ArrayList<>();
Statement stmt = null;
long coupID = 0;
stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM `couponsystem`.`customers_vs_coupons` WHERE (`CUSTOMER_ID` = '?')");
while ((resultSet != null) && (resultSet.next())) {
coupID = resultSet.getLong("COUPON_ID");
customerCouponID.add(coupID);
}
Iterator<Long> myIterator = customerCouponID.iterator();
while (myIterator.hasNext()) {
Long couponID = myIterator.next();
resultSet = stmt.executeQuery(
"SELECT * FROM `couponsystem`.`customers_vs_coupons` where COUPON_ID = " + couponID);
while (resultSet.next()) {
Coupon coupon = new Coupon(resultSet.getInt(1), resultSet.getInt(2),
Category.categoryFor(resultSet.getInt(3)), resultSet.getString(4), resultSet.getString(5),
resultSet.getDate(6), resultSet.getDate(7), resultSet.getInt(8), resultSet.getDouble(9),
resultSet.getString(10));
customerCoupon.add(coupon);
}
}
ConnectionPool.getInstance().restoreConnection(connection);
return customerCoupon;
}
}
Coupon class:
import java.util.Date;
public class Coupon {
private int id;
private int companyID;
private Category category;
private String title;
private String description;
private Date startDate;
private Date endDate;
private int amount;
private double price;
private String image;
public Coupon(int companyID, Category category, String title, String description, Date startDate, Date endDate,
int amount, double price, String image) {
this.companyID = companyID;
this.category = category;
this.title = title;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.price = price;
this.image = image;
}
public Coupon(int id, int companyID, Category category, String title, String description, Date startDate,
Date endDate, int amount, double price, String image) {
this.id = id;
this.companyID = companyID;
this.category = category;
this.title = title;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.price = price;
this.image = image;
}
public Coupon() {
super();
}
public void setId(int id) {
this.id = id;
}
public void setCompanyID(int companyID) {
this.companyID = companyID;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
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 int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getId() {
return id;
}
public int getCompanyID() {
return companyID;
}
#Override
public String toString() {
return "Coupon: ID = " + id + ", Company ID = " + companyID + ", Category = " + category + ", Title = " + title
+ ", Description = " + description + ", Start Date = " + startDate + ", End Date = " + endDate
+ ", Amount = " + amount + ", Price = " + price + ", IMAGE = " + image;
}
}
Calling the method:
public List<Coupon> getCustomerCoupons() throws SQLException {
return coup.getPurchasedCoupons(customerID);
}
My SQL table:
Coupon_vs_Customer table contains only 2 rows. which both are foreign keys to other tables.
CustomerID is connected to table of 'CUSTOMERS' while coupon_ID is connected to table 'COUPONS'
CustomerID Coupon_ID
1 1
1 2
1 3
As you can see above customer with ID 1 owns 3 coupons, and I'm trying to read them in a list on my eclipse project.
I do not get any exception, however I get returned an empty arraylist. I cannot seem to solve this issue since I am quite new to JDBC.
Your first query tries to find customers with id = "?". Maybe this was an attempt to create a prepared statement but then you need a few more steps
String query = "SELECT COUPON_ID FROM couponsystem.customers_vs_coupons WHERE CUSTOMER_ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, customerID);
ResultSet resultSet = statement.executeQuery();

JPA 2.2: Using find method to retrieve data from mysqlDB

I´m using JPA 2.2(Openjpa) running on OpenLiberty and mysqlVer 15.1 Distrib 10.1.21-MariaDB.
I have an object call Account where I use the entityManager.find to retrieve a given record.
The record is indeed retrieved but only this column "status" returns null.
But when I do the manual select against the DB,the value is there.
My Entity class
Account
package br.com.rsm.model;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
//#XmlRootElement
#Entity
#Table(name = "tb_account")
#NamedQueries({
#NamedQuery(name="Account.findByEmail", query="SELECT a FROM Account a where a.email = :email"),
#NamedQuery(name="Account.findByCpf", query="SELECT a FROM Account a where a.cpf = :cpf"),
#NamedQuery(name="Account.findByUserId", query="SELECT a FROM Account a where a.userId = :userId")
})
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String fullname;
private String email;
private String birthdate;
private String cpf;
private String rg;
private String address;
private String addressNumber;
private String complement;
private String cep;
private String state;
private int city;
private String phone;
private String mobile;
private String carrier;
#Column(name = "status")
private String status;
private long leftSide;
private long rightSide;
private Timestamp created;
private String parentId;
private String parentSide;
private String networkSide;
private Timestamp activated;
private double points;
private String nickname;
private String nis;
private String whatsapp;
private long bank;
private String accountType;
private String branchNumber;
private String branchDigit;
private String accountNumber;
private String accountDigit;
private String accountOwner;
private String cpfAccountOwner;
private String facebookID;
private double career;
private double pb;
private int certID;
private String automaticRenovation;
private String emailPagamento;
#Transient
private Account rightSideAccount;
#Transient
private Account leftSideAccount;
#Transient
private boolean searchableBySignedInUser;
#Transient
private long totalCandidatosAgente;
#Transient
private long totalAgentes;
#Transient
private long totalAgentesBracoEsq;
#Transient
private long totalAgentesBracoDir;
#Transient
private long totalAnjos;
#Transient
private boolean cfaCompleto;
//#Transient
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "owner" )
List<Ticket> tickets = new ArrayList<Ticket>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("created DESC")
#JoinColumn(name = "accountId" )
private List<Score> scores = new ArrayList<Score>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#OrderBy("activated DESC")
#JoinColumn(name = "idAccount" )
private List<ProductAccount> productsAccount = new ArrayList<ProductAccount>();
#OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, orphanRemoval = true)
#JoinColumn(name = "origin" )
private List<Trade> trades = new ArrayList<Trade>();
/**
* Construtor
*/
public Account() {}
public List<Trade> getTrades() {
return trades;
}
public void setTrades(List<Trade> trades) {
this.trades = trades;
}
public List<ProductAccount> getProductsAccount() {
return productsAccount;
}
public void setProductsAccount(List<ProductAccount> productsAccount) {
this.productsAccount = productsAccount;
}
public List<Score> getScores() {
return scores;
}
public void setScores(List<Score> scores) {
this.scores = scores;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddressNumber() {
return addressNumber;
}
public void setAddressNumber(String addressNumber) {
this.addressNumber = addressNumber;
}
public String getComplement() {
return complement;
}
public void setComplement(String complement) {
this.complement = complement;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getLeftSide() {
return leftSide;
}
public void setLeftSide(long leftSide) {
this.leftSide = leftSide;
}
public long getRightSide() {
return rightSide;
}
public void setRightSide(long rightSide) {
this.rightSide = rightSide;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentSide() {
return parentSide;
}
public void setParentSide(String parentSide) {
this.parentSide = parentSide;
}
public String getNetworkSide() {
return networkSide;
}
public void setNetworkSide(String networkSide) {
this.networkSide = networkSide;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> tickets) {
this.tickets = tickets;
}
public Timestamp getActivated() {
return activated;
}
public void setActivated(Timestamp activated) {
this.activated = activated;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
#Transient
public String getShortName() {
if(fullname==null){
return "";
}
if (nickname == null || nickname.isEmpty() ) {
nickname = fullname;
}
if(nickname != null || !nickname.isEmpty()){
String[] arrTmp = fullname.replace("\n", " ").split(" ");
String shortName = "";
if(arrTmp.length >= 2){
shortName = arrTmp[0] + " " + arrTmp[1] ;
}else if(arrTmp.length >= 1){
shortName = arrTmp[0];
}
//Passo o limitador de tamanho para ambas situações.
if(shortName!=null){
if(shortName.length() > 20){
shortName = fullname.substring(0, 19) + "...";
}
}
return shortName;
}
return "";
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNis() {
return nis;
}
public void setNis(String nis) {
this.nis = nis;
}
public String getWhatsapp() {
return whatsapp;
}
public void setWhatsapp(String whatsapp) {
this.whatsapp = whatsapp;
}
public long getBank() {
return bank;
}
public void setBank(long bank) {
this.bank = bank;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getBranchDigit() {
return branchDigit;
}
public void setBranchDigit(String branchDigit) {
this.branchDigit = branchDigit;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountDigit() {
return accountDigit;
}
public void setAccountDigit(String accountDigit) {
this.accountDigit = accountDigit;
}
public String getAccountOwner() {
return accountOwner;
}
public void setAccountOwner(String accountOwner) {
this.accountOwner = accountOwner;
}
public String getCpfAccountOwner() {
return cpfAccountOwner;
}
public void setCpfAccountOwner(String cpfAccountOwner) {
this.cpfAccountOwner = cpfAccountOwner;
}
public String getFacebookID() {
return facebookID;
}
public void setFacebookID(String facebookID) {
this.facebookID = facebookID;
}
public double getCareer() {
return career;
}
public void setCareer(double career) {
this.career = career;
}
public double getPb() {
return pb;
}
public void setPb(double pb) {
this.pb = pb;
}
public int getCertID() {
return certID;
}
public void setCertID(int certID) {
this.certID = certID;
}
public String getAutomaticRenovation() {
return automaticRenovation;
}
public void setAutomaticRenovation(String automaticRenovation) {
this.automaticRenovation = automaticRenovation;
}
public String getEmailPagamento() {
return emailPagamento;
}
public void setEmailPagamento(String emailPagamento) {
this.emailPagamento = emailPagamento;
}
public Account getRightSideAccount() {
return rightSideAccount;
}
public void setRightSideAccount(Account rightSideAccount) {
this.rightSideAccount = rightSideAccount;
}
public Account getLeftSideAccount() {
return leftSideAccount;
}
public void setLeftSideAccount(Account leftSideAccount) {
this.leftSideAccount = leftSideAccount;
}
public boolean isSearchableBySignedInUser() {
return searchableBySignedInUser;
}
public void setSearchableBySignedInUser(boolean searchableBySignedInUser) {
this.searchableBySignedInUser = searchableBySignedInUser;
}
public long getTotalCandidatosAgente() {
return totalCandidatosAgente;
}
public void setTotalCandidatosAgente(long totalCandidatosAgente) {
this.totalCandidatosAgente = totalCandidatosAgente;
}
public long getTotalAgentes() {
return totalAgentes;
}
public void setTotalAgentes(long totalAgentes) {
this.totalAgentes = totalAgentes;
}
public long getTotalAgentesBracoEsq() {
return totalAgentesBracoEsq;
}
public void setTotalAgentesBracoEsq(long totalAgentesBracoEsq) {
this.totalAgentesBracoEsq = totalAgentesBracoEsq;
}
public long getTotalAgentesBracoDir() {
return totalAgentesBracoDir;
}
public void setTotalAgentesBracoDir(long totalAgentesBracoDir) {
this.totalAgentesBracoDir = totalAgentesBracoDir;
}
public long getTotalAnjos() {
return totalAnjos;
}
public void setTotalAnjos(long totalAnjos) {
this.totalAnjos = totalAnjos;
}
public boolean isCfaCompleto() {
return cfaCompleto;
}
public void setCfaCompleto(boolean cfaCompleto) {
this.cfaCompleto = cfaCompleto;
}
/**
* Adiciona uma nova classe Score
* #param score Score
*/
public void addScore(Score score) {
getScores().add(score);
}
public void addProductAccount(ProductAccount productAccount) {
getProductsAccount().add(productAccount);
}
public void addTrade(Trade trade) {
getTrades().add(trade);
}
#Override
public String toString() {
return "Account [id=" + id + ", userId=" + userId + ", fullname=" + fullname + ", email=" + email
+ ", birthdate=" + birthdate + ", cpf=" + cpf + ", rg=" + rg + ", address=" + address
+ ", addressNumber=" + addressNumber + ", complement=" + complement + ", cep=" + cep + ", state="
+ state + ", city=" + city + ", phone=" + phone + ", mobile=" + mobile + ", carrier=" + carrier
+ ", status=" + status + ", leftSide=" + leftSide + ", rightSide=" + rightSide + ", created=" + created
+ ", parentId=" + parentId + ", parentSide=" + parentSide + ", networkSide=" + networkSide
+ ", activated=" + activated + ", points=" + points + ", nickname=" + nickname + ", nis=" + nis
+ ", whatsapp=" + whatsapp + ", bank=" + bank + ", accountType=" + accountType + ", branchNumber="
+ branchNumber + ", branchDigit=" + branchDigit + ", accountNumber=" + accountNumber + ", accountDigit="
+ accountDigit + ", accountOwner=" + accountOwner + ", cpfAccountOwner=" + cpfAccountOwner
+ ", facebookID=" + facebookID + ", career=" + career + ", pb=" + pb + ", certID=" + certID
+ ", automaticRenovation=" + automaticRenovation + ", emailPagamento=" + emailPagamento
+ ", rightSideAccount=" + rightSideAccount + ", leftSideAccount=" + leftSideAccount
+ ", searchableBySignedInUser=" + searchableBySignedInUser + ", totalCandidatosAgente="
+ totalCandidatosAgente + ", totalAgentes=" + totalAgentes + ", totalAgentesBracoEsq="
+ totalAgentesBracoEsq + ", totalAgentesBracoDir=" + totalAgentesBracoDir + ", totalAnjos=" + totalAnjos
+ ", cfaCompleto=" + cfaCompleto + ", tickets=" + tickets + ", scores=" + scores + ", productsAccount="
+ productsAccount + ", trades=" + trades + "]";
}
}
And this is my select result( snapshot table is to big )
[
id=2111,
userId=99YWK,
fullname=PatrickRibeiroBraz,
email=null,
birthdate=null,
cpf=null,
rg=null,
address=null,
addressNumber=null,
complement=null,
cep=null,
state=null,
city=0,
phone=null,
mobile=null,
carrier=null,
status=null,
leftSide=0,
rightSide=0,
created=2018-06-1212: 09: 29.0,
parentId=999I2,
parentSide=null,
networkSide=null,
activated=null,
points=0.0,
nickname=null,
nis=null,
whatsapp=null,
bank=0,
accountType=null,
branchNumber=null,
branchDigit=null,
accountNumber=null,
accountDigit=null,
accountOwner=null,
cpfAccountOwner=null,
facebookID=null,
career=0.0,
pb=0.0,
certID=0,
automaticRenovation=null,
emailPagamento=null,
rightSideAccount=null,
leftSideAccount=null,
searchableBySignedInUser=false,
totalCandidatosAgente=0,
totalAgentes=0,
totalAgentesBracoEsq=0,
totalAgentesBracoDir=0,
totalAnjos=0,
cfaCompleto=false,
tickets={
IndirectList: notinstantiated
},
scores={
IndirectList: notinstantiated
},
productsAccount={
IndirectList: notinstantiated
},
trades={
IndirectList: notinstantiated
}
]
ID fullname status
2111 Patrick Ribeiro Braz C
Has anyone went through this before?

Unknown column when trying to add data to a database

I am working on a simple CRUD project using Spring, Hibernate & JPA.
It's a basic coupon system, Coupon object has parameters, one of them is Coupon Type. When typing in the vales in the jsp which is bound to the server:
<h1> Create Coupon </h1>
<form:form action="company/create" method="POST" modelAttribute="theCoupon">
<input name="title"/>
<input name="startDate"/>
<input name="endDate"/>
<input name="amount"/>
<input name="message"/>
<input name="price"/>
<input name="image"/>
<select name="couponType">
<option>SPORTS</option>
<option>GAMING</option>
</select>
<input type="submit" value="submit">
</form:form>
this is the controller :
#PostMapping("/add")
public String newCoupon(Model theModel) {
List<CouponType> couponType = new ArrayList<CouponType>( Arrays.asList(CouponType.values()));
System.out.println(couponType);
theModel.addAttribute("couponType", couponType);
theModel.addAttribute("theCoupon", new Coupon());
return "add";
}
#RequestMapping("/create")
public String add(#ModelAttribute("theCoupon") Coupon theCoupon) {
theCoupon.setId(0);
System.out.println(theCoupon);
couponService.save(theCoupon);
return "savedCoupon";
}
I am getting this error:
java.sql.SQLSyntaxErrorException: Unknown column 'coupon0_.coupon_type' in 'field list'
Here is a screenshot of the database structure, the names are the same I have no idea whats the problem.
Also, here is the Coupon pojo:
#Entity
#Table(name = "coupon")
public class Coupon {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "title")
private String title;
#Column(name = "startDate")
private String startDate;
#Column(name = "endDate")
private String endDate;
#Column(name = "amount")
private int amount; // decrease amount on every customer purchase
#Column(name = "couponType")
private String couponType;
#Column(name = "message")
private String message;
#Column(name = "price")
private double price;
#Column(name = "image")
private String image;
public Coupon(long id, String title, String startDate, String endDate, int amount, String couponType,
String message, double price, String image) {
super();
this.id = id;
this.title = title;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.couponType = couponType;
this.message = message;
this.price = price;
this.image = image;
}
public Coupon() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getCouponType() {
return couponType;
}
public void setCouponType(String couponType) {
this.couponType = couponType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Override
public String toString() {
return "Coupon [id=" + id + ", title=" + title + ", startDate=" + startDate + ", endDate=" + endDate
+ ", amount=" + amount + ", couponType=" + couponType + ", message=" + message + ", price=" + price
+ ", image=" + image + "]";
}
}
Hope anyone of you could spot the problem, any help would be appreciated!
[SOLVED]
The problem was that I was using two words in my var, like couponType, would be coupon_type on the data base.
changed it to type only, the pojo & the database & now it works fine!
hope this helps to anyone that had this problem.

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.

Springboot REST application should accept and produce both XML and JSON

I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency.
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.5.4</version>
</dependency>
I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped to Java Object. The following is my Resource class.
#Configuration
#ImportResource("/application-context.xml")
#EnableAutoConfiguration
#ResponseBody
#RequestMapping("/match")
public class MatchResource {
private static final Logger logger = LogManager.getLogger(MatchResource.class);
#Autowired
private MatchService matchService;
#RequestMapping(method = RequestMethod.POST)
#Consumes({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
#Produces({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
//#Produces( MediaType.APPLICATION_XML)
public Response matchRequest(#RequestBody MatchRequest matchRequest,
#Context HttpServletRequest headers) throws Exception {
Response resp = null;
MiniMatchResponse output = null;
// Headers are store in the "headers" object. To retrieve a specific header, please take a look at the below statement
String apiUser = headers.getHeader("Api-User");
UUID randID = UUID.randomUUID();
logger.info("Get Match for with ID: " + randID);
// Get service profile from headers via MatchConstants.SERVICE_PROFILE_HEADER
String serviceProfile = "";
try {
//TODO: MatchService should return MatchResponse Object
//Json OutPut
output = matchService.findResponse(matchRequest, serviceProfile);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
logger.debug("Match Request: " + matchRequest.toString());
} catch (ErrorException e) {
logger.error(e.getMessage(), e);
}
// Form Response
resp = Response.status(200).entity(output).build();
return resp;
}
The below is my Request Object
package com.infoconnect.api.dto.Match;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class MatchRequest implements Serializable {
// Gets or sets the RequestType of request this represents.
// Allowed values are "Company", "People" and "Any".
private String requestType;
private String name;
private String companyName;
private String streetAddress;
private String streetAddress2;
private String city;
private String stateProvince;
private String postalCode;
private String country;
private String serviceProfile;
private String resourceType;
private int limit;
private Integer confidence;
private String phone;
private Boolean includeHistorical;
private Boolean includeNonVerified;
private String requestId;
private List<String> fields;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getServiceProfile() {
return serviceProfile;
}
public void setServiceProfile(String serviceProfile) {
this.serviceProfile = serviceProfile;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public Integer getConfidence() {
return confidence;
}
public void setConfidence(Integer confidence) {
this.confidence = confidence;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getIncludeHistorical() {
return includeHistorical;
}
public void setIncludeHistorical(Boolean includeHistorical) {
this.includeHistorical = includeHistorical;
}
public Boolean getIncludeNonVerified() {
return includeNonVerified;
}
public void setIncludeNonVerified(Boolean includeNonVerified) {
this.includeNonVerified = includeNonVerified;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
#Override
public String toString() {
return "MatchRequest{" +
"requestType='" + requestType + '\'' +
", name='" + name + '\'' +
", companyName='" + companyName + '\'' +
", streetAddress='" + streetAddress + '\'' +
", streetAddress2='" + streetAddress2 + '\'' +
", city='" + city + '\'' +
", stateProvince='" + stateProvince + '\'' +
", postalCode='" + postalCode + '\'' +
", country='" + country + '\'' +
", serviceProfile='" + serviceProfile + '\'' +
", resourceType='" + resourceType + '\'' +
", limit=" + limit +
", confidence=" + confidence +
", phone='" + phone + '\'' +
", includeHistorical=" + includeHistorical +
", includeNonVerified=" + includeNonVerified +
", requestId='" + requestId + '\'' +
", fields=" + fields +
'}';
}
}
JSON request and Response works fine. Can you please help me how to Include XML request and Response in my application.
Try to add a #XmlRootElement(name="myRootTag") JAXB annotation with the tag you use as the root tag to the class MatchRequest. I have had similar issues when using both XML and JSON as transport format in a REST request, but using moxy instead of Jackson. In any case, proper JAXB annotations are necessary to convert to/from XML (XML is much pickier in this respect than JSON).
Jackson XML is supposed to support JAXB annotations, and if this does not work, it has an own set of similar annotations that are incompatible to JAXB (see https://github.com/FasterXML/jackson-dataformat-xml and https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations)

Categories

Resources