This question already has an answer here:
why "productname" not supported when i add productimage code and " NULL not allowed for column "PRODUCTNAME"; SQL statement:" [closed]
(1 answer)
Closed 5 years ago.
[HTTP Status 500 - Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: NULL not allowed for column "PRODUCTNAME"; SQL statement][1]
[1]: https://i.stack.imgur.com/H6NkO.png
i can not add datbase in admin page so what is my probelem in this code?
please help me i can not uderstand. so how can i solve this?
i can not add datbase in admin page so what is my probelem in this code?
please help me i can not uderstand. so how can i solve this?
home controller
---------------
package com.emusicstore.controller;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
#Controller
public class HomeController {
private Path path;
#Autowired
private ProductDao productDao;
#RequestMapping("/")
public String home()
{
return "home";
}
#RequestMapping("/productList")
public String getProducts(Model model){
List<Product> products = productDao.getAllProducts();
model.addAttribute("products",products);
return "productList";
}
#RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(#PathVariable String productId, Model model) throws IOException
{
Product product = productDao.getProductById(productId);
model.addAttribute(product);
return "viewProduct";
}
#RequestMapping("/admin")
public String adminPage()
{
return "admin";
}
#RequestMapping("/admin/productInventory")
public String productInventory(Model model)
{
List<Product> products = productDao.getAllProducts();
model.addAttribute("products",products);
return "productInventory";
}
#RequestMapping("/admin/productInventory/addProduct")
public String addProduct(Model model){
Product product = new Product();
product.setProductCategory("instrument");
product.setProductCondition("new");
product.setProductStatus("active");
model.addAttribute("product",product);
return "addProduct";
}
#RequestMapping(value = "/admin/productInventory/addProduct" , method = RequestMethod.POST)
public String addProductPost(#ModelAttribute("product") Product product, HttpServletRequest request){
productDao.addProduct(product);
MultipartFile productImage = product.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
path = Paths.get(rootDirectory + "\\WEB-INF\\resources\\images\\"+product.getProductId()+".png");
if(productImage != null && !productImage.isEmpty())
{
try{
productImage.transferTo(new File(path.toString()));
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("Product image saving failed",e);
}
}
return "redirect:/admin/productInventory";
}
#RequestMapping("/admin/productInventory/deleteProduct/{id}")
public String deleteProduct(#PathVariable String id, Model model){
productDao.deleteProduct(id);
return "redirect:/admin/productInventory";
}
}
product
-------
package com.emusicstore.model;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.*;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacturer;
#Transient
private MultipartFile productImage;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public MultipartFile getProductImage() {
return productImage;
}
public void setProductImage(MultipartFile productImage) {
this.productImage = productImage;
}
}
i can not add datbase in admin page so what is my probelem in this code?
please help me i can not uderstand. so how can i solve this?
i can not add datbase in admin page so what is my probelem in this code?
please help me i can not uderstand. so how can i solve this?
I think so you have applied NOT NULL constraint on Product name
Related
I'm trying to retrieve a list of just the orders created from one day ago till today, and I can't manage to find any help about it, tried everything I found already.
Basically I need a getAllOrders(), but with filtered by that time period, one day....
How do I filter it ? I Found tons of tutorials on how to sort them descending or ascending, nothing else.
My order.java:
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
#ToString
#Entity
#Table(name = "myorder")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "userId")
private User user;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
#JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
#CreationTimestamp
#Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My orderservice.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
/* #Query(value = "from order t where Date BETWEEN :yesterday AND :now")
public List<Order> getAllBetweenDates(#Param("yesterday")Date yesterday,#Param("now")Date localdate.now){
private LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
return orderRepository.findAll();
} */
public List<Order> getAllOrderDetail() {
return orderRepository.findAll();
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount + singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderDTO.java
package com.proj.my.dto;
import com.proj.my.model.ShoppingCart;
import java.util.List;
public class OrderDTO {
private List<ShoppingCart> cartItems;
private String userEmail;
private String userName;
public OrderDTO() {
}
public OrderDTO(List<ShoppingCart> cartItems, String userEmail, String userName) {
this.cartItems = cartItems;
this.userEmail = userEmail;
this.userName = userName;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
public String getuserEmail() {
return userEmail;
}
public void setuserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "OrderDTO{" +
", cartItems=" + cartItems +
", userEmail='" + userEmail + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
My shoppingcart.java
package com.proj.my.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/*#Data
#AllArgsConstructor
#RequiredArgsConstructor
#NoArgsConstructor
*/
#Entity
public class ShoppingCart {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer productId;
private String productName;
private int quantity;
private float amount;
public ShoppingCart() {
}
public ShoppingCart(Integer productId, String productName, int quantity, float amount) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.amount = amount;
}
public ShoppingCart(Integer productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public ShoppingCart(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingCart{" +
"id=" + id +
", productId=" + productId +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", amount=" + amount +
'}';
}
}
And finally my orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.Order;
import com.proj.my.model.User;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
#RestController
#RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
#GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(#PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
#GetMapping(value = "/getOrder")
public List<Order> getAllOrderDetails() {
return orderService.getAllOrderDetail();
}
#PostMapping("/placeOrder")
public ResponseEntity<ResponseOrderDTO> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
float amount = orderService.getCartAmount(orderDTO.getCartItems());
User user = new User(orderDTO.getuserName(), orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}}
You can add method in OrderRepository interface
public List<Order> findByCreatedAtBetween(LocalDate d1, LocalDate d2)
and call it
orderRepository.findByCreatedAtBetween(today.minusDays(1),today);
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details
I'm doing a vote counting system, the winner is the one who has more than 3 votes, however, I'm facing the following problem. When there is more than one place with 3 votes, instead of my JSON returning the one with the most votes, it always returns the one with more than 3 votes ordered by ID.
That is, if the restaurant with ID 1 has 3 votes, and the restaurant with ID 2 has 10 votes, the restaurant with ID 1 ends up appearing on the route /restaurants/winner despite not being the most voted, is there any way I can make the most voted show up?
e.g: return from /restaurants/winner route
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
While McDonalds has 5 votes
{
"id": 2,
"restaurant": "McDonalds",
"address": "Av. Ipiranga, 5200",
"website": "https://www.mcdonalds.com.br/",
"description": "Rede de fast-food tradicional conhecida por ter ótimos hambúrgueres e batatas fritas.",
"count": 5
}
Here are the classes that I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#JsonIgnore
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.exceptions.NotFoundException;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant : restaurants) {
// Hibernate.initialize(restaurant.getCount());
if (restaurant.getCount() >= 3) {
return restaurant;
}
}
throw new NotFoundException(
"Nenhum restaurante ganhou a votação, é necessário um total de 3 votos para ter um restaurante vencedor.");
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.dbserver.restaurantes.entities.Restaurant;
public interface RestaurantRepository extends JpaRepository<Restaurant, Long> {
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#GetMapping(value = "/winner")
public Restaurant findWinner(Integer count) {
return service.findWinner(count);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}
You have to check the top value as well. So You need to add your own query for that. Here is the code
public interface RestaurantRepository extends JpaRepository<Restaurant, Long>
{
Optional<Restaurant> findFirstByCountGreaterThanEqualOrderByCountDesc (Integer count);
}
and Use that inside your method
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) throws NotFoundException
{
Optional<Restaurant> data = repository.findFirstByCountGreaterThanEqualOrderByCountDesc(3);
if (data.isPresent())
{
return data.get();
}
throw new NotFoundException("Nenhum restaurante ganhou a votação, é necessário um total de 3 votos para ter um restaurante vencedor.");
}
You can use native queries as well.
I'm getting an error where the entity class's variable is not found while the variable is clearly there and the entity class is found
#RestController
public class LanguageController {
#Autowired
private LanguageService service;
#RequestMapping("/language")
public List<Language> allLanguages() {
return service.getAllLanguages();
}
#RequestMapping("/language/{id}")
public Optional<Language> allLanguagesById(#PathVariable String id) {
return service.getLanguagesById(id);
}
#RequestMapping(value = "/language", method = RequestMethod.POST)
public void addTopic(#RequestBody Language topic) {
service.addLanguage(topic);
}
// addLanguage used to save/add depending if obj already exists
// Will need more variable in obj for it to truly update
#RequestMapping(value = "/language/{id}", method = RequestMethod.PUT)
public void updateTopic(#RequestBody Language lang) {
service.addLanguage(lang);
}
#RequestMapping(value = "/language/{id}", method = RequestMethod.DELETE)
public void deleteTopics(#PathVariable String id) {
service.deleteLanguage(id);
}
}
entity class
package com.Alex.language;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import com.Alex.language.Language;
// JPA to create columns according it
// Act as table labels
#Entity
public class Topics {
// Mark primary key
#Id
private String id;
private String name;
private String description;
// Many topics to one language
#ManyToOne
private Language lang;
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Topics() {
}
public Topics(String id, String name, String description, String langId) {
super();
this.id = id;
this.name = name;
this.description = description;
this.lang = new Language(langId);
}
public Language getLang() {
return lang;
}
public void setLang(Language lang) {
this.lang = lang;
}
}
package com.Alex.language;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Language {
#Id
private String langId;
public String getLangId() {
return langId;
}
public void setLangId(String langId) {
this.langId = langId;
}
public Language(String langId) {
super();
this.langId = langId;
}
public Language() {
}
}
Controller class
package com.Alex.language;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.Alex.language.Language;
// Used to create RESTful web services
#RestController
public class TopicsController {
// As the database is embedded, will have to add data before able to see in Postman
#Autowired
private TopicService service;
#RequestMapping("/language/{id}/topics")
public List<Topics> getAllTopics(#PathVariable String id) {
return service.getAllTopicsByLanguageId(id);
}
// #PathVariable get variable from #RequestMapping {id}
#RequestMapping("/language/{langId}/topics/{id}")
public Optional<Topics> getSpecifiedTopic(#PathVariable String id) {
return service.getTopic(id);
}
// #RequestBody to convert JSON object to Java object to be used
#RequestMapping(value = "/language/{langId}/topics", method = RequestMethod.POST)
public void addTopic(#RequestBody Topics topic, #PathVariable String langId) {
topic.setLang(new Language(langId));
service.addTopic(topic);
}
#RequestMapping(value = "/language/{langId}/topics/{id}", method = RequestMethod.PUT)
public void updateTopic(#PathVariable String langId, #RequestBody Topics topic) {
topic.setLang(new Language(langId));
service.updateTopic(topic);
}
#RequestMapping(value = "/language/{langId}/topics/{id}", method = RequestMethod.DELETE)
public void deleteTopics(#PathVariable String id) {
service.deleteTopic(id);
}
}
So, I get the following error message when I type in the url something like this in Postman. localhost:8080/language/java/topics ( POST )
message=Unable to find com.Alex.language.Language with id langId; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.Alex.language.Language with id langId, path=/language/java/topics}]
EDIT: Remove " " between langId which makes a literal String. Silly me, this is one of the mistakes I make most commonly :/
Solving that, I'm getting " Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'langId' in value "/language/${langId}/topics/{id}". I believe there is some configuration problem in main or so.
I have an Object defined that has ChildAccountList of Strings as one of the attributes.
Is there a findBy method that I can use such that it will return the list of all rows where one of the elements in the array equals the passed in parameter.
I mean something like:
List <String> childrenAccountsList = Arrays.asList("A","B","C");
List<DBObjectType> retList = findBy_{whatGoesHere} (String childValue);
List<DBObjectType> retList = findBy_{whatGoesHere} ("A");
UPDATE ( with example )
Here are my class definitions
UserREF.java
package test;
import com.microsoft.azure.spring.data.documentdb.core.mapping.Document;
import com.microsoft.azure.spring.data.documentdb.core.mapping.PartitionKey;
import org.springframework.data.annotation.Id;
import java.util.List;
#Document(collection = "user-management")
public class UserREF{
#Id
private String id;
private String userId;
private String role;
private String primaryAccountId;
#PartitionKey
private String partition;
private String shipTo;
// #ElementCollection
private List<ShipToAccounts> childShipToAccounts;
public String getUserId(){
return userId;
}
public void setUserId(String userId){
this.userId = userId;
}
public String getRole(){
return role;
}
public void setRole(String role){
this.role = role;
}
public String getPrimaryAccountId(){
return primaryAccountId;
}
public void setPrimaryAccountId(String primaryAccountId) {
this.partition = primaryAccountId;
this.primaryAccountId = primaryAccountId;
}
public String getPartition() {
this.partition = this.primaryAccountId;
return this.partition;
}
public void setPartition(String partition) {
this.partition = this.primaryAccountId;
}
public String getShipTo(){
return shipTo;
}
public void setShipTo(String shipTo){
this.shipTo = shipTo;
}
public List<ShipToAccounts> getChildShipToAccounts(){
return childShipToAccounts;
}
public void setChildShipToAccounts(List<ShipToAccounts> shipToAccounts){
for (ShipToAccounts shipToAccount : shipToAccounts) {
shipToAccount.setPrimaryAccountId(this.primaryAccountId);
}
this.childShipToAccounts = shipToAccounts;
}
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
}
ShipToAccounts.java
package test;
public class ShipToAccounts{
private String primaryAccountId;
private String accountId;
public String getPrimaryAccountId() {
return primaryAccountId;
}
public void setPrimaryAccountId(String primaryAccountId) {
this.primaryAccountId = primaryAccountId;
}
public String getAccountId(){
return accountId;
}
public void setAccountId(String input){
this.accountId = input;
}
}
UserREFRepository.java
package test;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.microsoft.azure.spring.data.documentdb.core.DocumentDbOperations;
import com.microsoft.azure.spring.data.documentdb.repository.DocumentDbRepository;
import java.util.List;
#Repository
#ConditionalOnBean(DocumentDbOperations.class)
public interface UserREFRepository extends DocumentDbRepository<UserREF, String> {
#Override
#Cacheable("test_users")
UserREF findOne(String id, String partitionKeyValue);
List<UserREF> findByRole(String role);
List<UserREF> findByChildShipToAccounts_PrimaryAccountId (#Param("primaryAccountId") String primaryAccountId);
List<UserREF> findAllByChildShipToAccounts_PrimaryAccountId(String s);
}
UserRefService.java
package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
#Service
public class UserRefService {
private static final Logger log = LoggerFactory.getLogger(UserRefService.class);
#Autowired
private UserREFRepository userREFRepository;
public UserREF save(UserREF inUser) {
List<UserREF> adminUsersList = userREFRepository.findAllByChildShipToAccounts_PrimaryAccountId("123456");
System.out.println("users " + adminUsersList);
UserREF newUser = userREFRepository.save(inUser);
return newUser;
}
}
And this is how my JSON document looks like
{
"role": "admin",
"partition": "123456",
"primaryAccountId": "123456",
"childShipToAccounts": [
{
"accountId": "1111",
"primaryAccountId": "123456"
},
{
"accountId": "2222",
"primaryAccountId": "123456"
},
{
"accountId": "3333",
"primaryAccountId": "123456"
}
],
"id": "1b6d8497-1aca-4cab-9e3d-f8be3ba4f71c",
"userId": "22",
"shipTo": "2222"
}
I am getting below error on List<UserREF> adminUsersList = userREFRepository.findAllByChildShipToAccounts_PrimaryAccountId("123456");
java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException:
Message: {"Errors":["Invalid query. Specified parameter name '#childShipToAccounts.primaryAccountId' is invalid.
Parameter names should be in the format of symbol '#' followed by a valid identifier. E.g. #param1"]}
ActivityId: fd188aac-f99c-4983-b442-713c529dc930, Microsoft.Azure.Documents.Common/2.1.0.0, StatusCode: BadRequest
How should I define my "findBy" method ?
Thanks
Try findByChildrenAccountsListContaining(yourString)
Spring MVC + Hibernate web application with mysql database.
3 tables (products, members and cart to connect this two). Members table have two different users: admin and customer.
It should be something like Online Store.
To have Administrator and Customer users. Admin entering new, edit and delete products. Customer to list all products and add to cart part.
But before that it should have log in and sign up part. So Admin or Customer can log in or sign up.
So I have welcome page, index.jsp, from which I need links to:
all_products.jsp -> list all products from products table mysql database
signup.jsp -> Add new member form and sending data to members table mysql database.
login.jsp -> Log In form
From login.jsp depending who logged in:
Customer -> index.jsp
Admin -> admin.jsp
admin.jsp -> add.jsp, all_products.jsp with edit and delete option.
add.jsp-> add new product form
I setup up a new project in Netbeans, with Spring mvc and hibernate framework, connect with mysql database, set up server, glassfish... etc...
Then add...
Members.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="members")
public class Members implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int memberId;
private String userName;
private String password;
private String fullName;
private String email;
private String address;
private String gender;
private String dateOfBirth;
private String memberType;
private Set<Cart> carts = new HashSet<Cart>(0);
public Members() {
}
public Members(int memberId) {
this.memberId = memberId;
}
public Members(int memberId, String userName, String password, String fullName, String email, String address, String gender, String dateOfBirth, String memberType, Set<Cart> carts) {
this.memberId = memberId;
this.userName = userName;
this.password = password;
this.fullName = fullName;
this.email = email;
this.address = address;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.memberType = memberType;
this.carts = carts;
}
public int getMemberId() {
return this.memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMemberType() {
return this.memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Products.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="products")
public class Products implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
private String productName;
private String productType;
private String description;
private Double price;
private String productColor;
private String productBrand;
private String productSize;
private Integer allProductsQuantity;
private Set<Cart> carts = new HashSet<Cart>(0);
public Products() {
}
public Products(int productId) {
this.productId = productId;
}
public Products(int productId, String productName, String productType, String description, Double price, String productColor, String productBrand, String productSize, Integer allProductsQuantity, Set<Cart> carts) {
this.productId = productId;
this.productName = productName;
this.productType = productType;
this.description = description;
this.price = price;
this.productColor = productColor;
this.productBrand = productBrand;
this.productSize = productSize;
this.allProductsQuantity = allProductsQuantity;
this.carts = carts;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return this.price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getProductColor() {
return this.productColor;
}
public void setProductColor(String productColor) {
this.productColor = productColor;
}
public String getProductBrand() {
return this.productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSize() {
return this.productSize;
}
public void setProductSize(String productSize) {
this.productSize = productSize;
}
public Integer getAllProductsQuantity() {
return this.allProductsQuantity;
}
public void setAllProductsQuantity(Integer allProductsQuantity) {
this.allProductsQuantity = allProductsQuantity;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Cart.java
package model;
public class Cart implements java.io.Serializable {
private int cartId;
private Members members;
private Products products;
private Integer cartQuantity;
public Cart() {
}
public Cart(int cartId) {
this.cartId = cartId;
}
public Cart(int cartId, Members members, Products products, Integer cartQuantity) {
this.cartId = cartId;
this.members = members;
this.products = products;
this.cartQuantity = cartQuantity;
}
public int getCartId() {
return this.cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public Members getMembers() {
return this.members;
}
public void setMembers(Members members) {
this.members = members;
}
public Products getProducts() {
return this.products;
}
public void setProducts(Products products) {
this.products = products;
}
public Integer getCartQuantity() {
return this.cartQuantity;
}
public void setCartQuantity(Integer cartQuantity) {
this.cartQuantity = cartQuantity;
}
}
I add service also for this classes.
MemberService
package service;
import java.util.List;
import model.Members;
public interface MembersService {
public void add(Members members);
public void edit(Members members);
public void delete(int memberId);
public Members getMembers(int memverId);
public List getAllMembers();
}
ProductsService
package service;
import java.util.List;
import model.Products;
public interface ProductsService {
public void add(Products products);
public void edit(Products products);
public void delete(int productId);
public Products getProducts(int productId);
public List getAllProducts();
}
Also add ServiceImpl
MembersServiceImpl
package service;
import DAO.MembersDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Members;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class MembersServiceImpl implements MembersService{
#Autowired
private MembersDAO membersDAO;
#Transactional
public void add(Members members) {
membersDAO.add(members);
}
#Transactional
public void edit(Members members) {
membersDAO.edit(members);
}
#Transactional
public void delete(int productId) {
membersDAO.delete(productId);
}
#Transactional
public Members getMembers(int productId) {
return membersDAO.getMembers(productId);
}
#Transactional
public List getAllMembers() {
return membersDAO.getAllMembers();
}
}
ProductsServiceImpl
package service;
import DAO.ProductsDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Products;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class ProductsServiceImpl implements ProductsService{
#Autowired
private ProductsDAO productsDAO;
#Transactional
public void add(Products products) {
productsDAO.add(products);
}
#Transactional
public void edit(Products products) {
productsDAO.edit(products);
}
#Transactional
public void delete(int productId) {
productsDAO.delete(productId);
}
#Transactional
public Products getProducts(int productId) {
return productsDAO.getProducts(productId);
}
#Transactional
public List getAllProducts() {
return productsDAO.getAllProducts();
}
}
And ProductsContoller
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import service.ProductsService;
public class ProductsController extends SimpleFormController {
public ProductsController() {
setCommandClass(Products.class);
setCommandName("products");
setSuccessView("products");
setFormView("products");
}
protected ModelAndView products(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
Products products = (Products) command;
ModelAndView mv = new ModelAndView(getSuccessView());
/*ModelAndView addObject = mv.addObject("products", ProductsService.ProductsService(products.getValue()));*/
return mv;
}
#Autowired
private ProductsService productsService;
public void setProductsService(ProductsService productsService) {
this.productsService = productsService;
}
}
Here I am stack.
I also have simple MembersDAO.java, ProductsDAO.java and there implementations.
...and fist question is how to connect two .jsp pages?
How to make simple navigation bar to connect first all my .jsp(view) pages?
To make simple nav bar on header and use on all my pages.
I know i should use spring contorollers...
How to make simple controller that will take me to all_products.jsp from index.jsp and list all products from products table from mysql database???
How to import spring security, log in section in my app?
Also add new product form...
My app is working and deplopying...
I can upload web.xml and servlet.xml but did change things...
Can anyone help me?!
Thank you very much.
in your .jsp. create your navigation. If products on href doesn't work. Then add
${pageContext.request.contextPath}/products
this will be your navigation
<ul>
<li>
Home
</li>
<li>
Products
</li>
<li>
Users
</li>
</ul>
navigation should look like this or depends on what you want
Home
Products
Users
and the simple controller for the views or for your .jsp files.
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home() {
return new ModelAndView("home"); //home.jsp
}
#RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView products() {
return new ModelAndView("products");
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ModelAndView users() {
return new ModelAndView("users");
}