Friday, March 13, 2020

Sample Spring-Hibernate-MySQL example for add, update, delete, list cards

Let's start with an example. Let's say we want to create page to add card to patients/students, update card details, delete a card and list all cards. In the following you can see the steps to do that.
  1. Create MySQL table for card
  2. Add a Hibernate Pojo/Model for Card
  3. Modify hibernate.cfg.xml to create a mapping of the POJO.
  4. Create CardDAO for the corresponding Card Pojo.
  5. Create Spring Controller
  6. Add CardDAO bean into root-context.xml
  7. Add the jsp files to add card to patients/students, update card details, delete a card and list all cards.
  8. Link the jsp with your existing webpage e.g. home page

Let us take a look at each step details.

Step 1

Create the table first. It can be skipped if you use below property in your hibernate.cfg.xml file.

<property name="hibernate.hbm2ddl.auto">update</property>

Step 2

Use below code snipped.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="card_table")
public class Card {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cardID", unique = true, nullable = false)
    private long id;
@Column(name="card_no")
private String cardNo;
@Column(name="card_name")
private String cardName;
@Column(name="group_capacity")
private Long groupCapacity;
@Column(name="validity_year")
private Long validityInYears;
@Column(name="amount")
private Long amount;
@Column(name="title")
    private String title;
@Column(name="message")
    private String message;
@Column(name = "price")
private Float price;
@Transient
private int postedBy;
public int getPostedBy() {
return postedBy;
}

public void setPostedBy(int postedBy) {
this.postedBy = postedBy;
}

public Card() {
}
public Card(String cardNo, String cardName, Long groupCapacity, Long validityInYears, Long amount,
String title, String message, Float price) {
super();
this.cardNo = cardNo;
this.cardName = cardName;
this.groupCapacity = groupCapacity;
this.validityInYears = validityInYears;
this.amount = amount;
this.title = title;
this.message = message;
this.price = price;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getCardNo() {
return cardNo;
}

public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}

public String getCardName() {
return cardName;
}

public void setCardName(String cardName) {
this.cardName = cardName;
}

public Long getGroupCapacity() {
return groupCapacity;
}

public void setGroupCapacity(Long groupCapacity) {
this.groupCapacity = groupCapacity;
}

public Long getValidityInYears() {
return validityInYears;
}

public void setValidityInYears(Long validityInYears) {
this.validityInYears = validityInYears;
}

public Long getAmount() {
return amount;
}

public void setAmount(Long amount) {
this.amount = amount;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Float getPrice() {
return price;
}

public void setPrice(Float price) {
this.price = price;
}
}

Step 3

Add below mapping class into hibernate.cfg.xml

<mapping class="com.my.spring.pojo.Card"/>

Step 4

Create CardDAO for the corresponding Card Pojo.

import java.util.Collections;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;

public class CardDAO extends DAO {

public Card create(Card card) {
try {
begin();            
getSession().save(card);     
commit();
return card;
catch (HibernateException e) {
return null;
finally {
rollback();
}
}

public Card update(Card card) {
try {
begin();
Card newCard = get(""+card.getId());//long to string
newCard.setTitle(card.getTitle());
newCard.setMessage(card.getMessage());
newCard.setPrice(card.getPrice());
getSession().saveOrUpdate(newCard);     
commit();
return newCard;
catch (HibernateException e) {
return null;
finally {
rollback();
}
}


public void delete(String cardId) {
try {
begin();
getSession().delete(get(cardId));
commit();
catch (HibernateException e) {

finally {
rollback();
}
}

public void delete(Card card) {
try {
begin();
getSession().delete(card);
commit();
catch (HibernateException e) {

finally {
rollback();
}
}

public List<Card> list() {

try {
begin();
Query q = getSession().createQuery("from Card");
List<Card> cards = q.list();
return cards;
catch (HibernateException e) {

}
return Collections.EMPTY_LIST;
}

public Card get(String id) {

try {
Query q = getSession().createQuery("from Card where id = :id");
q.setString("id"id);
Card card = (Card) q.uniqueResult();
return card;
catch (HibernateException e) {
}
return null;
}
}

Step 5

Create Spring Controller

@Controller
@RequestMapping("/card/*")
public class CardController {
@Autowired
@Qualifier("cardDao")
CardDAO cardDao;

                @RequestMapping(value = "/card/add", method = RequestMethod.POST)
public ModelAndView addCategory(@ModelAttribute("card") Card card, BindingResult resultthrows Exception {

Card persistentCard = cardDao.create(card);
return new ModelAndView("card-success""card"persistentCard);
}

@RequestMapping(value="/card/add", method = RequestMethod.GET)
public ModelAndView initializeForm(HttpServletRequest requestthrows Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("card"new Card());
mv.setViewName("card-form");
return mv;
}

@RequestMapping(value = "/card/list", method = RequestMethod.GET)
public ModelAndView addCategory(HttpServletRequest requestthrows Exception {

ModelAndView mav = new ModelAndView("card-list");
List<Card> cards = cardDao.list();
mav.addObject("cards"cards);
return mav;

}

@RequestMapping(value = "/card/update", method = RequestMethod.POST)
public ModelAndView updateCategory(@ModelAttribute("card") Card card, BindingResult resultthrows Exception {

Card persistentCard = cardDao.update(card);
return new ModelAndView("card-success""card"persistentCard);
}

@RequestMapping(value="/card/update", method = RequestMethod.GET)
public ModelAndView initializeUpdateForm(HttpServletRequest request@RequestParam("id") String idthrows Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("card"cardDao.get(id));
mv.setViewName("card-update-form");
return mv;
}

@RequestMapping(value="/card/delete", method = RequestMethod.POST)
public ModelAndView deleteCard(HttpServletRequest request@RequestParam("cardId") String cardIdthrows Exception {
cardDao.delete(cardId);
ModelAndView mav = new ModelAndView("card-list");
List<Card> cards = cardDao.list();
mav.addObject("cards"cards);
return mav;
}
}

Step 6

Add CardDAO bean into root-context.xml
<bean id="cartDao" class="com.my.spring.dao.CartDAO" ></bean>

Step 7

Add the jsp files to add card to patients/students, update card details, delete a card and list all cards.

Step 8

Link the jsp with your existing webpage e.g. home page

No comments:

Post a Comment