samedi 28 février 2015

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;

}
}

Aucun commentaire:

Enregistrer un commentaire