Ошибка: колонки post_content не найдено в этом ResultSet’е
Не находит колонку пост контент. В постгре эта колонка стоит, но все значения null.
Вот мой код:
Product Controller
@Controller
@RequiredArgsConstructor
public class ProductController {
private final ProductService productService;
private final CategoryService categoryService;
@GetMapping("/products")
public String products(Model model, Principal principal) {
if (principal == null) {
return "redirect:/login";
}
List<ProductDto> products = productService.allProduct();
model.addAttribute("products", products);
model.addAttribute("size", products.size());
return "products";
}
@GetMapping("/products/{pageNo}")
public String allProducts(@PathVariable("pageNo") int pageNo, Model model, Principal principal) {
if (principal == null) {
return "redirect:/login";
}
Page<ProductDto> products = productService.getAllProducts(pageNo);
model.addAttribute("title", "Manage Products");
model.addAttribute("size", products.getSize());
model.addAttribute("products", products);
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", products.getTotalPages());
return "products";
}
@GetMapping("/search-products/{pageNo}")
public String searchProduct(@PathVariable("pageNo") int pageNo,
@RequestParam(value = "keyword") String keyword,
Model model, Principal principal
) {
if (principal == null) {
return "redirect:/login";
}
Page<ProductDto> products = productService.searchProducts(pageNo, keyword);
model.addAttribute("title", "Result Search Products");
model.addAttribute("size", products.getSize());
model.addAttribute("products", products);
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", products.getTotalPages());
return "product-result";
}
@GetMapping("/add-product")
public String addProductPage(Model model, Principal principal) {
if (principal == null) {
return "redirect:/login";
}
model.addAttribute("title", "Add Product");
List<Category> categories = categoryService.findAllByActivatedTrue();
model.addAttribute("categories", categories);
model.addAttribute("productDto", new ProductDto());
return "add-product";
}
@PostMapping("/save-product")
public String saveProduct(@ModelAttribute("productDto") ProductDto product,
@RequestParam("imageProduct") MultipartFile imageProduct,
RedirectAttributes redirectAttributes, Principal principal) {
try {
if (principal == null) {
return "redirect:/login";
}
productService.save(imageProduct, product);
redirectAttributes.addFlashAttribute("success", "Add new product successfully!");
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("error", "Failed to add new product!");
}
return "redirect:/products/0";
}
@GetMapping("/update-product/{id}")
public String updateProductForm(@PathVariable("id") Long id, Model model, Principal principal) {
if (principal == null) {
return "redirect:/login";
}
List<Category> categories = categoryService.findAllByActivatedTrue();
ProductDto productDto = productService.getById(id);
model.addAttribute("title", "Add Product");
model.addAttribute("categories", categories);
model.addAttribute("productDto", productDto);
return "update-product";
}
@PostMapping("/update-product/{id}")
public String updateProduct(@ModelAttribute("productDto") ProductDto productDto,
@RequestParam("imageProduct") MultipartFile imageProduct,
RedirectAttributes redirectAttributes, Principal principal) {
try {
if (principal == null) {
return "redirect:/login";
}
productService.update(imageProduct, productDto);
redirectAttributes.addFlashAttribute("success", "Update successfully!");
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("error", "Error server, please try again!");
}
return "redirect:/products/0";
}
@RequestMapping(value = "/enable-product", method = {RequestMethod.PUT, RequestMethod.GET})
public String enabledProduct(Long id, RedirectAttributes redirectAttributes, Principal principal) {
try {
if (principal == null) {
return "redirect:/login";
}
productService.enableById(id);
redirectAttributes.addFlashAttribute("success", "Enabled successfully!");
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("error", "Enabled failed!");
}
return "redirect:/products/0";
}
@RequestMapping(value = "/delete-product", method = {RequestMethod.PUT, RequestMethod.GET})
public String deletedProduct(Long id, RedirectAttributes redirectAttributes, Principal principal) {
try {
if (principal == null) {
return "redirect:/login";
}
productService.deleteById(id);
redirectAttributes.addFlashAttribute("success", "Deleted successfully!");
} catch (Exception e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("error", "Deleted failed!");
}
return "redirect:/products/0";
}
}
Класс Product
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "products", uniqueConstraints = @UniqueConstraint(columnNames = {"name", "image"}))
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "product_id")
private Long id;
private String name;
private String description;
private int currentQuantity;
private double costPrice;
private double salePrice;
@Lob
private String image;
@Length(min = 1, message = "Content of the Post should be start at least one character")
@Column(columnDefinition = "TEXT", name = "postContent")
private String post_content;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "category_id", referencedColumnName = "category_id")
private Category category;
private boolean is_activated;
private boolean is_deleted;
}
ProductDto:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductDto {
private Long id;
private String name;
private String description;
@NotBlank
@Lob
private String post_content;
private int currentQuantity;
private double costPrice;
private double salePrice;
private String image;
private Category category;
private boolean activated;
private boolean deleted;
private String currentPage;
}
ProductService:
public interface ProductService {
@Transactional(readOnly = true)
List<Product> findAll();
@Transactional(readOnly = true)
List<ProductDto> products();
@Transactional(readOnly = true)
List<ProductDto> allProduct();
@Transactional
Product save(MultipartFile imageProduct, ProductDto product);
@Transactional
Product update(MultipartFile imageProduct, ProductDto productDto);
@Transactional
void enableById(Long id);
@Transactional
void deleteById(Long id);
@Transactional(readOnly = true)
ProductDto getById(Long id);
@Transactional(readOnly = true)
Product findById(Long id);
@Transactional(readOnly = true)
List<ProductDto> randomProduct();
@Transactional(readOnly = true)
Page<ProductDto> searchProducts(int pageNo, String keyword);
@Transactional(readOnly = true)
Page<ProductDto> getAllProducts(int pageNo);
@Transactional(readOnly = true)
Page<ProductDto> getAllProductsForCustomer(int pageNo);
@Transactional(readOnly = true)
List<ProductDto> findAllByCategory(String category);
@Transactional(readOnly = true)
List<ProductDto> filterHighProducts();
@Transactional(readOnly = true)
List<ProductDto> filterLowerProducts();
@Transactional(readOnly = true)
List<ProductDto> listViewProducts();
@Transactional(readOnly = true)
List<ProductDto> findByCategoryId(Long id);
@Transactional(readOnly = true)
List<ProductDto> searchProducts(String keyword);
}
ProductServiceImpl:
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
private final ImageUpload imageUpload;
@Override
public List<Product> findAll() {
return productRepository.findAll();
}
@Override
public List<ProductDto> products() {
return transferData(productRepository.getAllProduct());
}
@Override
public List<ProductDto> allProduct() {
List<Product> products = productRepository.findAll();
List<ProductDto> productDtos = transferData(products);
return productDtos;
}
@Override
public Product save(MultipartFile imageProduct, ProductDto productDto) {
Product product = new Product();
try {
if (imageProduct != null) {
imageUpload.uploadFile(imageProduct);
product.setImage(Base64.getEncoder().encodeToString(imageProduct.getBytes()));
}
product.setName(productDto.getName());
product.setDescription(productDto.getDescription());
product.setPost_content(productDto.getPost_content());
product.setCurrentQuantity(productDto.getCurrentQuantity());
product.setCostPrice(productDto.getCostPrice());
product.setCategory(productDto.getCategory());
product.set_deleted(false);
product.set_activated(true);
return productRepository.save(product);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public Product update(MultipartFile imageProduct, ProductDto productDto) {
try {
Product productUpdate = productRepository.getReferenceById(productDto.getId());
if (imageProduct.getBytes().length > 0) {
if (imageUpload.checkExist(imageProduct)) {
productUpdate.setImage(productUpdate.getImage());
} else {
imageUpload.uploadFile(imageProduct);
productUpdate.setImage(Base64.getEncoder().encodeToString(imageProduct.getBytes()));
}
}
productUpdate.setCategory(productDto.getCategory());
productUpdate.setId(productUpdate.getId());
productUpdate.setName(productDto.getName());
productUpdate.setDescription(productDto.getDescription());
productUpdate.setCostPrice(productDto.getCostPrice());
productUpdate.setSalePrice(productDto.getSalePrice());
productUpdate.setCurrentQuantity(productDto.getCurrentQuantity());
return productRepository.save(productUpdate);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public void enableById(Long id) {
Product product = productRepository.getById(id);
product.set_activated(true);
product.set_deleted(false);
productRepository.save(product);
}
@Override
public void deleteById(Long id) {
Product product = productRepository.getById(id);
product.set_deleted(true);
product.set_activated(false);
productRepository.save(product);
}
@Override
public ProductDto getById(Long id) {
ProductDto productDto = new ProductDto();
Product product = productRepository.getById(id);
productDto.setId(product.getId());
productDto.setName(product.getName());
productDto.setDescription(product.getDescription());
productDto.setCostPrice(product.getCostPrice());
productDto.setSalePrice(product.getSalePrice());
productDto.setCurrentQuantity(product.getCurrentQuantity());
productDto.setCategory(product.getCategory());
productDto.setImage(product.getImage());
return productDto;
}
@Override
public Product findById(Long id) {
return productRepository.findById(id).get();
}
@Override
public List<ProductDto> randomProduct() {
return transferData(productRepository.randomProduct());
}
@Override
public Page<ProductDto> searchProducts(int pageNo, String keyword) {
List<Product> products = productRepository.findAllByNameOrDescription(keyword);
List<ProductDto> productDtoList = transferData(products);
Pageable pageable = PageRequest.of(pageNo, 5);
Page<ProductDto> dtoPage = toPage(productDtoList, pageable);
return dtoPage;
}
@Override
public Page<ProductDto> getAllProducts(int pageNo) {
Pageable pageable = PageRequest.of(pageNo, 6);
List<ProductDto> productDtoLists = this.allProduct();
Page<ProductDto> productDtoPage = toPage(productDtoLists, pageable);
return productDtoPage;
}
@Override
public Page<ProductDto> getAllProductsForCustomer(int pageNo) {
return null;
}
@Override
public List<ProductDto> findAllByCategory(String category) {
return transferData(productRepository.findAllByCategory(category));
}
@Override
public List<ProductDto> filterHighProducts() {
return transferData(productRepository.filterHighProducts());
}
@Override
public List<ProductDto> filterLowerProducts() {
return transferData(productRepository.filterLowerProducts());
}
@Override
public List<ProductDto> listViewProducts() {
return transferData(productRepository.listViewProduct());
}
@Override
public List<ProductDto> findByCategoryId(Long id) {
return transferData(productRepository.getProductByCategoryId(id));
}
@Override
public List<ProductDto> searchProducts(String keyword) {
return transferData(productRepository.searchProducts(keyword));
}
private Page toPage(List list, Pageable pageable) {
if (pageable.getOffset() >= list.size()) {
return Page.empty();
}
int startIndex = (int) pageable.getOffset();
int endIndex = ((pageable.getOffset() + pageable.getPageSize()) > list.size())
? list.size()
: (int) (pageable.getOffset() + pageable.getPageSize());
List subList = list.subList(startIndex, endIndex);
return new PageImpl(subList, pageable, list.size());
}
private List<ProductDto> transferData(List<Product> products) {
List<ProductDto> productDtos = new ArrayList<>();
for (Product product : products) {
ProductDto productDto = new ProductDto();
productDto.setId(product.getId());
productDto.setName(product.getName());
productDto.setCurrentQuantity(product.getCurrentQuantity());
productDto.setCostPrice(product.getCostPrice());
productDto.setSalePrice(product.getSalePrice());
productDto.setDescription(product.getDescription());
productDto.setImage(product.getImage());
productDto.setCategory(product.getCategory());
productDto.setActivated(product.is_activated());
productDto.setDeleted(product.is_deleted());
productDtos.add(productDto);
}
return productDtos;
}
}
ProductRepository:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
@Transactional
@Query("select p from Product p where p.is_deleted = false and p.is_activated = true")
List<Product> getAllProduct();
@Query("select p from Product p where lower(p.name) like %?1% or lower(p.description) like %?1%")
List<Product> findAllByNameOrDescription(String keyword);
@Query("select p from Product p inner join Category c ON c.id = p.category.id" +
" where p.category.name = ?1 and p.is_activated = true and p.is_deleted = false")
List<Product> findAllByCategory(String category);
@Query(value = "select " +
"p.product_id, p.name, p.description, p.current_quantity, p.cost_price, p.category_id, p.sale_price, p.image, p.is_activated, p.is_deleted, p.post_content " +
"from products p where p.is_activated = true and p.is_deleted = false order by random() limit 9", nativeQuery = true)
List<Product> randomProduct();
@Query(value = "select " +
"p.product_id, p.name, p.description, p.current_quantity, p.cost_price, p.category_id, p.sale_price, p.image, p.is_activated, p.is_deleted " +
"from products p where p.is_deleted = false and p.is_activated = true order by p.cost_price desc limit 9", nativeQuery = true)
List<Product> filterHighProducts();
@Query(value = "select " +
"p.product_id, p.name, p.description, p.current_quantity, p.cost_price, p.category_id, p.sale_price, p.image, p.is_activated, p.is_deleted " +
"from products p where p.is_deleted = false and p.is_activated = true order by p.cost_price asc limit 9", nativeQuery = true)
List<Product> filterLowerProducts();
@Query(value = "select p.product_id, p.name, p.description, p.current_quantity, p.cost_price, p.category_id, p.sale_price, p.image, p.is_activated, p.is_deleted from products p where p.is_deleted = false and p.is_activated = true limit 4", nativeQuery = true)
List<Product> listViewProduct();
@Query(value = "select p from Product p inner join Category c on c.id = ?1 and p.category.id = ?1 where p.is_activated = true and p.is_deleted = false")
List<Product> getProductByCategoryId(Long id);
@Query("select p from Product p where p.name like %?1% or p.description like %?1%")
List<Product> searchProducts(String keyword);
}
форма для добавления пост контент:
<textarea id="content2" class="form-control" name="post_content" th:field="*{post_content}" style="display: none;"></textarea>