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");
}
Related
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.
Dear Stackoverflow community,
I am new to working with generics and have problems with using genericts correctly. What I want to do is, that a static method can take a generic Object as a parameter. My idea is, to pass Entity Objects as parameter and after return a UserDetailsImpl object. So I want to make this method able to handle different entity classes and dont write boilerplatecode. For this I write an easy Box class for it.
Box.java
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Now I try to use it to pass generic object as parameter in my UserDetailsImpl.java class in the static build method:
package com.yildiz.tradilianz.security.services;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String email;
#JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(Long id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(Box<Object> user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
Now the problem is, that the passed Object doesn't know the whole get() methods I try to access like user.getId(), user.getRoles(), user.getPassword() etc. I want that the generic Box Class contains any Object but how to declare this method I need to access from it?
Otherwise it ends up with "The method getRoles() is undefined for the type Box"
What I wanted to pass as generic Object is my customer entity class, but if it returns null instead i want to test if retailer entity class works and so on in **UserDetailsServiceImpl **:
package com.yildiz.tradilianz.security.services;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yildiz.tradilianz.auth.User;
import com.yildiz.tradilianz.auth.UserRepository;
import com.yildiz.tradilianz.customer.Customer;
import com.yildiz.tradilianz.customer.CustomerDTO;
import com.yildiz.tradilianz.customer.CustomerRepository;
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
CustomerRepository customerRepository;
#Autowired
CustomerDTO customerDTO;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Check for username or email passed through username parameter
boolean valid = EmailValidator.getInstance().isValid(username);
if (valid == false) {
/*
* Build with UserDetailsImpl but if user for Customer class is null I want to try another repository and do
* something like this:
* Retailer user = retailerRepository.findByUsername(username); And if it is not null
* it should pass user Object which class is Retailer and so on.
*
*/
Customer user = customerRepository.findByUsername(username);
return UserDetailsImpl.build(user);
} else {
Customer user = customerRepository.findByEmail(username):
return UserDetailsImpl.build(user);
}
}
}
customer entity class
package com.yildiz.tradilianz.customer;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import com.yildiz.tradilianz.auth.ERole;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Size(max = 20)
private String username;
#NotBlank
#Size(max = 120)
private String password;
#Column(nullable = false)
private String givenName;
#Column(nullable = false)
private String surname;
private String birthday;
private String streetAddress;
private String city;
private String postalCode;
#Column(updatable = false, nullable = false)
private String email;
private String phoneNumber;
#CreationTimestamp
private Timestamp timestamp;
private Double balance;
private Integer bonuspoints;
private String role;
protected Customer() {
}
public Customer(String username,String password, String givenName, String surname, String birthday, String streetAddress, String city,
String postalCode, String email, String phoneNumber, Double balance, Integer bonuspoints, String role) {
this.username = username;
this.password = password;
this.givenName = givenName;
this.surname = surname;
this.birthday = birthday;
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
this.email = email;
this.phoneNumber = phoneNumber;
this.balance = balance;
this.bonuspoints = bonuspoints;
this.role = role;
}
#Override
public String toString() {
return ("Benutzername: "+username+ "Passwort: "+password+ "Vorname: " + givenName + " Nachname: " + surname +
" Geburtstag: " + birthday + " Straße: "+ streetAddress + " Stadt: " + city + " Postleitzahl: " +
postalCode + " E-Mail-Adresse: " + email+ " Telefonnummer: " + phoneNumber + "Kontostand: " + balance +
" Bonuspunkte: " + bonuspoints+" Rolle:"+role);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public Long getId() {
return id;
}
public String getGivenName() {
return givenName;
}
public String getSurname() {
return surname;
}
public String getBirthday() {
return birthday;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Timestamp getTimestamp() {
return timestamp;
}
public Integer getBonuspoints() {
return bonuspoints;
}
public Double getBalance() {
return balance;
}
public String getRole() {
return role;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public void setCity(String city) {
this.city = city;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public void setBonuspoints(Integer bonuspoints) {
this.bonuspoints = bonuspoints;
}
public void setRole(String role) {
this.role = role;
}
}
**
Can you pls give me tipps how I do it the right way?
in your build() method, you are passing Box, so it only knows the type as Object.
public static UserDetailsImpl build(Box<Object> user)
when you try to access it, you are trying to access the methods from type Customer, which it will not have any clue what methods are associated with Customer object. (user reference will only know about Box class methods)
so, what you need to do is change Box<Object> to Box<Customer> and then access the Customer's methods using
user.get().getId() etc.
here user.get() will return the underlying type object and you will have access to its methods.
or what you can also do is if you want the generic type to be a specific instance type, you can change your Box class implementation to be (extends T type to an instance of that class), for e.g. Customer in your case. (you ca create an interface or abstract class that will have methods that you are trying to use)
public class Box< T extends Customer>
public class Box<T extends CustomerInterface> etc.
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.
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
I am working on a spring mvc app in which I have 2 model classes. Following are my model classes:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#ManyToOne
#JoinColumn(name="locationid")
private LocationModel locationModel;
public LocationModel getLocationModel() {
return locationModel;
}
public void setLocationModel(LocationModel locationModel) {
this.locationModel = locationModel;
}
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and LocationModel
import java.util.List;
//import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
#OneToMany(mappedBy = "locationModel")
private List<ContactModel> contactList;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLocationType() {
return locationType;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getLocationDescription() {
return locationDescription;
}
public void setLocationDescription(String locationDescription) {
this.locationDescription = locationDescription;
}
}
On deleting location I want to set location of corresponding contacts to null. I am using following code for this:
public void selLocationToNull(int locationId) throws Exception {
try {
logger.info("deleteContact() begins:");
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel=:locationId");
query.setParameter("newLocation", null);
query.setParameter("locationId", locationId);
query.executeUpdate();
logger.info("null update query executed...");
} catch (Exception e) {
logger.debug("Error while updating location to null: "
+ e.getMessage());
throw e;
} finally {
}
}
I am getting exception for this:
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.bizmerlin.scm.model.LocationModel.locationId
Caused by: java.lang.IllegalArgumentException: Can not set int field com.bizmerlin.scm.model.LocationModel.locationId to java.lang.Integer
I have getter method for locationId in my LocationModel class.
How can you set a null to a primitive type? It is generally good practice to use wrapper types for fields in your Entity.
#Id
#Column(name="locationid")
#GeneratedValue
private Integer locationId;
You set in the query's where LocationModel and compare it with int. SHould be
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel.id=:locationId");
instead. Or pass the LocationModel instance rather than id