Hibernate Native SQL

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package corehibernatedemo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import model.Person;
import model.Student;
import model.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Shailesh Sonare
 */
public class CoreHibernateDemo {
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException {
        // TODO code application logic here
        /*
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        
        SessionFactory factory = cfg.buildSessionFactory(ssrb.build());
        
        Session session = factory.openSession();
        
        Transaction t = session.beginTransaction();
        
        List users = session.createQuery("from Users").list();
        System.out.println("done...");
        
        for (Iterator iterator = users.iterator(); iterator.hasNext();) {
            Users e = (Users) iterator.next();
            System.out.println(e.getFirstName());
        }
        
        
        
        Date bdate = new SimpleDateFormat("yyyy-MM-dd").parse("1992-11-15");
        
        Users  usr = new Users("Sunita", "Sonare", bdate);
        
        String hql = "UPDATE Users SET dob = :dob WHERE id = :id";
        
        Query query = session.createQuery(hql);
        query.setParameter("dob", bdate);
        query.setParameter("id", 4);
        query.executeUpdate();
        
        //session.save(usr);
        t.commit();
        session.close();
        System.out.println("DOne....");
        */
        
        //Student s = new Student();
        
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        
        SessionFactory factory = cfg.buildSessionFactory(ssrb.build());
        
        Session session = factory.openSession();
        
//        String hql = "FROM Users";
//        List<Users> list = session.createQuery(hql).list();

        String sql = "SELECT first_name, last_name, dob FROM users";
        
        SQLQuery query = session.createSQLQuery(sql);
        query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); // important when you are using alias <key><value> pair
//        List<Object[]> rows = query.list();
//        
//        for(Object[] row : rows){
//            
//            Users u = new Users(row[0].toString(), row[1].toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(row[2].toString()));
//            System.out.println(u);
//            System.out.println("--------------");
//        }

        List list = query.list();
        
        for(Object obj : list){
            Map map = (Map)obj;
            System.out.println("" + map.get("first_name"));
            System.out.println("" + map.get("last_name"));
            System.out.println("" + map.get("dob"));
            System.out.println("-------------------------");
        }
    }
    
}

 

 

Users.java

package model;
// Generated 30 May, 2017 5:20:27 PM by Hibernate Tools 4.3.1


import java.util.Date;

/**
 * Users generated by hbm2java
 */
public class Users  implements java.io.Serializable {


     private Integer id;
     private String firstName;
     private String lastName;
     private Date dob;

    public Users() {
    }

    public Users(String firstName, String lastName, Date dob) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.dob = dob;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return this.firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return this.lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return this.dob;
    }
    
    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + '}';
    }

}


 

Sorting User Defined Collection Using Comparator

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", age=" + age + '}';
    }
}

 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;


/**
 *
 * @author Shailesh Sonare
 */
public class MyCollections {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(0, 5);
        list.add(1, 2);
        list.add(2, 3);
        list.add(3, 8);
        
        Collections.sort(list, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }            
        });
        
        for(Iterator i = list.iterator(); i.hasNext();) {
            System.out.println("" + i.next());
        }
        
        
        Hashtable ht = new Hashtable();
        ht.put(0, "Shailesh Sonare");
        
        HashMap hm = new HashMap();
        hm.put(0, "Mahesh Sonare");
        
        ArrayList<Student> sl = new ArrayList<Student>();
        
        sl.add(new Student("Shailesh", 28));
        sl.add(new Student("Mahesh", 20));
        sl.add(new Student("Shilpa", 22));
        
        Collections.sort(sl, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.age > o2.age) {
                    return 1;
                } else if(o1.age < o2.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        
        for(Iterator i = sl.iterator(); i.hasNext();) {
            System.out.println((Student)i.next());
        }
        
    }
    
}

 

equals and hashcode

equals() method

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

hashCode() method

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

__________________________

A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.
Imagine the following simple example:
On the table in front of you you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.
What you need is a way of instantly deciding which box you have put each object in. It works like an index; you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.
Now imagine that you don’t want to bother with the index, you want to be able to find out immediately from the object which box it lives in.
In the example, let’s use a really simple way of doing this – the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we’ll change our algorithm a little and “wrap round” so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.
Sometimes a box will have more than one object in it, but if you are looking for a rocket, it’s still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas , banjos and rhinoceroses.
That’s a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for generating its own. Lookup the “hashCode” method of Object.

Filters

<DOCTYPE html>
    <html>
        <head>
            <meta CHARSET="UTF-8">
            <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        </head>
        <body ng-app="myApp" ng-controller="myCtrl">
            <h2>Filters (uppercase, lowercase, currency, filter, Custom filter)</h2>
            <fieldset>
                <legend>
                    Uppercase
                </legend>
                <div ng-init='name = {"first_name":"Shailesh"}'>
                    {{name.first_name| uppercase}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Lowercase
                </legend>
                <div ng-init='month = {"first":"january"}'>
                    {{month.first| lowercase}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Currency
                </legend>
                <div ng-init='currency = {"inr": 20000, "usd":30000, "euro": 25000}'>
                    <!-- {{ currency_expression | currency : symbol : fractionSize}} -->
                    {{currency.inr| currency : ' &#8377;' : 3}} <br/>
                    {{currency.usd| currency}} <br/>
                    {{currency.euro| currency : '&euro;'}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Single Filter
                </legend>
                <div ng-init='city = ["Mumbai", "Pune", "Nagpur"]'>
                    <table border="1">
                        <ul>
                            <li ng-repeat="x in city">
                                {{x}}
                            </li>
                        </ul>
                    </table>
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Multiple Filter
                </legend>
                <div>
                    Search by any <input type="text" name="" ng-model="search.$"/> <br/>
                    Search by Name <input type="text" name="" ng-model="search.name"/> <br/>
                    Search Country <input type="text" name="" ng-model="search.country"/> <br/>
                    <table border="1">
                        <tr ng-repeat="x in emp_records| filter:search">
                            <td>{{x.name}}</td>
                            <td>{{x.country}}</td>
                            <td>{{x.age}}</td>
                        </tr>
                    </table>
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Multiple Filter Skip Few
                </legend>
                <div>
                    Search by Name or Country Only <input type="text" name="" ng-model="query"/> <br/>
                    <table border="1">
                        <tr ng-repeat="x in emp_records| filter:search2">
                            <td>{{x.name}}</td>
                            <td>{{x.country}}</td>
                            <td>{{x.age}}</td>
                        </tr>
                    </table>
                </div>
            </fieldset>
        </body>
        <script>
            var app = angular.module("myApp", []);
            app.controller("myCtrl", function ($scope) {
                $scope.emp_records = [
                    {name: 'Jani', country: 'Norway', 'age': 20},
                    {name: 'Carl', country: 'Sweden', 'age': 21},
                    {name: 'Margareth', country: 'England', 'age': 22},
                    {name: 'Hege', country: 'Norway', 'age': 23},
                    {name: 'Joe', country: 'Denmark', 'age': 24},
                    {name: 'Gustav', country: 'Sweden', 'age': 25},
                    {name: 'Birgit', country: 'Denmark', 'age': 26},
                    {name: 'Mary', country: 'England', 'age': 27},
                    {name: 'Kai', country: 'Norway', 'age': 28}
                ];

                $scope.search2 = function (row) {
                    return (angular.lowercase(row.name).indexOf(angular.lowercase($scope.query) || '') !== -1 ||
                            angular.lowercase(row.country).indexOf(angular.lowercase($scope.query) || '') !== -1);
                };
            });

        </script>
    </html>

 

ng-repeat

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h2>ng-repeat</h2>
        <fieldset>
            <legend>
                List
            </legend>
            <div ng-init='name = ["Shailesh", "Mahesh", "Shilpa"]'>
                <ul>
                    <li ng-repeat="x in name">{{x}}</li>
                </ul>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Table
            </legend>
            <div ng-init='months = ["Jan", "Feb", "Mar"]'>
                <table border="1">
                    <tr ng-repeat="x in months">
                        <td>{{x}}</td>
                    </tr>
                </table>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Select
            </legend>
            <div ng-init='cities = [{"id":"1", "value":"Mumbai"}, {"id":"2", "value":"Pune"}, {"id":"3", "value":"Nagpur"}]'>
                <select>
                    <option ng-repeat="x in cities" value="{{x.id}}">{{x.value}}</option>
                </select>
            </div>
        </fieldset>
    </body>
    <script>
                var app = angular.module("myApp", []);
                app.controller("myCtrl", function($scope) {

                });
    </script>
</html>

 

 

Working with JSON

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h2>JSON</h2>
        <fieldset>
            <legend>
                String
            </legend>
            <div ng-init='name = {"first_name":"Shailesh", "last_name" : "Sonare"}'>
                {{name.first_name}} <br/>
                {{name.last_name}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Numbers
            </legend>
            <div ng-init='months = {"jan": 1, "feb" : 2}'>
                {{months.jan}} <br/>
                {{months.feb}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Objecs
            </legend>
            <div ng-init='result = {employee:{"name": "Shailesh", "age" : 28}}'>
                {{result.employee.name}} <br/>
                {{result.employee.age}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Array
            </legend>
            <div ng-init='result = {employee:[{"name": "Shailesh", "age" : 28},{"name": "Mahesh", "age" : 26}]}'>
                {{result.employee[0].name}} <br/>
                {{result.employee[1].age}}
            </div>
            <div ng-init='result2 = {months:["Jan","Feb"]}'>
                {{result2.months[0]}} <br/>
                {{result2.months[1]}}
            </div>
        </fieldset>
    </body>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope) {

        });
    </script>
</html>

 

 

Routing without hashtag

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <base href="/">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    </head>
    <body ng-app="myApp">
        <aside>
            <a href="testlab/angular/sample/26_routing_without_hashing.html">Home</a>
            <a href="red">Red</a>
            <a href="green">Green</a>
            <a href="blue">Blue</a>
            <a href="default">Default</a>
        </aside>
        <section ng-view></section>
    </body>
    <script>
        var app = angular.module("myApp", ["ngRoute"]);
        app.config(function ($routeProvider, $locationProvider) {
            $routeProvider
                    .when("/red", {
                        template: "<h2 style='color:red;'>Red Color</h2>"
                                /*
                                 templateUrl : "red.html",
                                 controller : "myCtrl"
                                 */
                    })
                    .when("/green", {
                        template: "<h2 style='color:green;'>Green Color</h2>"
                    })
                    .when("/blue", {
                        template: "<h2 style='color:blue;'>Blue Color</h2>"
                    })
                    .otherwise({
                        template: "<h2>Default Black Color</h2>"
                    });

            $locationProvider.html5Mode(true);
        });
    </script>
</html>

 

 

Routing

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    </head>
    <body ng-app="myApp">
        <aside>
            <a href="#red">Red</a>
            <a href="#green">Green</a>
            <a href="#blue">Blue</a>
            <a href="#default">Default</a>
        </aside>
        <section ng-view></section>
    </body>
    <script>
        var app = angular.module("myApp", ["ngRoute"]); // where ngRoute is a dependent module
        app.config(function ($routeProvider) {
            $routeProvider
                    .when("/red", {
                        template: "<h2 style='color:red;'>Red Color</h2>"
                    })
                    .when("/green", {
                        template: "<h2 style='color:green;'>Green Color</h2>"
                    })
                    .when("/blue", {
                        template: "<h2 style='color:blue;'>Blue Color</h2>"
                    })
                    .otherwise({
                        template: "<h2>Default Black Color</h2>"
                    });
        });
    </script>
</html>