update table using spring mvc web and hibernate
I have simple spring mvc web application which can handle simple book store. I have a problem when the existing book is updating.
I want to up date title of a book. My updateBook.jsp is somethig like this.
<form method="post" action="">
Previous book title : <input type="text" name="previousTitle" /> <br>
New book title :<input type="text" name="newTitle"/><br>
<input t开发者_如何学Cype="submit" name="update" value="update"/>
</form>
Problem: I have java class,"UpdateBookController" for handle the update of book. How can I handle the previous and new book titles in "UpdateBookController" class.
any idea..?
Thank in advance!
Spring 3.0 way
@Controller
public class BookController {
@Autowired
private BookRepository<Book, Integer> bookRepository;
@RequestMapping(method=RequestMethod.POST)
public void updateTitle(@RequestParam("bookId") Integer bookId,
@RequestParam("previousTitle") String previousTitle,
@RequestParam("newTitle") String newTitle) {
Book book = bookRepository.findById(bookId);
book.setPreviousTitle(previousTitle);
book.setNewTitle(newTitle);
bookRepository.merge(book);
}
}
Where BookRepository can be written as
@Repository
public class BookRepository extends AbstractRepository<Book, Integer> {
@Autowired
private SessionFactory sessionFactory;
@Override
public void merge(Book book) {
sessionFactory.getCurrentSession().update(book);
}
}
If you want, you can create a custom UpdateTitleUseCase command class which encapsulates previousTitle and newTitle attributes. This way, your controller looks like
@RequestMapping(method=RequestMethod.POST)
public void updateTitle(UpdateTitleUseCase command) {
Book book = bookRepository.findById(command.getBookId());
book.setPreviousTitle(command.getPreviousTitle());
book.setNewTitle(command.getNewTitle());
bookRepository.merge(book);
}
How about something like this:
Session sess = null;
try {
SessionFactory fact = new Configuration().configure().buildSessionFactory();
sess = fact.openSession();
Transaction tr = sess.beginTransaction();
Book book = (Book)sess.get(Book.class, new Long(<id of the book to update>));
book.setTitle(<new title>);
sess.update(book);
tr.commit();
sess.close();
System.out.println("Update successfully!");
}
catch(Exception e){
System.out.println(e.getMessage());
}
However, you may want to use the DAO pattern to handle this in a neat way.
精彩评论