Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to save collections into database using @ElementCollection, @JoinTable and @JoinColumn annotations in Hibernate Framework ?.

Program to demonstrate how to save collections into database using @ElementCollection, @JoinTable and @JoinColumn annotations in Hibernate Framework.

A simple POJO class (model) Customer.java

package com.hubberspot.hibernate.examples;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 // In order to save collections into database
 // using Hibernate we use an annotation called as
 // @ElementCollection which creates a seperate table
 // for storing the contents of multiple addresses 
 // and associate a foreign key relationship with
 // Customer table.
 @ElementCollection

 // In order to provide user friendly name to the
 // separate table we use @JoinTable annotation which
 // takes in name as the name user wants to provide to 
 // collections table. We can also provide name to foreign key
 // using @JoinColumn annotation
 @JoinTable(name="Customer_Address" , joinColumns=@JoinColumn(name="Customer_Id"))
 private Set< Address >setOfAddresses = new HashSet< Address >();

 public Set< Address >getSetOfAddresses() {
  return setOfAddresses;
 }

 public void setSetOfAddresses(Set< Address >setOfAddresses) {
  this.setOfAddresses = setOfAddresses;
 }
 public int getCustomerId() {
  return customerId;
 }
 public void setCustomerId(int customerId) {
  this.customerId = customerId;
 }

 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }
}




A simple POJO class (model) Address which is being used as a collection into Customer

package com.hubberspot.hibernate.examples;

import javax.persistence.Embeddable;

// @Embeddable tells Hibernate that Address object 
// will be embedded into some other tables.
// The values of the properties will be populated
// into a table in which we want to embed the Address
@Embeddable
public class Address {

 private String street;
 private String city;
 private String state;
 private String zipCode;

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

 public String getZipCode() {
  return zipCode;
 }

 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;
 } 

}




Hibernate Configuration XML file


<?xml version='1.0' encoding='utf-8'?>
<!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">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

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


A simple Test.java

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();
  customer.setCustomerId(1);
  customer.setCustomerName("Jonty");

  // Lets create multiple addresses object which will be
  // saved as a collections into a separate table
  Address address1 = new Address();
  address1.setStreet("Street Name 1");
  address1.setCity("City Name 1");
  address1.setState("State Name 1");
  address1.setZipCode("Zip-Code Value 1");

  Address address2 = new Address();
  address2.setStreet("Street Name 2");
  address2.setCity("City Name 2");
  address2.setState("State Name 2");
  address2.setZipCode("Zip-Code Value 2");

  customer.getSetOfAddresses().add(address1);
  customer.getSetOfAddresses().add(address2);

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();
 }
}




Output of the program : 

Two tables created into database as below: 




 Table 1: Customer












Table 2: Customer_Address


 




Video tutorial to demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.









How to implement @Embeddable and @Embedded annotation in Hibernate Framework ?.

Program to demonstrate how to implement @Embeddable and @Embedded annotation in Hibernate Framework.


A simple POJO class (model) Customer.java

package com.hubberspot.hibernate.examples;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 // @Embedded defines that customer address will be
 // embedded by an object called as Address
 // The value of Address will be provided by Address object
 // but in database the properties of Address will be embedded
 // into Customer table.
 @Embedded
 private Address customerAddress;


 public Address getCustomerAddress() {
  return customerAddress;
 }

 public void setCustomerAddress(Address customerAddress) {
  this.customerAddress = customerAddress;
 }
 public int getCustomerId() {
  return customerId;
 }
 public void setCustomerId(int customerId) {
  this.customerId = customerId;
 }

 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }
}




A simple POJO class (model) Address which is embedded into Customer

package com.hubberspot.hibernate.examples;

import javax.persistence.Embeddable;

// @Embeddable tells Hibernate that Address object 
// will be embedded into some other tables.
// The values of the properties will be populated
// into a table in which we want to embed the Address
@Embeddable
public class Address {

 private String street;
 private String city;
 private String state;
 private String zipCode;

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

 public String getZipCode() {
  return zipCode;
 }

 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;
 } 

}




Hibernate Configuration XML file


<?xml version='1.0' encoding='utf-8'?>
<!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">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

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


A simple Test.java
package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();
  customer.setCustomerId(1);
  customer.setCustomerName("Jonty");

  // Lets create a Address object which will be
  // embedded into Customer object
  Address address = new Address();
  address.setStreet("Street Name");
  address.setCity("City Name");
  address.setState("State Name");
  address.setZipCode("Zip-Code Value");

  customer.setCustomerAddress(address);

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();
 }
}



Output of the program : 





















 




Video tutorial to demonstrate how to implement Component Mapping by @Embedded annotation in Hibernate using JPA.








Video tutorial to demonstrate how to create Composite Primary Keys by @Embeddable annotation in Hibernate using JPA.










How to retrieve an object from database by primary key using Hibernate Framework ?.

Program to demonstrate how to retrieve an object from database by primary key using Hibernate Framework.

A simple POJO class (model) Customer.java, whose object we want to store and than retrieve back using primary key from database using Hibernate.

package com.hubberspot.hibernate.examples;

import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity 
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 public int getUserId() {
  return customerId;
 }
 public void setUserId(int userId) {
  this.customerId = userId;
 }

 public String getUserName() {
  return customerName;
 }
 public void setUserName(String userName) {
  this.customerName = userName;
 }
}




Hibernate Configuration XML file


<?xml version='1.0' encoding='utf-8'?>
<!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">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

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


A simple test class to save and than retrieve an object from database using the primary key.

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();

  customer.setUserId(1);
  customer.setUserName("Jonty");  

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();

  // Pointing the customer to null in order to  
  // demonstrate how to fetch / retrieve the object 
  customer = null;

  // again opening a session from SessionFactory
  session = sessionFactory.openSession();
  session.beginTransaction();

  // We use get method of the session for retrieving
  // the object from the database if we know the primary key
  // for which we want to retrieve. 
  // The get method takes in two arguments one is class object
  // for which we want to fetch record and second is the 
  // primary key.
  customer = (Customer) session.get(Customer.class, 1);
  
  // finally printing the retrieved customer name based on the 
  // primary key passed
  System.out.println("Customer Name retrived is : " + customer.getUserName());
 }
}



Output of the program : 


 

How to save an Object in database using Hibernate Framework through Annotations ?.

Program to demonstrate how to save an Object in database using Hibernate Framework through Annotations.

A simple POJO class (model) Customer.java, whose object we want to store in database using Hibernate.

package com.hubberspot.hibernate.examples;

import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity 
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 public int getUserId() {
  return customerId;
 }
 public void setUserId(int userId) {
  this.customerId = userId;
 }

 public String getUserName() {
  return customerName;
 }
 public void setUserName(String userName) {
  this.customerName = userName;
 }
}




Hibernate Configuration XML file


<?xml version='1.0' encoding='utf-8'?>
<!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">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

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

A simple test class to run and save object into database.

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();

  customer.setUserId(1);
  customer.setUserName("Jonty");  

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  session.getTransaction().commit();
  session.close();

 }
}




Output of the program :




How to demonstrate Polymorphism through a simple Java program ?.

Program to demonstrate how to implement Polymorphism in Java.

package com.hubberspot.examples;

class Shape {

 public void draw(){

  System.out.println("Shape drawn ... ");

 }

}

class Rectangle extends Shape {

 public void draw(){

  System.out.println("Rectangle drawn ... ");

 }
}

class Circle extends Shape {

 public void draw(){

  System.out.println("Circle drawn ... ");

 }

}

// Polymorphism implementing class 
// Performing decoupling as well
// Later in design if a new shape appears
// the functionality of the class has 
// decoupled the object creation hardcoding 
// to a polymorphic way using setShape() 
// and drawShape()
class Drawing {

 private Shape s;

 // Setting polymorphic behavior and 
 // this class doesnt care which shape
 // it is.
 public void setShape(Shape s) {

  this.s = s;

 }

 public void drawShape() {

  this.s.draw();

 }
}


public class Test {

 public static void main(String[] args) {

  Rectangle rectangle = new Rectangle();
  Circle circle = new Circle();

  Drawing drawing = new Drawing();

  drawing.setShape(rectangle);
  drawing.drawShape();

  drawing.setShape(circle);
  drawing.drawShape();

 }
}



Output of the program :



How to implement Comparable Interface in Java with an example ?

Program to demonstrate how to implement Comparable Interface in Java with an example.

package com.hubberspot.code;

import java.util.ArrayList;
import java.util.Collections;

public class Student implements Comparable {

 public String name;
 public double percentage;

 Student(String name, double percentage)
 {
  this.name = name; 
  this.percentage = percentage;
 }

 public String toString()
 {
  return "\nName = " + name + "\n"+
    "Percentage = " + percentage+"\n";
 }


 @Override
 public int compareTo(Object o) {
  Student other = (Student) o;

  Double percentage1 = (Double) this.percentage;
  Double percentage2 = (Double) other.percentage;

  return percentage1.compareTo(percentage2);

 }


 public static void main(String[] args) {

  ArrayList list = new ArrayList();

  list.add(new Student("Dinesh",76.2));
  list.add(new Student("Jonty",96.5));
  list.add(new Student("Gunjan",81.7));
  list.add(new Student("Parishrut",62.1));

  System.out.println("Before Sorting : \n" + list);

  Collections.sort(list);

  System.out.println("\nAfter Sorting : \n" + list);

 }
}



Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot