Primefaces datatable not saving data - primefaces

I'm new in Java and I trying to use primefaces datatable to save data in database. I can edit some value in datatable, but after refreshing nothing changed. Here is my code.
User.java
#Entity
#Table(name="users")
public class User {
private int id;
public String name = null;
public String surname = null;
public String username = null;
public String description = null;
public String email = null;
public String phone = null;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
#Column(name = "Name")
public String getName(){
return name;
}
public void setName(String Name){
this.name = Name;
}
#Column(name = "Surname")
public String getSurname(){
return surname;
LogonTest.java
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
}
TableBean.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;
#ViewScoped
#javax.faces.bean.ManagedBean(name = "tableBean")
public class TableBean implements Serializable {
private List<User> carsSmall;
public TableBean() {
carsSmall = new ArrayList<User>();
populateRandomCars(carsSmall, 9);
}
private void populateRandomCars(List<User> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new User());
}
public List<User> getCarsSmall() {
return carsSmall;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Edited", ((User) event.getObject()).getName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Cancelled", ((User) event.getObject()).getName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}

Related

How to query a many to many relationship in spring boot repository

I am trying to have the api return a list of notes, associated by a many to many relationship with labels, given a label id. Spring boot automatically created a bridge table called notes_tables with a notes_id field and a labels_id field. Spring Boot also created a notes table and a labels table. I attempted the following:
#Query(value="select * from notes join notes_labels on note.id=notes_id join labels on labels_id=labels.id where labels_id=:lid", nativeQuery=true)
public List<Note> findNotesForLabel(#Param("lid") int labelId);
I just need to get this to work but I am specifically curious if I can get it to work with jpa method query. Any query will do as long as it works though.
EDIT:
Entities
Note.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "notes")
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany
#JsonIgnore
private List<Label> labels;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Folder getFolder() {
return folder;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Label> getLabels() {
return labels;
}
public void setLabels(List<Label> labels) {
this.labels = labels;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Note)) {
return false;
}
Note note = (Note) o;
return id == note.id && Objects.equals(note, note.note) &&
Objects.equals(title, note.title) && Objects.equals(status,
note.status) && Objects.equals(user, note.user) &&
Objects.equals(folder, note.folder) && Objects.equals(labels,
note.labels);
}
#Override
public int hashCode() {
return Objects.hash(id, note, title, status, user, folder,
labels);
}
}
Label.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "labels")
public class Label {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany(mappedBy = "labels")
#JsonIgnore
private List<Note> notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Label)) {
return false;
}
Label label = (Label) o;
return id == label.id && Objects.equals(title, label.title) &&
Objects.equals(status, label.status) && Objects.equals(user,
label.user) && Objects.equals(folder, label.folder) &&
Objects.equals(notes, label.notes);
}
#Override
public int hashCode() {
return Objects.hash(id, title, status, user, folder, notes);
}
}
Services:
NoteService.java
package com.example.maapi.services;
import com.example.maapi.models.Folder;
import com.example.maapi.models.Note;
import com.example.maapi.models.User;
import com.example.maapi.repositories.FolderRepo;
import com.example.maapi.repositories.NoteRepo;
import com.example.maapi.repositories.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class NoteService {
#Autowired
NoteRepo noteRepo;
#Autowired
UserRepo userRepo;
#Autowired
FolderRepo folderRepo;
public List<Note> findAllNotes(){
return noteRepo.findAllNotes();
}
public Note findNoteById(int noteId){
return noteRepo.findNoteById(noteId);
}
public List<Note> findNotesByUser(int userId){
return noteRepo.findNotesByUser(userId);
}
public Note createNoteForUser(int userId, Note note){
User user = userRepo.findUserById(userId);
note.setUser(user);
return noteRepo.save(note);
}
public List<Note> findNotesByFolder(int folderId){
return noteRepo.findNotesByFolder(folderId);
}
public Note createNoteForFolder(int folderId, Note note){
Folder folder = folderRepo.findFolderById(folderId);
note.setFolder(folder);
note.setUser(folder.getUser());
return noteRepo.save(note);
}
public int updateNote(int noteId, Note updatedNote){
Note note = noteRepo.findNoteById(noteId);
updatedNote.setUser(note.getUser());
updatedNote.setFolder(note.getFolder());
noteRepo.save(updatedNote);
if(updatedNote.equals(note)){
return 1;
} else {
return 0;
}
}
public int deleteNote(int noteId){
noteRepo.deleteById(noteId);
if(noteRepo.findNoteById(noteId) == null) {
return 1;
} else {
return 0;
}
}
// SEARCH IMPLEMENTATION
public List<Note> searchForNote(String note){
return noteRepo.searchForNote(note);
}
}
LabelService.java
So this is the spring-booty way to do this that I was able to figure out. CrudRepository has findById(Integer id) which returns an Optional object.
All you have to do is optional.get() to return the encapsulated object and then you can return the desired field (in my case List notes) with a getter.
// CrudRepo interface provides the findById method which returns an Optional<Label>
// object that may or may not exist. Optional.get() returns the encapsulated object.
public List<Note> findNotesByLabelId(int labelId) {
Optional<Label> label = labelRepo.findById(labelId);
return label.get().getNotes();
}
Try this one!
SELECT * FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1
Edit:
#Entity
#Table(name = "notes")
#NamedNativeQuery(name = "Note.getNoteByLabel", resultSetMapping = "getNote",
query = "SELECT n.id,n.note,n.title,n.status FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1")
#SqlResultSetMapping(name = "getNote", classes = #ConstructorResult(targetClass = Note.class,
columns = {#ColumnResult(name = "id", type = Integer.class),#ColumnResult(name = "note", type = String.class)
#ColumnResult(name = "title", type = String.class),#ColumnResult(name = "status", type = String.class)}))
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
NoteRepo.java
#Query(nativeQuery = true)
List<Note> getNoteByLabel(int labelId);
Build a proper constructor and try this one.
You have to think on it as if it was simple POO. For example, you can use:
#Query("FROM Note n WHERE (SELECT l FROM Label l WHERE l.id = :lid) MEMBER OF labels")
public List<Note> findNotesByLabel(#Param("lid") int id);
which basically means,
get all notes where given id's label is part of the labels attribute
I don't fully know each implementation yet, surely the documentation would give a better approach, but I just came up with that problem and it did the trick

How can I create an email-verification page when the user follows the link sent to him from spring?

I have a spring controller that sends an email to user after he creates a new account which contains a link that looks something like this "To confirm your account, please click here : http://localhost:8082/confirm-account?token=THE_TOKEN" but I'm having troubling creating a webpage using angular that would shows up when the user clicks on the link. Can you help me?
Here's the controller in spring:
package com.example.demo.controller;
import com.example.demo.domain.ConfirmationToken;
import com.example.demo.domain.Response;
import com.example.demo.domain.User;
import com.example.demo.repository.ConfirmationTokenRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.EmailSenderService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;
import java.util.Calendar;
#RestController
#CrossOrigin
public class UserAccountController {
#Autowired
private UserRepository userRepository;
#Autowired
private UserService userService;
#Autowired
private ConfirmationTokenRepository confirmationTokenRepository;
#Autowired
private EmailSenderService emailSenderService;
#RequestMapping(value="/register", method= RequestMethod.POST)
#ResponseBody
public ResponseEntity<Response> registerUser( #RequestBody User user)
{
userService.saveUser(user);
ConfirmationToken confirmationToken = new ConfirmationToken(user);
confirmationTokenRepository.save(confirmationToken);
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(user.getEmail());
mailMessage.setSubject("Complete Registration!");
mailMessage.setFrom("ddailyservice#gmail.com");
mailMessage.setText("To confirm your account, please click here : "
+"http://localhost:8082/confirm-account?token="+confirmationToken.getConfirmationToken());
emailSenderService.sendEmail(mailMessage);
return new ResponseEntity<Response>(new Response("User is saved successfully"), HttpStatus.OK) ;
}
#RequestMapping(value="/confirm-account", method= { RequestMethod.GET})
#ResponseBody
public ResponseEntity<Response> confirmUserAccount(#RequestParam("token") String confirmationToken)
{
ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);
User user = token.getUser();
Calendar calendar = Calendar.getInstance();
if((token.getExpiryDate().getTime() - calendar.getTime().getTime()) <=0) {
return new ResponseEntity<Response>(new Response("token is expired"), HttpStatus.OK);
}
if(token != null)
{
user=userRepository.findByUsernameIgnoreCase(token.getUser().getUsername());
user.setEnabled(true);
userRepository.save(user);
}
else
{
return new ResponseEntity<Response>(new Response("token is broken"), HttpStatus.OK);
}
return new ResponseEntity<Response>(new Response("account verified"), HttpStatus.OK);
}
public UserRepository getUserRepository() {
return userRepository;
}
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public ConfirmationTokenRepository getConfirmationTokenRepository() {
return confirmationTokenRepository;
}
public void setConfirmationTokenRepository(ConfirmationTokenRepository confirmationTokenRepository) {
this.confirmationTokenRepository = confirmationTokenRepository;
}
public EmailSenderService getEmailSenderService() {
return emailSenderService;
}
public void setEmailSenderService(EmailSenderService emailSenderService) {
this.emailSenderService = emailSenderService;
}
}
And the confirmationToken entity:
package com.example.demo.domain;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
#Entity
public class ConfirmationToken {
private final static int EXPIRATION = 60*24;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="token_id")
private long tokenid;
#Column(name="confirmation_token")
private String confirmationToken;
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
#OneToOne(targetEntity = User.class, fetch = FetchType.EAGER, cascade = {CascadeType.REMOVE}, orphanRemoval = true)
#JoinColumn(nullable = false, name = "user_id")
private User user;
private Date expiryDate;
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
private Date calculateExpiryDate(int expiryTimeInMinutes) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Timestamp(calendar.getTime().getTime()));
calendar.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(calendar.getTime().getTime());
}
public ConfirmationToken() {
}
public ConfirmationToken(User user) {
this.user = user;
confirmationToken = UUID.randomUUID().toString();
Calendar calendar = Calendar.getInstance();
createdDate = new Date(calendar.getTime().getTime());
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
public ConfirmationToken(final String confirmationToken) {
this.confirmationToken = confirmationToken;
this.expiryDate = calculateExpiryDate(EXPIRATION);
}
public String getConfirmationToken() {
return confirmationToken;
}
public void setConfirmationToken(String confirmationToken) {
this.confirmationToken = confirmationToken;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public long getTokenid() {
return tokenid;
}
public void setTokenid(long tokenid) {
this.tokenid = tokenid;
}
}

Spring Boot: Found shared references to a collection error

I'm trying to build a small Spring Boot CRUD app with some basic e-commerce functionality (i.e. add to cart, etc.). My Basic entities are customer, cheese, roles and orders.
Customer's have a many-to-many relationship with Cheese (the fictional object I'm selling) objects. In addition, Orders have a many-to-many relationship with Cheese objects. When my customer checks out, I am intending to transfer the cart contents (i.e. the list of Cheeses) to the Order object, along with customer id, total price, etc. I want the "Orders" to be able to be logged by myself, as well as to provide an order history for the customer. The instantiating of the order object with customer.getCheeses() is what is giving me the shared collection error.
I can somewhat get around this by creating new Cheese items, however, that messes up my database, creating duplicates upon every new order.
The processing of orders is done in the completeOrder() function in UserController. All of the html/thymeleaf seems to be working - I can post it if it will help.
Cheese
package com.example.demo.models;
import javax.persistence.*;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Cheese {
#NotNull
#Size(min=2, max=20)
private String name;
#NotNull
#Size(min=2, max=20)
private String description;
#NotNull
#DecimalMax("10000.0") #DecimalMin("0.0")
private BigDecimal price;
#Id
#GeneratedValue
private int id;
#ManyToMany(mappedBy = "cheeses")
private List<Customer> customers = new ArrayList<>();
#ManyToMany(mappedBy = "cheeses")
private List<Orders> orders = new ArrayList<>();
public Cheese() {}
public Cheese(String name, String description, BigDecimal price) {
this.name = name;
this.description = description;
this.price = price;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
}
Customer
package com.example.demo.models;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Customer implements Serializable {
#NotNull
#Size(min = 2, max = 25)
private String name;
#GeneratedValue
#Id
private int accountNumber;
private BigDecimal accountFunds;
#NotNull
#Size(min = 2)
private String password;
#NotNull
#Size(min = 2, max = 25)
#Email
private String email;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="user_roles",
joinColumns={#JoinColumn(name="CUSTOMER_EMAIL", referencedColumnName = "email")},
inverseJoinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="id")})
private List<Role> roles;
//#ElementCollection
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="cheese_customers",
joinColumns={#JoinColumn(name="CUSTOMER_ID", referencedColumnName = "accountNumber")},
inverseJoinColumns={#JoinColumn(name="PRODUCT_ID", referencedColumnName="id")})
private List<Cheese> cheeses = new ArrayList<>();
public Customer(String name, String password, String email) {
this.name = name;
this.password = password;
this.email = email;
this.accountFunds = new BigDecimal(225.00);
}
public Customer() {}
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAccountNumber() {
return accountNumber;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public BigDecimal getAccountFunds() {
return accountFunds;
}
public void setAccountFunds(BigDecimal accountFunds) {
this.accountFunds = accountFunds;
}
public List<Cheese> getCheeses() {
return cheeses;
}
public void setCheeses(List<Cheese> cheeses) {
this.cheeses = cheeses;
}
}
Orders
package com.example.demo.models;
import javax.persistence.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Entity
public class Orders {
#GeneratedValue
#Id
private int orderId;
#ManyToMany(cascade= CascadeType.ALL)
#JoinTable(name="customer_orders",
joinColumns={#JoinColumn(name="ORDER_ID", referencedColumnName = "orderId")},
inverseJoinColumns={#JoinColumn(name="PRODUCT_ID", referencedColumnName="id")})
private List<Cheese> cheeses = new ArrayList<>();
private int customerId;
private BigDecimal totalPrice;
private Date date;
public Orders() {}
public Orders(List<Cheese> cheeses, int customerId, BigDecimal totalPrice) {
this.cheeses = cheeses;
this.customerId = customerId;
this.totalPrice = totalPrice;
this.date = new Date();
}
private String getFormattedDate() {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(this.date);
}
public int getOrderId() {
return orderId;
}
public List<Cheese> getCheeses() {
return cheeses;
}
public void setCheeses(List<Cheese> cheeses) {
this.cheeses = cheeses;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
UserController
package com.example.demo.controllers;
import com.example.demo.models.Customer;
import com.example.demo.models.Orders;
import com.example.demo.models.data.CheeseDao;
import com.example.demo.models.data.CustomerDao;
import com.example.demo.models.data.OrdersDAO;
import com.example.demo.models.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
#Controller
#RequestMapping("cheese")
public class UserController {
#Autowired
private CustomerDao customerDao;
#Autowired
UserService userService;
#Autowired
CheeseDao cheeseDao;
#Autowired
OrdersDAO ordersDAO;
#RequestMapping(value = "login")
public String loginPage(Model model) {
model.addAttribute("title", "Login Page");
model.addAttribute("customer", new Customer());
return "cheese/login";
}
#RequestMapping(value = "account")
public String accountInfo(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
model.addAttribute("name", customer.getName());
model.addAttribute("funds", customer.getAccountFunds());
model.addAttribute("customer", customer);
model.addAttribute("cheeses", customer.getCheeses());
model.addAttribute("total", userService.getCartTotal(customer));
return "cheese/account";
}
#PostMapping(value = "account")
public String removeItem(#RequestParam int cheeseId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
if (customer.getCheeses().contains(cheeseDao.getCheeseById(cheeseId))) {
customer.getCheeses().remove(cheeseDao.getCheeseById(cheeseId));
}
customerDao.save(customer);
return "redirect:/cheese/account";
}
#RequestMapping(value = "checkout")
public String orderCheckout(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
model.addAttribute("cheeses", customer.getCheeses());
model.addAttribute("total", userService.getCartTotal(customer));
return "cheese/checkout";
}
#GetMapping("signup")
public String displaySignUpForm(Model model) {
model.addAttribute("title", "Sign Up");
model.addAttribute("customer", new Customer());
return "cheese/signup";
}
#PostMapping(value = "signup")
public String processSignUp(Model model, #ModelAttribute Customer customer, Errors errors) {
if (errors.hasErrors()) {
return "cheese/signup";
}
userService.createUser(customer);
return "cheese/success";
}
#GetMapping("ordersuccess")
public String showForm() {
return "cheese/ordersuccess";
}
#PostMapping("checkout")
public String completeOrder() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
double accountFunds = customer.getAccountFunds().doubleValue();
double cartTotal = userService.getCartTotal(customer).doubleValue();
if (accountFunds >= cartTotal) {
accountFunds = accountFunds - cartTotal;
customer.setAccountFunds(new BigDecimal(accountFunds));
Orders order = new Orders(customer.getCheeses(), customer.getAccountNumber(), new BigDecimal(cartTotal));
customer.getCheeses().clear();
customerDao.save(customer);
ordersDAO.save(order);
return "redirect:/cheese/ordersuccess";
}
return "redirect:cheese/checkout";
}
#GetMapping("orders")
public String viewOrderHistory(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = customerDao.findByEmail(authentication.getName());
List<Orders> orders = ordersDAO.findOrdersByCustomerId(customer.getAccountNumber());
model.addAttribute("orders", orders);
return "cheese/orders";
}
}
So what you are trying to do is fetch and fill the cheese collection when you get a customer? Normally, in order to do that, you must set lazy loading to false, otherwise the session closes before you can fetch the collection.
To be able to load the customer with it's cheese collection, you must got to your Hibernate query and use a "join fetch" command. Something like this.
sessionFactory.getCurrentSession().createQuery("from Customer C join fetch C.cheeses").list();
This will force the query to fetch the cheese collection before the session closes. Also, one more thing, normally I would use a Set to avoid duplicates in the collection. I hope this helps.

show details of all orders placed by customer

I am developing an E-Commerce website(Spring MVC, java, mySql, Hibernate) for my college project. I have various models like customer,product,orders,custOrderHistory, etc.
I am able to show all customer details(in admin page) and all products for a customer to browse through.
But the problem I am facing is, how do I show the Orders and order history of a customer?
My orders table has orderId, productId, quantity and total price. but to show the product name, I have to use the productId and rerieve the Product name from product table.
I have no clue on how to do it.
Till now, i was using the jstl foreach loop to iterate the products in the productList.jsp page and displaying them in a table.
But as i told above, i need to retrieve data from 3-4 tables at once, like productName(from product table), productManuacturer(also from product table), ShippingAddress (from customer table). And I am unsure how to do this.
Edit 1: I asked this question from someone else's computer and didn't have my code with me then.
So, I am giving my code here.
Customer.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = -3280023076408333682L;
#Id
#GeneratedValue
private int customerId;
#NotEmpty(message = " The customer name must not be blank.")
private String customerName;
#NotEmpty (message = " The customer email must not be blank.")
private String customerEmail;
private String customerPhone;
#NotEmpty (message = " The username must not be blank.")
private String username;
#NotEmpty (message = " The password must not be blank.")
private String password;
private boolean enabled;
#OneToOne
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
#OneToOne()
#JoinColumn(name = "cartId")
#JsonIgnore
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
Cart.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Cart implements Serializable{
private static final long serialVersionUID = -2479653100535233857L;
#Id
#GeneratedValue
private int cartId;
#OneToMany(mappedBy = "cart", cascade= CascadeType.ALL, fetch = FetchType.EAGER)
private List cartItems = new ArrayList();
#OneToOne
#JoinColumn(name = "customerId")
#JsonIgnore
private Customer customer;
private double grandTotal;
public int getCartId() {
return cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public double getGrandTotal() {
return grandTotal;
}
public void setGrandTotal(double grandTotal) {
this.grandTotal = grandTotal;
}
public List getCartItems() {
return cartItems;
}
public void setCartItems(List cartItems) {
this.cartItems = cartItems;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
CartItem.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
#Entity
public class CartItem implements Serializable{
private static final long serialVersionUID = -904360230041854157L;
#Id
#GeneratedValue
private int cartItemId;
#ManyToOne
#JoinColumn(name="cartId")
#JsonIgnore
private Cart cart;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
private int quantity;
private double totalPrice;
#ManyToMany(cascade=CascadeType.ALL, mappedBy="cartItems")
#JsonIgnore
private List<OrderHistory> orderHistoryList;
public int getCartItemId() {
return cartItemId;
}
public void setCartItemId(int cartItemId) {
this.cartItemId = cartItemId;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public List<OrderHistory> getOrderHistoryList() {
return orderHistoryList;
}
public void setOrderHistoryList(List<OrderHistory> orderHistoryList) {
this.orderHistoryList = orderHistoryList;
}
}
CustomerOrder.java
package com.site.model;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = -3608286390950243118L;
#Id
#GeneratedValue
private int customerOrderId;
#OneToOne
#JoinColumn(name = "cartId")
private Cart cart;
#OneToOne
#JoinColumn(name = "customerId")
private Customer customer;
#OneToOne
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
public int getCustomerOrderId() {
return customerOrderId;
}
public void setCustomerOrderId(int customerOrderId) {
this.customerOrderId = customerOrderId;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
}
OrderHistory.java
package com.site.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Entity
public class OrderHistory implements Serializable {
private static final long serialVersionUID = 1083533250613139445L;
#Id
#GeneratedValue
private int orderHistoryId;
private int customerId;
private String customerName;
private int customerOrderId;
private int cartId;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "cartItem_orderHistory", joinColumns = #JoinColumn(name = "orderHistoryId"),
inverseJoinColumns = #JoinColumn
(name = "cartItemId"))
private List<CartItem> cartItems = new ArrayList<CartItem>();
private double grandTotal;
private String billingAddress;
private String shippingAddress;
public int getOrderHistoryId() {
return orderHistoryId;
}
public void setOrderHistoryId(int orderHistoryId) {
this.orderHistoryId = orderHistoryId;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public int getCustomerOrderId() {
return customerOrderId;
}
public void setCustomerOrderId(int customerOrderId) {
this.customerOrderId = customerOrderId;
}
public int getCartId() {
return cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
public double getGrandTotal() {
return grandTotal;
}
public void setGrandTotal(double grandTotal) {
this.grandTotal = grandTotal;
}
public String getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(String billingAddress) {
this.billingAddress = billingAddress;
}
public String getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(String shippingAddress) {
this.shippingAddress = shippingAddress;
}
}
edit 2: how do I store the data in the ustomerorder table and orderhistory table, and also, how do i show it on a jsp page?
you should have a CustomerId column in order table for detecting the order is associated with which customer. Simply insert logged in userid in that and fetch the customer name by making join with customer table.
You should have customerid in your order table. So that you can fetch the customer's order history by providing customerid.

IllegalArgumentException: MetaClass not found

I use a framework called "Cuba.Studio" to create a CRUD application.
When I use this JPQL Query, I get this exception:
Error com.haulmont.cuba.core.global.RemoteException: MetaClass not
found for firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK
this is my code:
try (Transaction tx = persistence.createTransaction()) {
EntityManager em = persistence.getEntityManager();
Query query = em.createQuery("select firstusecase$Project.name from
firstusecase$UseCase useCase,
firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK commonTable,
firstusecase$Project project where useCase.id = commonTable.use_case_id
and project.id = commonTable.project_id and useCase.id = :useCaseId")
.setParameter("useCaseId", useCase.getId());
and here is a part of the code of my Entity Class:
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
Does anybody have an idea?
I would be very thankful about your support :)
Thanks
EDIT:
Here is the code of the UseCase Class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Collection;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import com.haulmont.cuba.core.entity.StandardEntity;
import javax.persistence.Column;
import com.haulmont.chile.core.annotations.NamePattern;
import javax.persistence.Lob;
import com.haulmont.chile.core.annotations.MetaProperty;
import javax.persistence.Transient;
#NamePattern("%s|jamaref")
#Table(name = "FIRSTUSECASE_USE_CASE")
#Entity(name = "firstusecase$UseCase")
public class UseCase extends StandardEntity {
private static final long serialVersionUID = 4928397068727365740L;
#Column(name = "JAMAREF", length = 30)
protected String jamaref;
#Column(name = "PROJECT_LIST")
protected String projectList;
#Transient
#MetaProperty
protected String usecaseDescription;
#Column(name = "CHANGE_TRACKING_COMMENT")
protected String changeTrackingComment;
#Lob
#Column(name = "CHANGE_TRACKING")
protected String changeTracking;
#Column(name = "POWERAMSREF", length = 30)
protected String poweramsref;
#Column(name = "LEGACYPWRUC", length = 30)
protected String legacypwruc;
#Column(name = "TRACKING_CHANGE_COMMENT")
protected String trackingChangeComment;
#Column(name = "INSERT_TIMESTAMP")
protected String insertTimestamp;
#Column(name = "USECASE_TYPE")
protected String usecaseType;
#Column(name = "CHANGE_TIMESTAMP")
protected String changeTimestamp;
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "USECASE_STATUS_ID")
protected UseCaseStatus usecaseStatus;
public void setProjectList(String projectList) {
this.projectList = projectList;
}
public String getProjectList() {
return projectList;
}
public String getUsecaseDescription() {
return usecaseDescription;
}
public void setChangeTrackingComment(String changeTrackingComment) {
this.changeTrackingComment = changeTrackingComment;
}
public String getChangeTrackingComment() {
return changeTrackingComment;
}
public void setChangeTracking(String changeTracking) {
this.changeTracking = changeTracking;
}
public void setInsertTimestamp(String insertTimestamp) {
this.insertTimestamp = insertTimestamp;
}
public void setChangeTimestamp(String changeTimestamp) {
this.changeTimestamp = changeTimestamp;
}
public String getInsertTimestamp() {
return insertTimestamp;
}
public void setUsecaseType(String usecaseType) {
this.usecaseType = usecaseType;
}
public String getUsecaseType() {
return usecaseType;
}
public String getChangeTimestamp() {
return changeTimestamp;
}
public String getChangeTracking() {
return changeTracking;
}
public void setTrackingChangeComment(String trackingChangeComment) {
this.trackingChangeComment = trackingChangeComment;
}
public String getTrackingChangeComment() {
return trackingChangeComment;
}
public void setUsecaseStatus(UseCaseStatus usecaseStatus) {
this.usecaseStatus = usecaseStatus;
}
public UseCaseStatus getUsecaseStatus() {
return usecaseStatus;
}
public void setJamaref(String jamaref) {
this.jamaref = jamaref;
}
public String getJamaref() {
return jamaref;
}
public void setPoweramsref(String poweramsref) {
this.poweramsref = poweramsref;
}
public String getPoweramsref() {
return poweramsref;
}
public void setLegacypwruc(String legacypwruc) {
this.legacypwruc = legacypwruc;
}
public String getLegacypwruc() {
return legacypwruc;
}
public void setProject(Collection<Project> project) {
this.project = project;
}
public Collection<Project> getProject() {
return project;
}
}
And the code of the Project.class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.chile.core.annotations.NamePattern;
#NamePattern("%s|name")
#Table(name = "FIRSTUSECASE_PROJECT")
#Entity(name = "firstusecase$Project")
public class Project extends StandardEntity {
private static final long serialVersionUID = -3997556855391197754L;
#Column(name = "NAME", nullable = false)
protected String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Thanks