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();
Related
I want to store class Reservation that a user makes when going to a cinema to watch a movie and I can't figure out how to convert it so that room can store it in the data base.
Errors appear for members: places and codeQR.
Class Reservation:
#Entity(tableName = "reservations", foreignKeys = #ForeignKey(entity = UtilizatorMADA.class, parentColumns = "id", childColumns = "idUser"))
public class Reservation implements Serializable {
#PrimaryKey(autoGenerate = true)
private long idReservation;
private long idUser;
#Embedded private Film film;
private Time startTime;
private List<Integer> places;
private Bitmap codeQR;
#Ignore
public Reservation(){}
public Reservation(long idReservation, long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idReservation = idReservation;
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(long idUser, Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.idUser = idUser;
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
#Ignore
public Reservation(Film film, Time startTime, List<Integer> places, Bitmap codeQR) {
this.film = film;
this.startTime = startTime;
this.places = places;
this.codeQR = codeQR;
}
public long getIdReservation() {
return idReservation;
}
public void setIdReservation(long idReservation) {
this.idReservation = idReservation;
}
public long getIdUser() {
return idUser;
}
public void setIdUser(long idUser) {
this.idUser = idUser;
}
public void setPlaces(List<Integer> places) {
this.places = places;
}
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
public Time getStartTime() {
return startTime;
}
public void setStartTime(Time startTime) {
this.startTime = startTime;
}
public Bitmap getCodeQR() {
return codeQR;
}
public void setCodeQR(Bitmap codeQR) {
this.codeQR = codeQR;
}
public List<Integer> getPlaces() { return places; }
#Override
public String toString() {
return "Reservation{" +
"film=" + film +
", startTime=" + startTime +
", codeQR='" + codeQR + '\'' +
'}';
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Reservation that = (Reservation) o;
return Objects.equals(film, that.film) &&
Objects.equals(startTime, that.startTime) &&
Objects.equals(places, that.places);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public int hashCode() {
return Objects.hash(film, startTime, places);
}
}
Class Film:
#Entity(tableName = "films")
public class Film implements Serializable {
#PrimaryKey(autoGenerate = true)
private int idFilm;
private String title;
private String genre;
private String description;
private double rating;
private int imagePath;
private boolean isFavorite;
public Film(int idFilm, String title, String genre, String description, double rating, int imagePath, boolean isFavorite) {
this.idFilm = idFilm;
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
this.isFavorite = isFavorite;
}
#Ignore
public Film(String title, String genre, String description, double rating, int imagePath) {
this.title = title;
this.genre = genre;
this.description = description;
this.rating = rating;
this.imagePath = imagePath;
isFavorite = false;
}
#Ignore
public Film(String title) {
this.title = title;
}
public int getIdFilm() {
return idFilm;
}
public void setIdFilm(int idFilm) {
this.idFilm = idFilm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getImagePath() {
return imagePath;
}
public void setImagePath(int imagePath) {
this.imagePath = imagePath;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
return Objects.equals(title, film.title);
}
#Override
public int hashCode() {
return Objects.hash(title);
}
}
I also get the following error by the ReservationOfMoviesDao, which may or may not be related. The queries affected are: getReservationOfMoviesByUserId(long id), getReservationOfMovies() and getReservationOfMoviesByRservationId(long id);
error: The columns returned by the query does not have the fields [idFilm] in com.example.cinemaapp.model.ReservationMovie even though they are annotated as non-null or primitive. Columns returned by the query: [idReservation,idUser,film,startTime,places,codeQR]
Interface ReservationOfMoviesDao:
#Dao
public interface ReservationOfMoviesDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(ReservationMovie rm);
#Transaction
#Query("SELECT * FROM reservations where idUser = :id")
List<ReservationMovie> getReservationOfMoviesByUserId(long id);
#Transaction
#Query("SELECT * FROM reservations")
List<ReservationMovie> getReservationOfMovies();
#Transaction
#Query("SELECT * FROM reservations where idReservation = :id")
ReservationMovie getReservationOfMoviesByReservationId(long id);
}
If you could help me out please, I'd appreciate it.
You cant use entities inside other entities (e.g. Film in Reservation). You should either use "relationships between entities" or try "Embedded" annotation.
Reffer to this link for more info.
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.
I want to create totalHaveMoney I was try to looping data income - expense in totalMoney method, but this failed. It is only getting income from one data, so the calculation doesn't work.
Model :
public class MoneyManager {
String name, category;
String date, description, key;
Long income, expense, totalMoney;
public MoneyManager(String name, String category, String date, Long income,Long expense , String description) {
this.name = name;
this.category = category;
this.date = date;
this.income = income;
this.expense = expense;
this.description = description;
}
public MoneyManager() {
}
public Long totalMoney(){
Long haveMoney = getIncome();
for (int i = 0; i < this.getIncome(); i++){
haveMoney -= getExpense();
}
return haveMoney;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Long getExpense() {
return expense;
}
public void setExpense(Long expense) {
this.expense = expense;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Long getIncome() {
return income;
}
public void setIncome(Long income) {
this.income = income;
}
public Long getTotalMoney() {
return totalMoney;
}
public void setTotalMoney(Long totalMoney) {
this.totalMoney = totalMoney;
}
}
When im getting data:
MoneyManager money = moneyManagers.get(position);
Resources resources = context.getResources();
Locale rupiah = new Locale("id", "id");
holder.textName.setText(String.valueOf(money.totalMoney()));
holder.textDate.setText(money.getDate());
The result of money.totalMoney() is the same as income.
If you have a List of you can iterate through them and add
long sum = 0;
for (MoneyManager mm : listOfMoneyManager) { // or whatever your local variable is
sum += mm.getIncome() - mm.getExpense();
}
// after the iteration you have the total
System.out.println (sum);
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.
The problem is that I have a table product and my update script doesn't work aparently. It allwas return false.
Product.class
#DatabaseTable(tableName = "Product")
public class Product {
#DatabaseField(index = true, generatedId = true)
private int productId;
#DatabaseField
private String name;
#DatabaseField
private int quantity;
//#DatabaseField(canBeNull = true)
//private Integer categorie;
//http://logic-explained.blogspot.com.ar/2011/12/using-ormlite-in-android-projects.html
#DatabaseField
private int categorie;
//#ForeignCollectionField
//private ForeignCollection<Categorie> itemsCategorie;
#DatabaseField
private String description;
#DatabaseField
private String photo;
Product() {
}
public Product(int productId, String name, int quantity, int categorie, String description, String photo) {
super();
this.productId = productId;
this.name = name;
this.quantity = quantity;
this.categorie = categorie;
this.description = description;
this.photo = photo;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return description;
}
public void setAddress(String address) {
this.description = address;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public CharSequence getDesc() {
return null;
}
}
my script updateProduct
public boolean updateProduct(Product p) {
boolean ret = false;
if (productDao != null) {
try {
productDao = getDao(Product.class);
UpdateBuilder<Product, Integer> updateBuilder = productDao
.updateBuilder();
updateBuilder.updateColumnValue("name", p.getName());
updateBuilder.updateColumnValue("quantity", p.getQuantity());
updateBuilder.updateColumnValue("categorie", p.getCategorie());
updateBuilder.updateColumnValue("description", p.getDesc());
updateBuilder.updateColumnValue("photo", p.getPhoto());
// but only update the rows where the description is some value
updateBuilder.where().eq("productId", p.getProductId());
// actually perform the update
String str = updateBuilder.prepareStatementString();
// UPDATE `Product` SET `name` = 'gcd' ,`quantity` = 1
// ,`categorie` = 1 ,`description` = ? ,`photo` = '' WHERE
// `productId` = 0
if (productDao.update(updateBuilder.prepare()) != 1) {
ret = false;
} else {
productDao.refresh(p);
ret = true;
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
then I call it with a function like this, but allways return false :(
public boolean updateProduct(Product p) {
boolean ret = false;
try {
ret = getHelper().updateProduct(p);
} catch (Exception e) {
e.printStackTrace();
ret =false;
}
return ret;
}
I can create and delete but I can not update . I tried everything.
If you please take a moment to answer my question I will appreciate.
for other developers, if you come face to face with a problem like this you should ensure the table must have an identity key.
#DatabaseTable(tableName = "User")
public class User {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
public String ServiceUserId;
#DatabaseField
public boolean IsActive;
#DatabaseField
public String FirstName;
#DatabaseField
public String LastName;
#DatabaseField
public String Key;
#DatabaseField
public String Email;
}
The solution was
Simply get the Instance of the object Product from the DB then modify to finaly send to the updateProduct method.
for example first I need to create any method first to get an objet by ID
// get the Instance calling to the getProductByID
Product p = getHelper().getProductByID(p.getId())
//modify any value of the product
p.setFirstName("asd");
//call the update
ret = getHelper().updateProduct(p);
then my objects is Updated.
Put attention for the object Id(should be the same) and use the natif function update(Product);
In your case, you must override equals and hashCode.