Spring, modelmap, getting attributes for displaying Lists in JSTL <c:foreach> - spring

I, a newbie in progrmming, develop spring MVC application with spring mvc frameworks. I want to list the data into table by using JSTL with 2 mapped entities.
<c:forEach items="${empList}" var="emp">
<tr class="odd gradeX">
<td>${emp.icode}</td>
<td>${emp.employeeName}</td>
//problem here
//I want to get employee's phone num
<td>${emp.ph_number}</td>
</tr>
</c:forEach>
This is the example of my Entity,
1) Employee Entity
#Entity
public class Employee implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long employeeId;
private String employeeName;
#OneToMany(mappedBy="employee" ,cascade={CascadeType.ALL})
private List<Phone>phones;
//method getter setter }
2)Phone Entity
#Entity
public class Phone implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long phoneId;
private String ph_number;
#ManyToOne
private Employee employee;
//method getter setter}
3)Enployee Controller
#Controller
public class EmployeeController {
#EJB(mappedName = "ejb:/EJB//EmployeeServiceBean!com.mfu.ejb.EmployeeService")
EmployeeService empServ;
#RequestMapping("/listEmp")
public ModelAndView listEmployee(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("ListEmp.jsp");
List<Employee> empList;
try {
empList = empServ.getAllEmployee();
mv.addObject("empList", empList);
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
}
Thankyou and sorry for my bad English. Hope it make sence.

Related

how to properly design a controller and a jsp page for an entity that has three keys, two external and one internal?

I'm trying to make a Spring MVC application.I have 4 entities(Company,Pass_in_trip,Passenger,Trip) Pass_in_trip has 3 keys consisting of Passenger, Trip and Timestamp, I don't know how to properly issue a key and how to transfer it through the jsp page to the controller, and how to issue the controller itself, can anyone tell me?and also an interesting question is how to make a request to the database to search for a record using three keys.
Thanks
here's what I was able to write at the moment, see if there are any errors somewhere
#Entity
#Table(name="company")
public class Company implements Serializable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name="id_comp")
private int id_comp;
#Column(name="name")
private String name;
//Getters and Setters
#Entity
#Table (name="pass_in_trip")
public class Pass_in_trip implements Serializable {
#EmbeddedId
private KeysPass_in_trip key=new KeysPass_in_trip();
#Column(name="place")
private String place;
//Getters and Setters
#Embeddable
public class KeysPass_in_trip implements Serializable{
#NotNull
#JoinColumn(name="date")
private Timestamp date=new Timestamp(System.currentTimeMillis());
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_psg")
private Passenger id_psg=new Passenger();
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "trip_no" )
private Trip trip_no=new Trip();
//Getters and Setters
//#Override hashCode and equals
#Entity
#Table(name="passenger")
public class Passenger implements Serializable {
#Column(name="name")
private String name;
#NotNull
#Id
#Column(name="id_psg")
#GeneratedValue(strategy = IDENTITY)
private int id_psg;
//Getters and Setters
#Entity
#Table(name="trip")
public class Trip implements Serializable {
#NotNull
#Id
#Column(name="trip_no")
private int trip_no;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "id_comp")
private Company comp=new Company();
#Column(name="plane")
private String plane;
#Column(name="town_from")
private String town_from;
#Column(name="town_to")
private String town_to;
#Column(name="time_out")
private Timestamp time_out;
#Column(name="time_in")
private Timestamp time_in;
//Getters and Setters
Conroller
#Controller
#RequestMapping("/pass_in_trip/")
public class Aero_Controller_Pass_in_trip {
#Autowired
private Aero_DAO service;
public void setService(Aero_DAO service) {
this.service = service;
}
#RequestMapping(method=RequestMethod.GET)
public String list(Model uiModel) {
List <Pass_in_trip> pass_in_trip=service.findallPass_in_trip();
uiModel.addAttribute("pass_in_trip",pass_in_trip);
return "/pass_in_trip/list";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value="delete/{id}",method=RequestMethod.GET)
public String delete(#PathVariable("id")int id, Model uiModel) {
if(service.findByIdPass_in_Trip(id)!=null)
service.delete_Pass_in_trip(id);
return "redirect:/pass_in_trip/";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value="update/{id}",method=RequestMethod.GET)
public String updateform(#PathVariable("id")int id, Model uiModel) {
System.out.println("upform");
uiModel.addAttribute("pass_in_trip",service.findByIdPass_in_Trip(id));
System.out.println("upform2");
return "/pass_in_trip/edit";
}
#RequestMapping(value="update/0",method=RequestMethod.GET)
public String newform(Model uiModel) {
System.out.println("Привет!");
return "/pass_in_trip/edit";
}
#PreAuthorize("hasRole('ROLE_Admin')")
#RequestMapping(value="update/{id}",method = RequestMethod.POST)
public String update(Pass_in_trip pass_in_trip,BindingResult bindingResult,Model uiModel,HttpServletRequest httprervletrequest , RedirectAttributes redirectatributes) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("pass_in_trip", pass_in_trip);
return "pass_in_trip/update";}
service.save(pass_in_trip);
return "redirect:/pass_in_trip/";
}
}
List.jsp
interested in this part:
<s:authorize access="hasRole('ROLE_Admin')">
<td> To change </td>
<td> Delete </td>
</s:authorize>

I don't know why the double values are displayed in postman. Is the my code correct?

This is my Book class:
#Entity
#Table(name="book")
public class Book {
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity=Category.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JoinColumn(name="CategoryId")
public Category category;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(length=10)
private int book_id;
#Column(length=128)
private String title;
#Column(length=64)
private String author;
#Column(length=200)
private String description;
#Column(length=10)
private int ISBN;
#Column(length=10)
private float price;
private Date published_Date;
#Lob
#Column
#Basic(fetch = FetchType.LAZY)
private byte[] icon;
//getter and setter
}
This is my Category class:
#Entity
#Table(name="category1")
public class Category {
#Id
#Column(length=12)
#GeneratedValue(strategy=GenerationType.AUTO)
public int CategoryId;
#Column(length=50)
public String CategoryName;
//#JsonBackReference
#OneToMany(mappedBy="category")
private List<Book> books = new ArrayList<Book>();
//getter and setter
}
The relationship between them is one to many.
This is my Category Service class
#Service
#Transactional
public class AdminServiceImpl implements AdminService {
#Autowired
private CategoryDao dao;
#Autowired
private BookDao dao1;
#Override
public List<Category> getAllCategory(){
return dao.findAll();
}
}
My Controller class
#RestController
#RequestMapping("/bookstore")
public class CategoryController {
#Autowired
private AdminService service;
#GetMapping("/GetAllCategory")
private ResponseEntity<List<Category>> getAllCategory() {
List<Category> catlist = service.getAllCategory();
return new ResponseEntity<List<Category>>(catlist, new HttpHeaders(), HttpStatus.OK);
}
}
My category table already has data.When i try to display them it is showing double values.
Displaying values using Postman
The Category table in the Database: Database table
Jackson's ObjectMapper uses the Java bean pattern and it expects the following
public class Foo {
public Object bar;
public Object getBar() {...}
public void setBar(Object bar) {...}
}
The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized.
Change
CategoryId to categoryId (first letter lowercase)
and
CategoryName to categoryName

When does the hibernate session gets closed

I have created the following entities.
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#OneToMany(mappedBy = "student")
private List<Book> books;
}
#Entity
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#ManyToOne
#JoinColumn(name = "STUDENT_ID")
private Student student;
}
My controller looks like this
#RestController
public class Controller {
MyService myService;
public Controller(MyService myService) {
this.myService = myService;
}
#GetMapping("student")
public List<Book> getBooksForStudent(Long id) {
return myService.getBooks(id);
}
}
The service is as follows.
public class MyService {
#Autowired
private StudentRepo studentRepo;
public List<Book> getStudent(Long id) {
Optional<Student> studentOptional = studentRepo.findById(id);
return studentOptional.map(Student::getBooks).orElseThrow(IllegalArgumentException::new);
}
}
I am getting the list of books as expected. But as I'm having lazy loaded list for books I should be getting a LazyInitializationException. I have not added transnational to the method and I'm returning the list of books from the entity itself without mapping it to a DTO. Why is the hibernate session not getting closed after the end of the method?
#RestController is transactional by default. Spring boot automatically registers an OpenEntityManagerInViewInterceptor when you use a web application/you use JPA. Refer #RestController methods seem to be Transactional by default, Why?

I am not getting any error , exception and also not getting any output on browser

Online shopping project in spring mvc.
This is my Controller class the where i am fetching url but not getting any output.
I am using session for storing cart values.
check my code it is correct for store customer order in a database.
OrderController.java
#Controller
public class orderController
{
#Autowired
private orderDaoInterface orderDao;
#Autowired
private cartDaoInterface cartdao;
#RequestMapping("/order/${id}")
public String createOrder(#PathVariable(value = "id") int id) {
customerOrderModel customerOrder = new customerOrderModel();
Cart cart = cartdao.getCartByID(id);
customerOrder.setCart(cart);
CustomerModel customer = cart.getCustomer();
customerOrder.setCustomerID(customer);
customerOrder.setBillingAddress(customer.getBillingAddress());
customerOrder.setShippingAddress(customer.getShippingAddress());
orderDao.addCustomerOrder(customerOrder);
return "redirect:/view/cart/addItem";
}
CartDao.java
#Repository
#Transactional
public class cartDao implements cartDaoInterface {
#Autowired
private SessionFactory sessionFactory;
public Cart getCartByID(int CartID)
{
Session session = sessionFactory.getCurrentSession();
return (Cart) session.get(Cart.class, CartID);
}
}
CartModel.java
#Entity
public class Cart {
#Id
#GeneratedValue
private int id;
private String name;
private BigDecimal price;
private int quantity;
private CustomerModel customer;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public CustomerModel getCustomer() {
return customer;
}
CustomerOrder_Model.java
#Entity
public class customerOrderModel {
#Id
#GeneratedValue
private String OrderID;
#OneToOne
#JoinColumn(name="ID")
private CustomerModel customerID;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "Cartid")
private Cart cart;
modify the createOrder method is as follows,
#RequestMapping("/order/{id}", method=RequestMethod.GET)
public String createOrder(#PathVariable int id) {
--------
}
if order id is 001, then ulr should be,
http://localhost:8007/Product/order/001
jsp,
<a class="btn btn-light btn-xl" href="<c:url value="/order/${items.id}">Order Now!</a>

spring mvc +hibernate one to many delete option

i am working on spring mvc but i am facing this problem
Provided id of the wrong type. Expected: class java.lang.Long, got class java.lang.Integer
here is my dao code
#Override
public String delete(long id) {
/*sessionFactory.getCurrentSession().createQuery("DELETE FROM Invoice WHERE id = "+ id).executeUpdate();*/
sessionFactory.getCurrentSession().createQuery("DELETE FROM InvoiceBatch WHERE id = "+ id).executeUpdate();
return "Successfuly Deleted";
}
here is my contoller
#RequestMapping(value="/delete",method=RequestMethod.GET)
public ModelAndView deleteEmployee( #RequestParam("id") String id, ModelMap model)
{
Long eid =Long.parseLong(id);
model.put("message",invoicManager.delete(eid));
//model.put("", invoicManager.clientList());
return new ModelAndView("Invoices", model);
}
here is my pojo
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="BATCH_REFERE
am i missing something
kindly help

Resources