Monday, 18 November 2013

Example of composite primary key in hibernate?
Composite primary keys means having more than one primary key, let us see few points on this concept
  • If the table has a primary key then in the hibernate mapping file we need to configure that column by using <id /> element right..!
  • Even though the database table doesn’t have any primary key, we must configure one column as id (one primary key is must)
  • If the database table has more than one column as primary key then we call it as composite primary key, so if the table has multiple primary key columns , in order to configure these primary key columns in the hibernate mapping file we need to use one new element called <composite-id …..> </composite-id>
  • Files required….
  • Product.java (Pojo)
  • ForOurLogic.java (for our logic)
  • hibernate.cfg.xml
  • Product.hbm.xml
  •  
  • public class Product implements java.io.Serializable{
     
        private static final long serialVersionUID = 1L;
     
        private int productId;
        private String proName;
        private double price;
     
        public void setProductId(int productId)
        {
            this.productId = productId;
        }
        public int getProductId()
        {
            return productId;
        }
     
        public void setProName(String proName)
        {
            this.proName = proName;
        }
        public String getProName()
        {
            return proName;
        }
     
        public void setPrice(double price)
        {
            this.price = price;
        }
        public double getPrice()
        {
            return price;
        }
    }

    hibernate.cfg.xml


    Product.hbm.xml


    ForOurLogic.java

    Eclipse output

    In the database

    Notes:
  • see Product.java pojo class, in line number 3 i have implemented the java.io.Serializable interface,  this is the first time am writing this implementation for the pojo class right…!  we will see the reason why we use this serializable interface later.
  • But remember, if we want to use the composite primary keys we must implement our pojo class with Serializable interface
  • hibernate.cfg.xml is normal as previous programs, something like hello world program
  • come to Product.hbm.xml, see line number 9-12, this time we are using one new element<composite-id>
  • Actually if we have a single primary key, we need to use <id> element, but this time we have multiple primary keys, so we need to use this new element <composite-id>
  • Actually we will see the exact concept of this composite primary keys in the next example (loading an object with composite key)
  •  

No comments:

Post a Comment