unable to display data on broswer using spring hibernate.below is my code and output - spring

Unable to display data on broswer using spring hibernate.below is my code and output..
Class: CustomerController
package com.luv2code.springdemo.controller;
import com.luv2code.springdemo.DAO.CustomerDAO;
import com.luv2code.springdemo.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#Autowired
private CustomerDAO customerDAO;
#RequestMapping("/list")
public String listCustomer(Model theModel){
List<Customer> theCustomers = customerDAO.getCustomers();
theModel.addAttribute("customers", theCustomers);
System.out.println(theCustomers);
return "list-customer";
}
}
Class: CustomerDAO Implementation
package com.luv2code.springdemo.DAO;
import com.luv2code.springdemo.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
Session getSession = sessionFactory.getCurrentSession();
Query<Customer> theCustomers = getSession.createQuery("from Customer", Customer.class);
List<Customer> customers = theCustomers.getResultList();
return customers;
}
}
Class: Customer mapping to database
package com.luv2code.springdemo.entity;
import javax.persistence.*;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name = "email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
jsp page..
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<!-- loop over and print our customers -->
<c:forEach var="tempCustomer" items="${customers}">
<tr>
<td> ${tempCustomer.firstName} </td>
<td> ${tempCustomer.lastName} </td>
<td> ${tempCustomer.email} </td>
</tr>
</c:forEach>
</table>
Output

You're probably using an old version of jstl where expressions must be called witch <c:out/> tag.
Try the following in your jsp
<td><c:out value="${tempCustomer.firstName}" /></td>
<td><c:out value="${tempCustomer.lastName}" /></td>
<td><c:out value="${tempCustomer.email}" /></td>

Related

Why am I getting null for the date when I create a Todo entity?

What is wrong with my to-do application? I want the user to be able to add a todo and have it be saved in my MySQL database with the time it was created, but I don't know what I'm doing wrong.
I am new to learning Springboot and would appreciate any suggestions or advice.
Todo Entity:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.util.Date;
#Entity(name = "Todo")
#NoArgsConstructor
#Table(name = "todos")
public class Todo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name="description")
private String description;
#Column(name="target_date")
#CreationTimestamp
private Date targetDate;
public Todo(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
#Override
public String toString() {
return "Todo{" +
"id=" + id +
", description='" + description + '\'' +
", targetDate=" + targetDate +
'}';
}
}
Adding a Todo with Spring Data JPA
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
#Component
public interface TodoRepository extends JpaRepository<Todo, Integer> {
#Modifying
#Query(value = "INSERT INTO todos (description) VALUES (:description)", nativeQuery=true)
#Transactional
void addTodo(#Param("description") String description);
}
TodoController
#RestController
#RequestMapping(value = "/api/v1/todos")
#AllArgsConstructor
public class TodoController {
#Autowired
private ITodoService todoService;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
todoService.addTodo(todo);
return todo.toString();
}
after getting a post request, the target_date is getting NULL in MySQL
I assume you can solve it by using persist():
#Autowired EntityManager entityManager;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
entityManager.persist(todo);
return todo.toString();
}

403 Forbidden post request spring boot not working

I'm having a 403 forbidden request when requesting POST using postman, get is working perfectly and im not using any of spring security tools just spring boot because i have seen some answers talking about disabling csrf which is not my case because im not using any of spring security.
Here is My Entity class:
package com.example.demo.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
#Entity
#Table(name="clients")
public class Clients {
#Id
#Column(name="phone")
private Long phone;
#NotBlank(message="Required Field")
#Column(name="firstname")
private String firstname;
#NotBlank(message="Required Field")
#Column(name="lastname")
private String lastname;
#NotBlank(message="Required Field")
#Column(name="birthDate")
private String birthDate;
#NotBlank(message="Required Field")
#Column(name="email")
private String email;
#NotBlank(message="Required Field")
#Column(name="addressClient")
private String addressClient;
#NotBlank(message="Required Field")
#Column(name="gender")
private String gender;
#Column(name="inscriptionDate")
private Date inscriptionDate;
#NotBlank(message="Required Field")
#Size(min=8 , message="Password needs to be more than 8 characters")
#Column(name="passwordClient")
private String passwordClient;
public Clients() {
}
public Clients(Long phone, #NotBlank(message = "Required Field") String firstname,
#NotBlank(message = "Required Field") String lastname,
#NotBlank(message = "Required Field") String birthDate, #NotBlank(message = "Required Field") String email,
#NotBlank(message = "Required Field") String addressClient,
#NotBlank(message = "Required Field") String gender, Date inscriptionDate,
#NotBlank(message = "Required Field") #Size(min = 8, message = "Password needs to be more than 8 characters") String passwordClient) {
super();
this.phone = phone;
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthDate;
this.email = email;
this.addressClient = addressClient;
this.gender = gender;
this.inscriptionDate = inscriptionDate;
this.passwordClient = passwordClient;
}
#PrePersist
public void newDate() {
this.inscriptionDate=new Date();
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressClient() {
return addressClient;
}
public void setAddressClient(String addressClient) {
this.addressClient = addressClient;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getInscriptionDate() {
return inscriptionDate;
}
public void setInscriptionDate(Date inscriptionDate) {
this.inscriptionDate = inscriptionDate;
}
public String getPasswordClient() {
return passwordClient;
}
public void setPasswordClient(String passwordClient) {
this.passwordClient = passwordClient;
}
}
And Here s my Repository Interface:
package com.example.demo.repositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Clients;
#Repository
public interface ClientsRepository extends JpaRepository<Clients , Long>{
}
My Controller Class:
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.Clients;
import com.example.demo.functions.ClientsFunctionsImpl;
import com.example.demo.repositories.ClientsRepository;
#RestController
public class ClientsController {
#Autowired
private ClientsRepository clientsRepository;
#CrossOrigin("http://localhost:3000")
#GetMapping(path="/clientslist")
public List<Clients> getAllClients(){
return clientsfunctionsimpl.list();
}
#CrossOrigin("http://localhost:3000")
#PostMapping("/clientslist")
public ResponseEntity<Clients> createEmployee(#Valid #RequestBody Clients client) {
Clients client1 = clientsRepository.save(client);
return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
}
}
Your code is working but I want to add one more thing is that use this type of structure it will prevent SQL injection and improve your creation API response.
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping(value = "/createEmployee")
public ResponseEntity<ClientsMetaModel> createEmployee(#Valid #RequestBody ClintsModel model) {
ClientsMetaModel metaModel = new ClientsMetaModel();
// set all your fields into metamodel by getting it from model
return new ResponseEntity<ClientsMetaModel>(empRepo.save(metaModel), HttpStatus.CREATED);
}
You have to kept your id, token, date all fields into metamodel only and try this.
If this will not work then use #CrossOrigin(/*) as global. Also as #Ananthapadmanabhan said in his answer but I advise you that use model and metamodel concept.
Could you try enabling CORS on all ports and url for your endpoint like :
#CrossOrigin
#PostMapping("/clientslist")
public ResponseEntity<Clients> createEmployee(#Valid #RequestBody Clients client) {
Clients client1 = clientsRepository.save(client);
return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
}

EL1008E: Property or field 'isAvailable' cannot be found on object of type 'com.inventory.domain.Item' - maybe not public or not valid?

I have one boolean field in item bean all other fields are populating but only isAvailable is not populating in ui using thymeleaf I am getting error as property can't not found I am not getting the root cause
Is there any specific way to read the boolean field in thymeleaf. because in .html page when i tried to read boolean value st.isAvailable its throwing error in backend property not found hence not populating value
Item Bean
package com.inventory.domain;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
#Entity
#Table(name = "item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int item_id;
#ManyToOne
#JoinColumn(name = "category_id")
private Category categoryId;
#Column(name = "item_name",unique = true)
private String itemName;
#Column(name = "current_stock_quantity")
private double currentStockQuantity;
public double getCurrentStockQuantity() {
return currentStockQuantity;
}
#Column(name = "unit")
#Enumerated(EnumType.STRING)
private ItemWeightUnit unit;
#Column(name = "current_purchase_price")
private double currentPurchasePrice;
#Column(name = "is_available")
private boolean isAvailable;
#Column(name = "is_active")
private boolean isActive;
#Column(name = "item_description")
#Lob
private String itemDescription;
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
private List<Vendor> vendor = new ArrayList<Vendor>();
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
#OrderBy("transaction_date ASC")
private SortedSet<ItemTransaction> itemTransaction=new TreeSet<ItemTransaction>();
#OneToMany(mappedBy = "item",cascade = CascadeType.ALL)
#OrderBy("date ASC")
private SortedSet<PricingHistory> priceHistory=new TreeSet<PricingHistory>();
public SortedSet<ItemTransaction> getItemTransaction() {
return itemTransaction;
}
public void setItemTransaction(SortedSet<ItemTransaction> itemTransaction) {
this.itemTransaction = itemTransaction;
}
public void setCurrentStockQuantity(double currentStockQuantity) {
this.currentStockQuantity = currentStockQuantity;
}
public List<Vendor> getVendor() {
return vendor;
}
public void setVendor(List<Vendor> vendor) {
this.vendor = vendor;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public Category getCategoryId() {
return categoryId;
}
public void setCategoryId(Category categoryId) {
this.categoryId = categoryId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public boolean isAvailable() {
return isAvailable;
}
public void setAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public ItemWeightUnit getUnit() {
return unit;
}
public void setUnit(ItemWeightUnit unit) {
this.unit = unit;
}
public double getCurrentPurchasePrice() {
return currentPurchasePrice;
}
public void setCurrentPurchasePrice(double currentPurchasePrice) {
this.currentPurchasePrice = currentPurchasePrice;
}
public SortedSet<PricingHistory> getPriceHistory() {
return priceHistory;
}
public void setPriceHistory(SortedSet<PricingHistory> priceHistory) {
this.priceHistory = priceHistory;
}
}
<tbody>
<tr th:each="st,iter : ${items}">
<td th:text="${iter.count}"></td>
<td th:text="${st.itemName}"></td>
<td th:text="${st.currentStockQuantity}"></td>
<td th:text="${st.unit}"></td>
<td th:text="${st.currentPurchasePrice}"></td>
<div th:if="${st.isAvailable} == true">
<td>Yes</td>
</div>
<div th:unless="${st.isAvailable} == false">
<td>No</td>
</div>
<td>
<a href="#" class="btn btn-default" th:href="#{/karyawan/form(id=${st.id})}"
title="Edit Data"><span class="glyphicon glyphicon-edit"></span></a>
<a href="#" class="btn btn-default" th:href="#{/karyawan/delete(id=${st.id})}"
title="Delete Data"><span class="glyphicon glyphicon-trash"></span></a>
</td>
</tr>
<tr th:if="${#lists.isEmpty(items.content)}">
<td colspan="13" class="text-center">Data Not Found</td>
</tr>
</tbody>
Getter and Setter for isAvailable method is not correct, when deserializing and serializing then you need to update them.
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}

I want to fetch my product details in database but it throws excepion org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not mapped

I'm keep getting an exception. I've tried to solve this problem for a few days now...
Please help me...
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not mapped [from Product]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
This is my ProductController
package com.controller;
import java.util.List;
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.servlet.ModelAndView;
import com.model.Categories;
import com.model.Product;
import com.service.ProductService;
#Controller
public class ProductController {
#Autowired
private ProductService productService;
// Getters and Setters
public ProductService getProductService() {
return productService;
}
public void setProductService(ProductService productService) {
this.productService = productService;
}
// Request Mapping
#RequestMapping("/getAllProducts")
public ModelAndView getAllProducts() {
List<Product> products = productService.getAllProducts();
return new ModelAndView("productList", "products", products);
}
#RequestMapping("getProductById/{productId}")
public ModelAndView getProductById(#PathVariable(value = "productId") String productId) {
Product product = productService.getProductById(productId);
return new ModelAndView("productPage", "productObj", product);
}
#RequestMapping("/delete/{productId}")
public String deleteProduct(#PathVariable(value = "productId") String productId) {
productService.deleteProduct(productId);
return "redirect:/getAllProducts";
}
#RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.GET)
public String getProductForm(Model model) {
Product product = new Product();
Categories category = new Categories();
category.setCategoryId("1");
product.setProductCategory(category);
model.addAttribute("productFormObj", product);
return "productForm";
}
#RequestMapping(value = "/admin/product/addProduct", method = RequestMethod.POST)
public String addProduct(#ModelAttribute(value = "productFormObj") Product product) {
productService.addProduct(product);
return "redirect:/getAllProducts";
}
}
This is my ProductClass
package com.model;
import java.util.Locale.Category;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "product")
public class Product {
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
#Column
private String productDescription;
#Column
private String productManufacturer;
#Column
private String productName;
#Column
private double productPrice;
#Column(name="stockunit")
private String unitStock;
#ManyToOne
#JoinColumn(name="categoryId")
private Categories productCategory;
// Getters and Setter
public String getProductId() {
return productId;
}
public Categories getProductCategory() {
return productCategory;
}
public String getProductDescription() {
return productDescription;
}
public String getProductManufacturer() {
return productManufacturer;
}
public String getProductName() {
return productName;
}
public double getProductPrice() {
return productPrice;
}
public String getUnitStock() {
return unitStock;
}
public void setProductId(String productId) {
this.productId = productId;
}
public void setProductCategory(Categories category) {
this.productCategory = category;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public void setUnitStock(String unitStock) {
this.unitStock = unitStock;
}
//Constructors
public Product(String productId, Categories productCategory, String productDescription, String productManufacturer,
String productName, double productPrice, String unitStock) {
super();
this.productId = productId;
this.productCategory = productCategory;
this.productDescription = productDescription;
this.productManufacturer = productManufacturer;
this.productName = productName;
this.productPrice = productPrice;
this.unitStock = unitStock;
}
public Product(){
}
}
This is my application Context
<!-- for Entity Classes annotated Classes package -->
<property name="packagesToScan">
<list>
<value>com.model.Product</value>
<value>com.model.Categories</value>
</list>
</property>
</bean>
My Category Class
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "categories")
public class Categories {
#Id
private String categoryId;
#Column
private String Categories;
#OneToMany(mappedBy = "categories")
private List<Product> product;
//And Respective Getters and Setters
ProductList page
<tbody>
<c:forEach items="${products}" var="prod">
<tr>
<td>${prod.productId}</td>
<td>${prod.productCategory}</td>
<td>${prod.productName}</td>
<td>${prod.productPrice}</td>
<td>${prod.unitStock}</td>
<td>${prod.productDescription}</td>
<td>${prod.productManufacturer}</td>
<td>
<span class="glyphicon glyphicon-info"></span>
<span class="glyphicon glyphicon-trash"></span>
</td>
</tr>
</c:forEach>
After a long analyse i have found the solution for this problem
I have modified some code in my daoImpl.
this is older code.
List<Product> products = session.createQuery("from Product").list();
I have changed this to
List<Product> products = session.createCriteria(Product.class).list();
And some changes in appication Context as #v.ladynev said :
<property name="packagesToScan">
<list>
<value>com.model</value>
</list>
</property>
You should specify a package here, not classes
<property name="packagesToScan">
<list>
<value>com.model</value>
</list>
</property>

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist

I am trying to create Spring boot application with JPARepository.My aim is to create the application generic.
In my application i have 4 common functionalities for all the entities as follows :
getAll
getAllNewAfterLastSyncDate
getAllModifiedAfterLastSyncDate
getAllDeletedAfterLastSyncDate
To achive this and avoid redundency of code i created one generic base repository which extends JPARepository as follows :
BaseRepository.java
package dev.ashish.syncdemo.utlities;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface BaseRepository<T> extends JpaRepository<T, Long>{
**#Query("select t from #{#entityName} t where t.deleteFlag = 'F' ")**
public List<T> getAll();
/*public List<T> getAllNewAfterLastSyncDate();
public List<T> getAllModifiedAfterLastSyncDate();
public List<T> getAllDeletedAfterLastSyncDate();
*/
}
I have created common bean which will be extended by all entities in my aplication as it has 5 common attributes or fields used for all entities.
CommonBean.java
package dev.ashish.syncdemo.beans;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class CommonBean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
private Long id;
#Column(name = "code")
private String code;
#Column(name = "created_by")
private Long createdBy;
#Column(name = "created_oy")
private Timestamp createdOn;
#Column(name = "modified_by")
private Long modifiedBy;
#Column(name = "modified_on")
private Timestamp modifiedOn;
#Column(name = "delete_flag")
private String deleteFlag;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Long getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
}
Now Consider i want to use this for customer entity
CustomerEntity.java
package dev.ashish.syncdemo.beans;
import javax.persistence.Column;
public class CustomerEntity extends CommonBean{
#Column(name="first_name")
private String firstName;
#Column(name="middle_name")
private String middleName;
#Column(name="last_name")
private String lastName;
#Column(name="address1")
private String address1;
#Column(name="address2")
private String address2;
#Column(name="landline_no")
private String landlineNo;
#Column(name="mobile_no")
private String mobileNo;
#Column(name="email_id")
private String emailId;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="country")
private String country;
#Column(name="pin_code")
private String pinCode;
#Column(name="fax_number")
private String faxNumber;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getLandlineNo() {
return landlineNo;
}
public void setLandlineNo(String landlineNo) {
this.landlineNo = landlineNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPinCode() {
return pinCode;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public String getFaxNumber() {
return faxNumber;
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
#Override
public String toString() {
return "CustomerEntity [firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName
+ ", address1=" + address1 + ", address2=" + address2 + ", landlineNo=" + landlineNo + ", mobileNo="
+ mobileNo + ", emailId=" + emailId + ", city=" + city + ", state=" + state + ", country=" + country
+ ", pinCode=" + pinCode + ", faxNumber=" + faxNumber + ", getId()=" + getId() + ", getCode()="
+ getCode() + ", getCreatedBy()=" + getCreatedBy() + ", getCreatedOn()=" + getCreatedOn()
+ ", getModifiedBy()=" + getModifiedBy() + ", getModifiedOn()=" + getModifiedOn() + ", getDeleteFlag()="
+ getDeleteFlag() + "]";
}
}
I created CustomerService which extends BaseRepositoy as follows:
CustomerService.java
package dev.ashish.syncdemo.service;
import org.springframework.stereotype.Service;
import dev.ashish.syncdemo.beans.CustomerEntity;
import dev.ashish.syncdemo.utlities.BaseRepository;
#Service("customerService")
public interface CustomerService extends BaseRepository<CustomerEntity>{
}
FrontController.java
package dev.ashish.syncdemo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import dev.ashish.syncdemo.service.CustomerService;
import dev.ashish.syncdemo.utlities.Constants;
#RestController
#RequestMapping("/frontgate")
public class FrontController {
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/getres", method = RequestMethod.POST)
public String getRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String reqStr = request.getReader().readLine();
System.out.println("Request is : " + reqStr);
Map<String, Object> reqMap = new Gson().fromJson(reqStr, new TypeToken<HashMap<String, Object>>() {
}.getType());
System.out.println("Req Map " + reqMap);
return parseRequest(reqMap);
}
public String parseRequest(Map<String, Object> reqMap)
{
String entity = (String)reqMap.get(Constants.ENTITY);
String action = (String)reqMap.get(Constants.ACTION);
String pageSize = (String)reqMap.get(Constants.PAGE_SIZE);
String pageNumber = (String)reqMap.get(Constants.PAGE_NUMBER);
String lastSyncDate = (String)reqMap.get(Constants.LAST_SYNC_DATE);
return customerService.getAll().toString();
}
}
SyncDemoApplication.java
package dev.ashish;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SyncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SyncDemoApplication.class, args);
}
}
Application flow is as follows:
Request will come to FrontController then it will be forwarded to customerservice which is extending base repository of type JPArepository.
As there are all common functionalities i dont want to create repository for all entities separately and write query for each of them. As you can see i am using SPEL #{#entityName} passing entity name at runtime to query in #Query annotation.
When i try to run application it gives me following exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'demo-db.common_bean' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_67]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.7.0_67]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.7.0_67]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:389) ~[mysql-connector-java-5.1.35.jar:5.1.35]
Query being fired is as follows :
Hibernate: select customeren0_.id as id2_0_, customeren0_.code as code3_0_, customeren0_.created_by as created_4_0_, customeren0_.created_oy as created_5_0_, customeren0_.delete_flag as delete_f6_0_, customeren0_.modified_by as modified7_0_, customeren0_.modified_on as modified8_0_, customeren0_.address1 as address9_0_, customeren0_.address2 as address10_0_, customeren0_.city as city11_0_, customeren0_.country as country12_0_, customeren0_.email_id as email_i13_0_, customeren0_.fax_number as fax_num14_0_, customeren0_.first_name as first_n15_0_, customeren0_.landline_no as landlin16_0_, customeren0_.last_name as last_na17_0_, customeren0_.middle_name as middle_18_0_, customeren0_.mobile_no as mobile_19_0_, customeren0_.pin_code as pin_cod20_0_, customeren0_.state as state21_0_
from **common_bean** customeren0_ where customeren0_.dtype='CustomerEntity' and customeren0_.delete_flag='F'
Instead of common_bean in from clause it should be customer as i am doing operation for entity customer.
Please let me know what i am doing wrong.

Resources