Spring framework - Data not display in view page - spring

no errors display in my view...but when it run it gives the value as '0'. my database table name is 'categories'.it has a value like 'category_l dummy' for the column .But in the view display as a 0...please help me to slove this...
This is my model class
#Entity
#Table(name = "categories")
public class CategoriesModel implements Serializable{
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO) //for autonumber
private int id;
#Column
private String category1;
#Column
private String desccategory1;
public CategoriesModel() {
}
public CategoriesModel(
int id,
String category1, String desccategory1) {
super();
this.id = id;
this.category1 = category1;
this.desccategory1 = desccategory1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory1() {
return category1;
}
public void setCategory1(String category1) {
this.category1 = category1;
}
public String getDesccategory1() {
return desccategory1;
}
public void setDesccategory1(String desccategory1) {
this.desccategory1 = desccategory1;
}
This is my Dao class
public interface CategoriesDao {
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
}
This is my Dao impl class
#Repository
public class CategoriesDaoImpl implements CategoriesDao {
#Autowired
private SessionFactory session;
#Override
public void add(CategoriesModel categories) {
session.getCurrentSession().save(categories);
//this "categories" is a table name
}
#Override
public void edit(CategoriesModel categories) {
session.getCurrentSession().update(categories);
//this "categories" is a table name
}
#Override
public void delete(int id) {
session.getCurrentSession().delete(getCategoriesModel(id));
//this "id" is a feild in Model
}
#Override
public CategoriesModel getCategoriesModel(int id) {
return (CategoriesModel) session.getCurrentSession().get(CategoriesModel.class, id);
}
#Override
public List getAllCategoriesModel() {
return session.getCurrentSession().createQuery("from CategoriesModel").list();
//this "CategoriesModel" is a its model name
}
This is my service class
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
This is my service impl class
#Service
public class CategoriesServiceImpl implements CategoriesService {
#Autowired
private CategoriesDao CategoriesDao;
#Transactional
public void add(CategoriesModel categories) {
CategoriesDao.add(categories);
}
#Transactional
public void edit(CategoriesModel categories) {
CategoriesDao.edit(categories);
}
#Transactional
public void delete(int id) {
CategoriesDao.delete(id);
}
#Transactional
public CategoriesModel getCategoriesModel(int id) {
return CategoriesDao.getCategoriesModel(id);
}
#Transactional
public List getAllCategoriesModel() {
return CategoriesDao.getAllCategoriesModel();
}
this is my controller class
#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Map<String, Object> map) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
map.put("category", categories);
//new created object is assign and view name
map.put("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}
this is my view
<c:forEach items="${categoriesList}" var="category">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="category">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6 ">
<a href="" target="_self"><img src="images/properties/cars.png" class="img-responsive">
<div class="link">
<p>${category.category1}</p>
</div>
</div>

#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Model model) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
model.addAttribute("category", categories);
//new created object is assign and view name
model.addAttribute("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}

Related

How do I make my second dropdown dependent on the first in Springboot Thymeleaf?

I have Studyfields and Modules and I only want the Modules for the respective Studyfield to be displayed in the dropdown. Like you can see at the moment it shows all Modules in the second Dropdown. How can I only show the Module to the respective StudyField in the second Dropdown?
This is my code:
View:
<select style="margin: 10px" name="studyfields" id="studyfields" th:required="required">
<option th:each="studyField : ${studyFields}" th:value="${studyField.getId()}" th:text="${studyField.getStudyField()}" >Select a Studyfield</option>
</select>
<div id="test1" style="display: none">
<label for="modules">Modul:</label>
<select style="margin: 10px" name="modules" id="modules" th:required="required">
<option th:each="module : ${modules}" th:value="${module.getId()}" th:text="${module.getName()}" >Select a Studyfield</option>
</select>
Controller:
#Controller
public class QuestionController {
private final QuestionService questionService;
private final CommentService commentService;
private final StudyFieldService studyFieldService;
private final ModuleService moduleService;
private final UserService userService;
public QuestionController(QuestionService questionService, CommentService commentService,
StudyFieldService studyFieldService,
ModuleService moduleService, UserService userService) {
this.questionService = questionService;
this.commentService = commentService;
this.studyFieldService = studyFieldService;
this.moduleService = moduleService;
this.userService = userService;
}
#GetMapping("/question/{id}")
public String showQuestion(#PathVariable long id, Model model) {
Question question = questionService.getQuestionById(id).orElseThrow(QuestionNotFound::new);
List<Comment> comments = commentService.getCommentsByQuestionId(id);
model.addAttribute("studyFields", studyFieldService.getAllStudyFields());
model.addAttribute("modules", moduleService.getAllModules());
model.addAttribute("question", question);
model.addAttribute("comments", comments);
return "question";
}
#GetMapping("/add-question")
public String goToAddQuestion(Model model) {
model.addAttribute("question", new Question());
model.addAttribute("studyFields", studyFieldService.getAllStudyFields());
model.addAttribute("modules", moduleService.getAllModules());
return "add-question";
}
Module Service:
#Service
public class ModuleService {
private final ModuleRepository moduleRepository;
public ModuleService(ModuleRepository moduleRepository) {
this.moduleRepository = moduleRepository;
}
public Optional<Module> getModuleById(long id){
return moduleRepository.findById(id);
}
public List<Module> getAllModules() {
return moduleRepository.findAll();
}
public List<Module> getAllModulesByStudyField(StudyField studyField) {
return moduleRepository.findAllByStudyField(studyField);
}
public List<Module> getAllModulesByStudyFieldId(long id) {
return getAllModules().stream()
.filter(module -> module.getStudyField().getId() == id).collect(Collectors.toList());
}
}
StudyField Service:
#Service
public class StudyFieldService {
private final StudyFieldRepository studyFieldRepository;
public StudyFieldService(StudyFieldRepository studyFieldRepository) {
this.studyFieldRepository = studyFieldRepository;
}
public Optional<StudyField> getStudyFieldById(long id) {
return studyFieldRepository.findById(id);
}
public List<StudyField> getAllStudyFields() {
return studyFieldRepository.findAll();
}
public StudyField addStudyField(StudyField studyField) {
return studyFieldRepository.save(studyField);
}
public StudyField getStudyFieldByName(String studyFieldName){return studyFieldRepository.getStudyFieldByStudyField(studyFieldName);}
}

Bidirectional OneToMany-ManyToOne Relationship referencing unsaved transient instance (Spring MVC - Thymeleaf)

new here. I'm new to Spring and Thymeleaf, I'm trying to learn by following a video and I don't know why I get the following exception (org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.launchcode.codingevents.models.Event.eventCategory -> org.launchcode.codingevents.models.EventCategory) when I try to creat an Event giving it an EventCategory in the Thymeleaf form. I tried cascading from one side, then from the other and then from both, but it didn't work.
I'll be immensely grateful with whoever helps me out.
Here's my code.
#MappedSuperclass
public abstract class AbstractEntity {
#Id
#GeneratedValue
private int id;
public int getId() {
return id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractEntity entity = (AbstractEntity) obj;
return this.id == entity.id;
}
#Entity
public class Event extends AbstractEntity {
#NotBlank(message = "Name is required")
#Size(min = 3, max = 50, message = "Name must be between 3 and 50 characters")
private String name;
#Size(max = 500, message = "Description too long!")
private String description;
#NotBlank(message = "Email is required")
#Email(message = "Invalid email. Try again")
private String contactEmail;
#ManyToOne
#NotNull(message = "Category is required")
private EventCategory eventCategory;
public Event() {
}
public Event(String name, String description, String contactEmail, EventCategory eventCategory) {
this.name = name;
this.description = description;
this.contactEmail = contactEmail;
this.eventCategory = eventCategory;
}
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 String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public EventCategory getEventCategory() {
return eventCategory;
}
public void setEventCategory(EventCategory eventCategory) {
this.eventCategory = eventCategory;
}
#Override
public String toString() {
return name;
}
#Entity
public class EventCategory extends AbstractEntity implements Serializable {
#Size(min = 3, message = "Name must be at least 3 characters long")
private String name;
#OneToMany(mappedBy = "eventCategory")
private final List<Event> events = new ArrayList<>();
public EventCategory() {
}
public EventCategory(#Size(min = 3, message = "Name must be at least 3 characters long") String name) {
this.name = name;
}
public List<Event> getEvents() {
return events;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
#Controller
#RequestMapping("events")
public class EventController {
#Autowired
private EventRepository eventRepository;
#Autowired
private EventCategoryRepository eventCategoryRepository;
#GetMapping
public String displayAllEvents(#RequestParam(required = false) Integer categoryId, Model model) {
if (categoryId == null) {
model.addAttribute("title", "All Events");
model.addAttribute("events", eventRepository.findAll());
} else {
Optional<EventCategory> result = eventCategoryRepository.findById(categoryId);
if (!result.isPresent()) {
model.addAttribute("title", "Invalid Category Id: " + categoryId);
} else {
EventCategory category = result.get();
model.addAttribute("title", "Events in Category: " + category.getName());
model.addAttribute("events", category.getEvents());
}
}
return "events/index";
}
// Lives at /events/create
#GetMapping("create")
public String displayCreateEventForm(Model model) {
model.addAttribute("title", "Create Event");
model.addAttribute(new Event());
model.addAttribute("categories", eventCategoryRepository.findAll());
return "events/create";
}
// lives at /events/create
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
eventRepository.save(newEvent);
return "redirect:";
}
// lives at /events/delete
#GetMapping("delete")
public String displayDeleteEventForm(Model model) {
model.addAttribute("title", "Delete Events");
model.addAttribute("events", eventRepository.findAll());
return "events/delete";
}
// lives at /events/delete
#PostMapping("delete")
public String processDeleteEventForm(#RequestParam(required = false) int[] eventIds) {
if (eventIds != null) {
for (int id : eventIds) {
eventRepository.deleteById(id);
}
}
return "redirect:";
}
}
Create Event
<nav th:replace="fragments :: navigation"></nav>
<form method="post" th:action="#{/events/create}" th:object="${event}">
<div class="form-group">
<label>Name
<input class="form-control" th:field="${event.name}">
</label>
<p class="error" th:errors="${event.name}"></p>
</div>
<div class="form-group">
<label>Description
<input class="form-control" th:field="${event.description}">
</label>
<p class="error" th:errors="${event.description}"></p>
</div>
<div class="form-group">
<label>Contact Email
<input class="form-control" th:field="${event.contactEmail}">
</label>
<p class="error" th:errors="${event.contactEmail}"></p>
</div>
<div class="form-group">
<label>Category
<select th:field="${event.eventCategory}">
<option th:each="eventCategory : ${categories}" th:value="${eventCategory.id}"
th:text="${eventCategory.name}">
</option>
</select>
<p class="error" th:errors="${event.eventCategory}"></p>
</label>
</div>
<div th:replace="fragments :: create-button"></div>
</form>
As per your code you are only trying to save Event entity and ignoring EventCategory.
You need to set Event to EventCategory as well as EventCategory to Event and make the cascade save.
First add cascade property in Event entity as below.
#ManyToOne(cascade = CascadeType.ALL)
#NotNull(message = "Category is required")
private EventCategory eventCategory;
Then in the Controller make the following changes.
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
EventCategory eventCategory = newEvent.getEventCategory();
eventCategory.setEvent(newEvent);
eventRepository.save(newEvent);
return "redirect:";
}

Spring Boot - Apache Derby duplicating IDs of a ListArray objects

This little project follows a basic MVC pattern, i'm using spring boot and apache derby as an embedded data base.
1) When adding a hardcoded object list inside service class, they all share the same id. Is there an explanation for this behavior ?
This shows the problem (Don't mind the 'kkk' objects, i've solved that part already)
Screen1
So this is the object account i'm working with :
#Entity
public class Account {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String owner;
private double budget;
private double budgetInvest;
private double budgetFonction;
public Account() {
}
public Account(String owner, double budget, double budgetInvest, double budgetFonction
) {
this.owner=owner;
this.budget = budget;
this.budgetInvest = budgetInvest;
this.budgetFonction = budgetFonction;
}
public Account (String owner, double budget) {
this.owner = owner;
this.budget=budget;
}
public Account (String owner) {
this.owner=owner;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
public double getBudgetInvest() {
return budgetInvest;
}
public void setBudgetInvest(double budgetInvest) {
this.budgetInvest = budgetInvest;
}
public double getBudgetFonction() {
return budgetFonction;
}
public void setBudgetFonction(double budgetFonction) {
this.budgetFonction = budgetFonction;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
These are the lines responsible for displaying the objects inside the view :
<tr th:each="account : ${accounts}">
<td th:text="${account.id}">id</td>
<td><a href="#" th:text="${account.owner}">Title
...</a></td>
<td th:text="${account.budget}">Text ...</td>
</tr>
Here is the controller :
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.GET)
public String addAccount(Model model) {
model.addAttribute("account", new Account());
return "accountAdd";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.POST)
public String postAccount(#ModelAttribute Account account) {
accountService.addAccount(account);
return "redirect:listAccount";
}
#RequestMapping(value="/listAccount", method=RequestMethod.GET)
public String listAccount(Model model) {
System.out.println(accountService.getAllAccounts());
model.addAttribute("accounts",accountService.getAllAccounts());
return "listAccount";
}
}
And finally the service class :
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public List<Account> getAllAccounts(){
List<Account>accounts = new ArrayList<>(Arrays.asList(
new Account("Maths Department",1000000,400000,600000),
new Account("Physics Department",7000000,200000,500000),
new Account("Science Department",3000000,700000,1000000)
));
accountRepository.findAll().forEach(accounts::add);
return accounts;
}
public Account getAccount(long id) {
return accountRepository.findById(id).orElse(null);
}
public void addAccount(Account account) {
accountRepository.save(account);
}
public void updateAccount(long id, Account account) {
accountRepository.save(account);
}
public void deleteAccount(long id) {
accountRepository.deleteById(id);
}
}
Ok, so while i haven't yet found the exact answer as to why it affects the same id for every object in a static list.
I found an elegant workaround to not only solve the issue but also enhance the structure of the code.
Instead of doing whatever barbaric initialization I was trying to perform, It's way better to do this inside the main class :
#SpringBootApplication
public class PayfeeApplication {
#Autowired
private AccountRepository accountRepository;
public static void main(String[] args) {
SpringApplication.run(PayfeeApplication.class, args);
}
#Bean
InitializingBean sendDatabase() {
return () -> {
accountRepository.save(new Account("Maths Department",1000000,400000,600000));
accountRepository.save(new Account("Physics Department",7000000,200000,500000));
accountRepository.save(new Account("Science Department",3000000,700000,1000000));
};
}
}

Spring Mvc display session in jsp

I have created a simple shopping cart project using spring framework. I've created a button add to cart so that when clicked it will create session of that item. I have following codes
<button href="/addcart/1">Add to button</button>
This is my controller
#RequestMapping("/addcart/{id}")
public ModelAndView goCart(#PathVariable("id")int id,HttpServletRequest request, HttpSession session) {
List<CartItem> cart = new ArrayList<CartItem>();
cart.add(new CartItem(productService.findProductCart(id),1));
session.setAttribute("cart", cart);
ModelAndView model = new ModelAndView();
model.setViewName("cart");
return model;
}
this is my CartItem class
public class CartItem {
private List<Product> product;
private int quantity;
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public CartItem(List<Product> product, int quantity) {
super();
this.product = product;
this.quantity = quantity;
}
public CartItem() {
super();
}
}
this is my Product class
public class Product {
private int pid;
private String productName;
private int unitPrice;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
}
I've a productServiceImpl class of this productDaoImpl
#Override
public List<Product> findProductCart(int id) {
List<Product> cartProduct = new ArrayList<Product>();
String sql = "select * from product where pid= " + id;
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
cartProduct = jdbcTemplate.query(sql, new ProductRowMapper());
return cartProduct;
}
I've view in jsp with following code
<c:forEach var="item" items="${sessionScope.cart}">
<li>${item.quantity}</li>
<li>${item}</li>
</c:forEach>
this give
1
com.sparktronix.mvc.domain.CartItem#344e01
How to display session value productname and unitprice? Any suggestion are welcomed. Thanks in advance
You are almost there! You just have to get the product object from sessionScope and iterate once again like below.
<c:forEach var="item" items="${sessionScope.cart}">
<li>${item.quantity}</li>
<c:forEach items = "${item.product}" var="product">
<li>${product.productName}</li>
<li>${product.unitPrice}</li>
</c:forEach>
</c:forEach>
Hope this helps!

How to use #ModelAttribute annotation to pass an object to the database?

I am going to use #ModelAttribute instead of #RequestParam to bind the user input and write it to the database. I am just confused when the #ModelAttribute bind the data in my request handler method (#ModelAttribute book Book) as an book object then how should I pass this object to the database? Normally using #RequestParam I bind the user inputs variable by variable according to my model class and then I send them to the db using the related DAO method. I show my classes in below. Can anybody say how my request handler method should look like if I use #ModelAttribute?
Model Class:
#Component
public class Book {
int bookId;
String title;
Author author;
Publisher publisher;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
}
DAO:
public class BookDAO extends JdbcDaoSupport {
#Autowired
AuthorDAO authorDAO;
#Autowired
PublisherDAO publisherDAO;
public void addBook(String title, int authorId, int publisherId)
throws ClassNotFoundException, SQLException {
String sql = "insert into tbl_book (title, authId, pubId) values (?, ?, ?)";
this.getJdbcTemplate().update(sql, new Object[]{title, authorId, publisherId});
}
}
Service:
#Service
public class BookService {
#Autowired
BookDAO bookDAO;
public Book getBookById(int bookId) throws ClassNotFoundException,
SQLException {
return bookDAO.getBookById(bookId);
}
public List<Book> getAllBooks() throws ClassNotFoundException,
SQLException {
List<Book> bookList = bookDAO.getAllBooks();
return bookList;
}
public void addBook(String title, int authorId, int publisherId) throws ClassNotFoundException,
SQLException {
bookDAO.addBook(title, authorId, publisherId);
}
}
Controller:
#Controller
public class BookController {
#RequestMapping(value = "/addBookExecution", method = equestMethod.POST)
protected ModelAndView addBookExecution(#RequestParam String title,
#RequestParam int authorId, #RequestParam int blisherId)
throws ClassNotFoundException, SQLException {
bookService.addBook(title, authorId, publisherId);
ModelAndView model = new ModelAndView("adminFunctionsPage");
model.addObject("Msg", "Your request has been processed successfully.");
return model;
}
}
Your form should have parameters names as your book object, check below sample code
<form >
<input type="text" name="authorId"/>
<input type="text" name="authorName"/>
etc...
</form>
Book.java
class Book{
Integer authorId;
String authorName;
etc..
}
#RequestMapping(value = "/addBookExecution", method = equestMethod.POST)
protected ModelAndView addBookExecution(#ModelAttribute Book book)
throws ClassNotFoundException, SQLException {
bookService.addBook(book);
ModelAndView model = new ModelAndView("adminFunctionsPage");
model.addObject("Msg", "Your request has been processed successfully.");
return model;
}

Resources