Skip to main content

Insert Data(without using service builder) in DB using Liferay + Hibernate

Pre-requisite for this example-:
Liferay 6.2.2GA3
Postgres 9.3
Hibernate JAR
GSON
JSON

Step 1-: Create Liferay MVC Portlet (See this)

Step 2-: Once you add a portlet on page view.jsp page will be called, now we will give link on our view.jsp but before that create a init.jsp in this jsp we will collect all needed Liferay Tag it will be in same package as of view.jsp(html/offer)

--init.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/security" prefix="liferay-security" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="liferay-aui"%>

<liferay-theme:defineObjects />
<portlet:defineObjects />

--copy this into view.jsp

<%@ include file="/html/init.jsp" %>

<portlet:actionURL var="redirectAddOfferURL" name="redirectAddOffer"></portlet:actionURL>

<a href ="<%= redirectAddOfferURL %>">Create Offer</a>

Step 3-: Create a model class and copy this code
This class is a POJO with basic hibernate annotation
Hibernate Annotation

@Entity
@Table(name = "Offer")
public class Offer implements Serializable {

    @Id
    @Column (name = "offerId" , nullable = true, length = 15)
    private int offerId;
   
    @Column (name = "offerCode" , nullable = false)
    private int offerCode;
   
    @Column (name = "offerTitle")
    private String title;
   
    @Column (name = "vendor")
    private String vendor;
    @Column (name = "aod")
    private String areaofDisplay;
    @Column (name = "description")
    private String desc;
    @Column (name = "terms")
    private String terms;
    @Column (name = "budget")
    private String budget;
    @Column (name = "budgetType")
    private String budgetType;
    @Column (name = "startDate")
    private String startDate;
    @Column (name = "endDate")
    private String endDate;
    @Column (name = "discount")
    private String discount;
    @Column (name = "disType")
    private String discountType;
    @Column (name = "offerLimit")
    private String limit;
    @Column (name = "upc")
    private String upc;
    public int getOfferId() {
        return offerId;
    }
    public void setOfferId(int offerId) {
        this.offerId = offerId;
    }
    public int getOfferCode() {
        return offerCode;
    }
    public void setOfferCode(int offerCode) {
        this.offerCode = offerCode;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getVendor() {
        return vendor;
    }
    public void setVendor(String vendor) {
        this.vendor = vendor;
    }
    public String getAreaofDisplay() {
        return areaofDisplay;
    }
    public void setAreaofDisplay(String areaofDisplay) {
        this.areaofDisplay = areaofDisplay;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public String getTerms() {
        return terms;
    }
    public void setTerms(String terms) {
        this.terms = terms;
    }
    public String getBudget() {
        return budget;
    }
    public void setBudget(String budget) {
        this.budget = budget;
    }
    public String getBudgetType() {
        return budgetType;
    }
    public void setBudgetType(String budgetType) {
        this.budgetType = budgetType;
    }
    public String getStartDate() {
        return startDate;
    }
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }
    public String getEndDate() {
        return endDate;
    }
    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }
    public String getDiscount() {
        return discount;
    }
    public void setDiscount(String discount) {
        this.discount = discount;
    }
    public String getDiscountType() {
        return discountType;
    }
    public void setDiscountType(String discountType) {
        this.discountType = discountType;
    }
    public String getLimit() {
        return limit;
    }
    public void setLimit(String limit) {
        this.limit = limit;
    }
    public String getUpc() {
        return upc;
    }
    public void setUpc(String upc) {
        this.upc = upc;
    }
    @Override
    public String toString() {
        return "Offer [offerId=" + offerId + ", offerCode=" + offerCode
                + ", title=" + title + ", vendor=" + vendor
                + ", areaofDisplay=" + areaofDisplay + ", desc=" + desc
                + ", terms=" + terms + ", budget=" + budget + ", budgetType="
                + budgetType + ", startDate=" + startDate + ", endDate="
                + endDate + ", discount=" + discount + ", discountType="
                + discountType + ", limit=" + limit + ", upc=" + upc + "]";
    }
   
   
}

Note-: We will be using DAO design pattern for this example
Step 4-: Create a OfferDAO

public interface OfferDAO {

    public int addOffer(final Offer offer);
   
}

Step 5-: Create OfferDAOFactory


public class OfferFactory{
    /**
     * This is factory implementation for OfferDAO.
     *
     * @return OfferDAO OfferDAO
     */
    public static OfferDAO create(){
        return (new OfferDAOImpl());
    }

}

Step 6-:  Create OfferDAOImpl

public class OfferDAOImpl implements OfferDAO {

    private static Log log = LogFactoryUtil.getLog(OfferDAOImpl.class);
    static private SessionFactory sessionFactory;
    private Session session;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
   
    static{
        sessionFactory = HibernateUtil.getSessionFactory();
    }
   
    @Override
    public int addOffer(Offer offer) {
   
        log.info("-----addOffer Called------");
        int offerId = 0;
       
     
        session = sessionFactory.openSession();
        session.beginTransaction();
       
        session.save(offer);
        session.getTransaction().commit();
        log.info("-----addOffer Comitted------");
        return offerId;
    }

}

Step 7-: Create HibernateUTIL Class

/**
 * This class provides hibernate utility.
 *
 * @author Vishal Srivastava
 */
public class HibernateUtil {

    private static Log log = LogFactoryUtil.getLog(HibernateUtil.class);
    private static final SessionFactory sessionFactory = buildSessionFactory();
   
    /**
     * This method builds sessionFactory for database connection.
     *
     * @return SessionFactory sessionFactory
     */
    private static SessionFactory buildSessionFactory(){
       
        try{
            log.info("--------Session Factory Build Session factory----");
            return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();   
        }catch(Throwable ex){
            log.info("Exception thrown while creating Session Factory---"+ex);
            throw new ExceptionInInitializerError(ex);
        }
       
    }
   
    /**
     * This method returns sessionFactory.
     *
     * @return SessionFactory sessionFactory
     */
    public static SessionFactory getSessionFactory() {
        //System.out.println("sessionFactory hashCode : "+sessionFactory.hashCode() +"sessionFactory toString : "+sessionFactory.toString());
        return sessionFactory;
    }
}

Step 8-: Create OfferServletContextListener it will create SessionFactory when context is loaded

public class OfferServletContextListener implements ServletContextListener {
   
    private static Log log = LogFactoryUtil.getLog(OfferServletContextListener.class);
   
    @Override
    public void contextInitialized(ServletContextEvent event){
        /*try{*/
        log.info("************ OfferServletContextListener : context-Initialized ************ ");
        HibernateUtil.getSessionFactory();
/*        }catch(Exception e){
            log.info("--------Exception in Listener---"+e);
        }*/
    }
   
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        log.info(" ************ OfferServletContextListener : context-Destroyed ************ ");  
    }

}

Step 9-:  Create hibernate.cfg.xml

<?xml version='1.0' ?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
    <session-factory>
   
       
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5432/pracLPortal</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- <property name="hbm2ddl.auto">validate</property> -->
        <!-- <property name="hbm2ddl.auto">create</property> -->
          <property name="hibernate.connection.autocommit">false</property>
          <mapping class="com.test.model.Offer"/>
         
         

    </session-factory>
</hibernate-configuration>


Step 10 -: Now we will create Controller class OfferPortlet which will have doView() and processAction method

In our Controller class we have a method redirectAddOffer you can see above in view.jsp on createOffer link we have given var-"redirectAddOfferURL" name ="redirectAddOffer" So once user click on this it will generate an action URL and call method redirectAddOffer in our controller.

In redirectAddOffer Action method on actionResponse.setrenderParamter we are setting attribute name and value name="custom-portlet" values="addNewOffer"

After this control passes in doView() Render method and there we will check custom-portlet attribute name and value and then we will forward this request to createOffer.jsp page
/**
 * This is Factory class for OfferDAOFactory.
 *
 * @author Vishal Srivastava
 */
public class OfferPortlet extends MVCPortlet {

    private static Log log = LogFactoryUtil.getLog(OfferPortlet.class);

public void doView(RenderRequest renderRequest,RenderResponse renderResponse)throws IOException,PortletException {

 ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
 PortletRequestDispatcher dispatcher = null;
  PortletSession session = renderRequest.getPortletSession();

//Here we will check if page name is addNewOffer then it will forward to createOffer //page
String portletTitle = renderRequest.getParameter("custom_portlet");
        if(portletTitle != null && portletTitle.equalsIgnoreCase("addNewOffer")){
            /*dispatcher = getPortletContext().getRequestDispatcher(OfferConstant.ADD_OFFER);*/
            dispatcher = getPortletContext().getRequestDispatcher("/html/offer/createOffer.jsp");
            /*dispatcher.include(renderRequest, renderResponse);*/
            dispatcher.forward(renderRequest, renderResponse);
        }
super.doView(renderRequest, renderResponse);
    }

    //These methods are just to redirect in doView and from there these gets the JSP page
    @ProcessAction(name="redirectAddOffer")
    public void redirectAddOffer(ActionRequest actionRequest, ActionResponse actionResponse){
           
        actionResponse.setRenderParameter("custom_portlet","addNewOffer");
    }
    @ProcessAction(name = "saveNewOffer")
    public int saveNewOffer(ActionRequest actionRequest,ActionResponse actionResponse){
    try{
        log.info("------Entered in Save New offer ----");
        int offerId = (int)CounterLocalServiceUtil.increment();
        String reponseData = actionRequest.getParameter("offerResponseJSON");
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(new StringReader(reponseData));       
       
        Offer offer = gson.fromJson(reader, Offer.class);
        offer.setOfferId(offerId);
       
        reader.setLenient(true);
        log.info("------Entered in Save New offer Offer DAO Called ----");
        OfferDAO offerDAO = OfferFactory.create();
       
        int returnOfferId = offerDAO.addOffer(offer);
       
        log.info("------Offer Id Reruned from DAO IMP ----"+returnOfferId);
    }catch(Exception e){
        log.info("Excetion occured in SaveNewOffer"+e);
    }
        return 145;
    }

}

Step 11-: Copy these content in language.properties file-:

offerTitle-required = Please enter Offer Title
upc-required = Enter UPC
offerCode-required = Enter offer Code

upc-required = Length must be less than 25
offerTitle-maxlength = Length must be less than 25
offerCode-maxlength = Length must be less than 25
vendor-maxlength = Length must be less than 25
areaofDisplay-maxlength = Length must be less than 25
desc-maxlength = Length must be less than 25
terms-maxlength = Length must be less than 25
budgetType-maxlength = Length must be less than 25
budget-maxlength = Length must be less than 25

Comments

  1. Thanks Vishal, Great efforts!!!
    Can you please share details about how to do the same thing using Serve Resource?

    ReplyDelete

Post a Comment

Popular posts from this blog

Liferay 7.1 Topics Coming Soon stay connected

1. Liferay 7.1 Service Builder 2. Rest Service and Liferay 3. Consuming SOAP service with Liferay 7.1 4. Creating Theme With Liferay 7.1 Using Liferay IDE Using NPM 5. Create Angular NPM Module 6. Web Content Management 7. OSGI Basic 8. Liferay 7.1 with more than 1 DB 9. A sample project 10. Liferay Dev Ops

How the portal page is loaded with respective portlets

How the portal page is loaded with respective portlets When a user requests a page with a URL, 1.    The browser sends the request to the Application Server (AS). 2.    Liferay gets the page name from the URL. 3.    It goes to the layout database table and finds the related        theme and page layout. 4.    Based on the page layout, Liferay finds the portlets added        into each area of the page layout. 5.    Liferay runs the portlet and adds the output in the        portlet.vm template. 6.    Liferay interprets the portlet.vm template and adds the output        in the page layout. 7.    Then Liferay interprets the page layout and adds the output in        the portal_normal.vm template. 8.    After that Liferay interprets the portal...

Liferay Custom Field and Custom Attribute (Using Liferay UI and Programatically)

Custom fields are a way to add attributes to many types of assets in the portal. Its basically help us to add additional fields to existed models or entities. Adding some more additional attributes to existed entities or models helps us so to meet our requirements. Liferay provide two way's to allow the creation of Custom Fields. 1. Using Liferay UI 2. Programatically Lets look these both topic one by one-: Suppose you have a scenario where its needed to add few fields in your User_ Table So its simple to add using Liferay UI just you need to follow these steps-: 1. Using Liferay UI-:   Goto-> Control-Panel -> Click on Custom Field A List will be displayed-: Now you can add your custom fields for any entity in the list. Click on User Entity and a page will be displayed like this-: Now add these value in respective fields-: KEY- myContactId Type- Select Integer After adding the custom field we can view, update from the Lifera...