Spring Boot JPA Entity class variable not found - java

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.

Related

How to return the genarated ID in CrudDAOImpl.java when using Hibernate-JPA

I use the hibernate-JPA implementation (v5.6.1.Final) in my project.
I have implemented the data access layer as follows:
Class Visualization Diagram.
1.1 Employee.java Entity
package com.elephasvacation.tms.web.entity;
import com.elephasvacation.tms.web.entity.enumeration.GenderTypes;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
#Entity
#Table(name = "employee")
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Employee implements SuperEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Integer id;
#Column(name = "name", nullable = false, length = 200)
private String name;
#Lob
#Column(name = "address")
private String address;
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#Column(name = "nic", length = 45)
private String nic;
#Column(name = "contact", length = 45)
private String contact;
#Column(name = "email", length = 200)
private String email;
#Column(name = "gender", length = 20)
private GenderTypes gender;
#Column(name = "position", length = 45)
private String position;
#Column(name = "status", length = 45)
private String status;
#Column(name = "created")
private LocalDateTime created;
#Column(name = "updated")
private LocalDateTime updated;
/* Constructor with ID attribute. */
public Employee(Integer id,
String name,
String address,
LocalDate dateOfBirth,
String nic,
String contact,
String email,
GenderTypes gender,
String position,
String status) {
this.id = id;
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
this.nic = nic;
this.contact = contact;
this.email = email;
this.gender = gender;
this.position = position;
this.status = status;
}
/* Constructor without ID attribute. */
public Employee(String name,
String address,
LocalDate dateOfBirth,
String nic,
String contact,
String email,
GenderTypes gender,
String position,
String status) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
this.nic = nic;
this.contact = contact;
this.email = email;
this.gender = gender;
this.position = position;
this.status = status;
}
#PrePersist
public void creationTimeStamps() {
created = LocalDateTime.now();
}
#PreUpdate
public void updateTimeStamps() {
updated = LocalDateTime.now();
}
}
I want to return the Generated ID when an object is persisted successfully. So, I Implemented EmployeeDAOImpl.java as follows:
1.2 EmployeeDAOImpl.java
package com.elephasvacation.tms.web.dal.custom.impl;
import com.elephasvacation.tms.web.dal.custom.EmployeeDAO;
import com.elephasvacation.tms.web.entity.Employee;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
public class EmployeeDAOImpl implements EmployeeDAO {
private EntityManager entityManager;
#Override
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public Integer save(Employee employee) throws Exception {
this.entityManager.persist(employee);
// call the flush method on EntityManager manually, because we need to get the Generated ID
this.entityManager.flush();
return employee.getId(); // here, generated ID will be returned.
}
#Override
public void update(Employee employee) throws Exception {
this.entityManager.merge(employee);
}
#Override
public void delete(Integer key) throws Exception {
this.entityManager.remove(this.entityManager.find(Employee.class, key));
}
#Override
public Employee get(Integer key) throws Exception {
return this.entityManager.find(Employee.class, key);
}
#Override
public List<Employee> getAll() throws Exception {
Query allEmployeesQuery = this.entityManager.createQuery("SELECT e FROM Employee e");
return (List<Employee>) allEmployeesQuery.getResultList();
}
}
I am refactoring the code as follows:
by creating CrudDAOImpl.java
Class Visualization Diagram After Using CrudDAOImpl.java
2.1 CrudDAOImpl.java
package com.elephasvacation.tms.web.dal;
import com.elephasvacation.tms.web.entity.SuperEntity;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
public class CrudDAOImpl<T extends SuperEntity, K extends Serializable> implements CrudDAO<T, K> {
private EntityManager entityManager;
private Class<T> entityClass;
public CrudDAOImpl() {
this.entityClass =
(Class<T>) (((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]);
}
/** This method is used to pass the EntityManager to the lower level classes that extend the CrudDAOImpl class.
* */
protected EntityManager getEntityManager(){
return this.entityManager;
}
#Override
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public Integer save(T entity) throws Exception {
/* If native hibernate is used in my project. I can do something like this;
this will return the generated ID:
* this.session.save(entity);
*
* Since I go with hibernate-JPA implementation I want to do the same thing in this method. */
this.entityManager.persist(entity);
this.entityManager.flush();
return null; // I want to return the generated ID here.
}
#Override
public void update(T entity) throws Exception {
this.entityManager.merge(entity);
}
#Override
public void delete(K key) throws Exception {
this.entityManager.remove(key);
}
#Override
public T get(K key) throws Exception {
return this.entityManager.find(this.entityClass, key);
}
#Override
public List<T> getAll() throws Exception {
TypedQuery<T> query =
this.entityManager.createQuery("SELECT " + (this.entityClass.getName()), this.entityClass);
return query.getResultList();
}
}
I would appreciate it if you could please suggest to me a way to return the generated ID when an object persists in the database. Thanks in advance.
If you are interested here's what I have done. I have used SuperEntity.java as #HasnainAliBohra suggested.
Add a getId() method to SuperEntity.java.
package com.elephasvacation.tms.web.entity;
import java.io.Serializable;
public interface SuperEntity extends Serializable {
<T extends Serializable> T getId();
}
Mostly, generated ID will be a java.lang.Integer, So it is Serializable.
Create a getter for the id attribute in Employee.java. Please note that I have used Project Lombok. So, the #Data annotation generates the getter for the id attribute.
Anyhow, getter method looks like this:
// Employee.java class
public Integer getId() {
return id;
}
Change the save() method in CrudDAOImpl.java as follows:
#Override
public Integer save(T entity) throws Exception {
this.entityManager.persist(entity);
this.entityManager.flush();
return entity.getId(); // Let's return the generated ID here.
}
Testing what I have done (with JUnit4).
package com.elephasvacation.tms.web.dal.custom.impl;
import com.elephasvacation.tms.web.dal.DAOFactory;
import com.elephasvacation.tms.web.dal.DAOTypes;
import com.elephasvacation.tms.web.dal.custom.EmployeeDAO;
import com.elephasvacation.tms.web.entity.Employee;
import com.elephasvacation.tms.web.entity.enumeration.GenderTypes;
import com.elephasvacation.tms.web.util.HibernateUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.time.LocalDate;
import static org.junit.Assert.assertNotNull;
public class EmployeeDAOImplTest {
private final EmployeeDAO employeeDAO = DAOFactory.getInstance().getDAO(DAOTypes.EMPLOYEE);
private EntityManagerFactory emf;
private EntityManager em;
#Before
public void setUp() {
try {
/* get EntityManagerFactory. */
this.emf = HibernateUtil.getEntityManagerFactory();
/* creates EntityManager. */
this.em = emf.createEntityManager();
} catch (Exception e) {
e.printStackTrace();
}
}
#After
public void tearDown() {
/* close the EntityManagerFactory and EntityManager. */
if (em != null) {
em.close();
emf.close();
}
}
#Test
public void save() {
try {
/* begins the transaction. */
this.em.getTransaction().begin();
/* set EntityManager. */
this.employeeDAO.setEntityManager(this.em);
/* creates a new Employee object. */
Employee john = new Employee("John Doe",
"New York",
LocalDate.of(1991, 01, 01),
"112233445566",
"03321234567",
"john.test#gmail.com",
GenderTypes.MALE,
"Trainee",
"Active");
/* saving the Employee. */
Integer generatedEmployeeId = this.employeeDAO.save(john);
/* assert */
assertNotNull(generatedEmployeeId);
/* print the generated ID on the terminal. */
System.out.println("Generated Employee ID: " + generatedEmployeeId);
/* committing the transaction. */
this.em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Test case did run successfully and the database record persisted in the employee table.
5.1 Terminal output
5.2 Database record screenshot.
Hope you find something useful, thank you.

CRUD API Spring Boot Make a Copy of an entry

I am trying to make a copy of an instance which I am fetching from a CRUD Repository. I want to store the copy of an instance but with a different primary key. In the copy method which I have made in the service class, when I try to make a copy, it throws an error saying org.hibernate.HibernateException: identifier of an instance of SpringBootStarter.Topic.Topic was altered from <id> to <new_id> When I hit a GET request on postman after making the copy, I want to see both the original and the copy in the result (but the copy with a different primary key.)
Can somebody please help me?
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
public Topic(){
}
public Topic(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
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;
}
}
Below is the Controller Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class TopicController {
#Autowired
private TopicService topicService;
#GetMapping("/topics")
public List<Topic> getAllTopics(){
return topicService.getAllTopics();
}
#GetMapping("/topics/{id}")
public Topic getTopic(#PathVariable String id){
return topicService.getTopic(id);
}
#PostMapping("/topics")
public void addTopic(#RequestBody Topic topic){
topicService.addTopic(topic);
}
#PostMapping("topics/{id}/{new_id}")
public void copyTopic(#PathVariable String id, #PathVariable String new_id){
topicService.copyTopic(id, new_id); }
#PutMapping("/topics/{id}")
public void updateTopic(#RequestBody Topic topic, #PathVariable String id){
topicService.updateTopic(topic, id);
}
#DeleteMapping("/topics/{id}")
public void deleteTopic(#PathVariable String id){
topicService.deleteTopic(id);
}
}
Below is the Service Class
package SpringBootStarter.Topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
public List<Topic> getAllTopics(){
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics :: add);
return topics;
}
public Topic getTopic(String id){
Optional<Topic> optional = topicRepository.findById(id);
return optional.get();
}
public void addTopic(Topic topic){
topicRepository.save(topic);
}
public void copyTopic(String id, String new_id){
Topic topic = topicRepository.findById(id).get();
Topic topicCopy = topic;
topicCopy.setId(new_id);
addTopic(topicCopy);
}
public void updateTopic(Topic topic, String id){
topicRepository.save(topic);
}
public void deleteTopic(String id){
topicRepository.deleteById(id);
}
}
Below is the Topic Repository
import org.springframework.data.repository.CrudRepository;
public interface TopicRepository extends CrudRepository<Topic, String> {
}
The persistence context holds the lifecycle of all entities. When you fetch an entity it will be an attached entity within that transsaction. Because the reference of your object does not change, the persistence context will know that it's still the same object in the database which does not allow it's identifier to change.
If you want to create a new entry, you will have to create a new object using the new keyword and persist that one.
So instead of changing the identifier like so
public void copyTopic(String id, String new_id){
Topic topic = topicRepository.findById(id).get();
Topic topicCopy = topic;
topicCopy.setId(new_id);
addTopic(topicCopy);
}
Create a new Topic entity and persist it like so
public void copyTopic(String id, String new_id){
Topic topic = topicRepository.findById(id).get();
Topic topicCopy = new Topic(topic);
topicCopy.setId(new_id);
addTopic(topicCopy);
}
My advice is to read up on the basics of Hibernate because there are a lot of pitfalls when using an ORM. It's never a good idea to start using one without understanding the very basics.

Error in returning list of objects for the spring boot application in microservices development

I followed the microservices tutorial from youtube to create independent services (spring boot Application)
I created a service implementation java file providing method definitions for the request mapping URL (/catalog/userId) for the read operation
To the above requested URL, returning a list of objects as the response body (HTTP response) for the HTTP read request
In the java, error occurring for the function definition of sending a list of objects
The error occurs in line 17 of MovieCatalogResource.java stating the illegal start of expression, unexpected token
I researched for the error but still I am struck with the execution
can you guys kindly provide your help to resolve issue with your suggestions
Providing the code below
CatalogItem.java
package com.example.moviecatalogservice;
public class CatalogItem {
private String name;
private String desc;
private int rating;
public CatalogItem(String name, String desc, int rating){
this.name = name;
this.desc = desc;
this.rating = rating;
}
public int getRating(){
return rating;
}
public void setRating(){
this.rating = rating;
}
public String getName(){
return name;
}
public void setName(){
this.name = name;
}
public String getDesc(){
return desc;
}
public void setDesc(){
this.desc = desc;
}
}
MovieCatalogService.java
package com.example.moviecatalogservice;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.an notation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
#RestController
#RequestMapping("/catalog")
public class MovieCatalogResource {
#RequestMapping("/{userId}")
//public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
return Collections.singletonList(
new CatalogItem(name: "transformers", desc:"Test", rating:4)
);
}
}
change
new CatalogItem(name: "transformers", desc:"Test", rating:4)
To
new CatalogItem("transformers", "Test", 4)
You must have a matching CatalogItem() constructor in CatalogItem
Entity Or Model
After a change at line no 17 of MovieCatalogResource.java it will look like as below
#RestController
#RequestMapping("/catalog")
public class MovieCatalogResource {
#RequestMapping("/{userId}")
//public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
public List<CatalogItem> getCatalog(#PathVariable("userId") String userId){
return Collections.singletonList(
new CatalogItem("transformers", "Test", 4)
);
}
}
Working Example
Controller.java
#GetMapping("/{id}")
public List<User> getUser(#PathVariable(name="id") int id)
{
return Collections.singletonList(
new User(1,"username")
);
}
User.java
public class User {
private int id;
private String name;
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
Tested using Postman
Why are you doing this :
new CatalogItem(name: "transformers", desc:"Test", rating:4)
instead of this :
new CatalogItem("transformers", "Test", 4)
at line no 17 of MovieCatalogResource.java?
Change the below statement from new CatalogItem(name: "transformers", desc:"Test", rating:4) to new CatalogItem("transformers","Test",4)

i can not add database in admin page [duplicate]

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

Spring MVC Hibernate web application

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");
}

Categories