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 + '}';
    }

}


 

Structure

  1. WAP to read Information about Student and Display it.
    (Information: Roll Number, Name, Age, Sex)
  2. WAP to read Information about an Employee and Display it.
    (Information: EmpNo, Name, Job, Sal)
  3. WAP to read Information about a Worker and Print Payment
    (Information: Name, Wages, WorkingDays)
  4. WAP to read information about 10 workers and print their Payment.
    Print Average Payment
    (Information: Name, Wages, WorkingDays)
  5. WAP to read co-ordinates of end point of a line and find its slope by using the structure
    struct Line{
    int x1, y1, x2, y2;
    }
  6. WAP to read information about student
    (Roll No. Name, Birth Date, Admission Date) by using following structure
    struct date {
    int D, M, Y;
    }
    struct Student {
    int RollNo;
    char name[20];
    struct date bdate;
    struct date admsndate;
    }

Arrays Programs (Multi Dimensional)

  1. WAP to read a matrix of size 3 X 5 and find their SUM
  2. WAP to read a matrix of size 3 X 5 and find sum of each ROW
  3. WAP to read a matrix of size 3 X 3 and check if it is NULL or NOT
  4. WAP to read a matrix of size 3 X 5 and count all EVEN and ODD numbers
  5. WAP to read matrix of size 3 X 3 and check if it is UNIT Matrix or NOT
  6. WAP to read 2 matrix of size 3 X 3 and find their Addition
  7. WAP to read 2 matrix of size 3 X 3 and find their Product
  8. WAP to read matrix of size 3 X 3 and find its Transpose
  9. WAP to read matrix of size 3 X 3 and find its Transpose without using second matrix
  10. WAP to read matrix of size 3 X 3 and find its Upper Triangular Matrix
  11. WAP to read matrix of size 3 X 3 and find its Lower Triangular Matrix
  12. WAP to read matrix of size 3 X 3 and check if sum of its diagonal is same or not
  13. WAP to read matrix of size 3 X 3 and check if sum of its middle row is same as sum of its middle column
  14. WAP to create TIC-TAC-TOE by showing number and take 9 inputs from 2 users.
    1 2 3
    4 5 6
    7 8 9

    X O X
    O X O
    O O X

    PLAYER 1 WIN
    O X O
    X O X
    O X O

    PLAYER 2 WIN

Arrays Programs (One Dimensional)

  1. WAP to read an array of 10 numbers and find their sum
  2. WAP to read temperature days of Week and find their Mean
  3. WAP to read an array of 10 numbers and find greatest of them
  4. WAP to read an array of 10 numbers and count all EVEN and ODD numbers
  5. WAP to rad an array of 10 numbers and find sum, mean, min, max
  6. WAP to read an array of 10 numbers and search a number in it
  7. WAP to read an array of 10 numbers and sort it in ascending order
  8. WAP to read an array of 10 numbers and sort it in descending order
  9. WAP to insert a number at given position in an array (optional)
  10. WAP to remove a number from given position from an array (optional)
  11. WAP to arrange all even numbers at top and all odd numbers at bottom of an array (optional)

FUNCTIONS

  1. WAF repeat to display a char specified no of times.
  2. WAF intrest to calculate simple intrest.
  3. WAF to return Volume of Sphere
  4. WAF to return mean of 3 numbers
  5. WAF to return greatest of 2 numbers
  6. WAF to return Factorial of given Number
  7. WAF to return Sum of Given Number.
  8. WAF to return Greatest of 3 numbers.
  9. WAF to print all numbers from 1 to given numbers
  10. WAF to repeat a given char given number of timest.
    e.g. repeat(‘#’, 25)
  11. Design a recursive function factorial to return factorial of given number.
  12. Design a recursive function intrest to return compound intrest.
  13. Design a recursive function SOD to return sum of digit of given number.
  14. WAF to return sum of number which is passed in a Array.
  15. WAF to return Mean of numbers which is passed in a Array.
  16. WAF to return Greatest number which is passed in a Array.

SWITCH Statement

  1. WAP to read a single digit number and print that number in words.
  2. WAP to read month in digits print it in words.
  3. WAP to read a single number and print all numbers from 1 to that number in words.
  4. WAP to read a color code (char value) and print appropriate color.
    (e.g. R – Red, G- Green, B-Blue and other char – Black)
  5. WAP to read 2 numbers and a Operator sign and perform the operation according to operator.
    (e.g.
    i/p:
    5
    7
    +

5+7=12
)

  • WAP to count total number of vowels in a string by using a switch statement
  • WAP to count total number of vowels of each type

Loops Programs

EXACT OUTPUT IS OPTIONAL FOR PYTHON AND JAVASCRIPT

  1. WAP to read a number and print all numbers from 1 to that number
    input: enter a number: 5
    output:
    1
    2
    3
    4
    5
  2. WAP to read number and print all even numbers from 1 to that number
    input: enter a number: 5
    output:
    2
    4
  3. WAP to print all number from 1 to 10 by using while, for and do -while loop.
  4. WAP to read a number and find sum of all numbers from 1 to that number
    input: enter a number: 5
    output: 1 + 2 + 3 + 4 + 5 = 15
  5. WAP to read a number and find factorial of that number
    input: enter a number: 5
    output: 1 * 2 * 3 * 4 * 5 = 120
  6. WAP to read a number and check if it is a prime number or not
    input: enter a number: 5
    output: 5 is a prime number
  7. WAP to print all prime number in range from 1 to 100
    output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  8. WAP to print first 10 fibonacci number
    output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
  9. WAP to print table of number in following format using 1 for loop
    input: enter a number: 5
    5 * 1 = 5 5 * 10 = 50
    5 * 2 = 10 5 * 9 = 45
    5 * 3 = 15 5 * 8 = 40
    5 * 4 = 20 5 * 7 = 35
    5 * 5 = 25 5 * 6 = 30
    5 * 6 = 30 5 * 5 = 25
    5 * 7 = 35 5 * 4 = 20 
    5 * 8 = 40 5 * 3 = 15
    5 * 9 = 45 5 * 2 = 10
    5 * 10 = 50 5 * 1 = 5
  10. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts
  11. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz

Programs on If Statement

  1. WAP to read a number and check if it is even or odd
    input:
    Enter a number: 5
    output: number 5 is odd
  2. WAP to read 2 numbers and check if their last digits are same or not
    input:
    Enter number 1: 55
    Enter number 2: 45
    output: Last digits of 55 and 45 are same
  3. WAP to read 3 angles and check if triangle can be formed or not
    input:
    Enter value for angle a: 50
    Enter value for angle b: 60
    Enter value for angle c: 70
    output: Triangle can be formed
  4. WAP to read 3 angles and check if it is and equilateral triangle or not
    input:
    Enter value for angle a: 60
    Enter value for angle b: 60
    Enter value for angle c: 60
    output: Triangle is equilateral triangle
  5. WAP to read marks for 5 subjects and check if student is passed or not
    input:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    output:
    Total Marks: 250
    Percentage: 50%
    Student is passed
  6. WAP to read 2 numbers and find the greatest of them
    input:
    Enter number 1: 50
    Enter number 2: 60
    output:
    60 is greater than 50
  7. WAP to read 3 numbers and find the greatest of them
    input:
    Enter number 1: 50
    Enter number 2: 60
    Enter number 2: 70
    output:
    70 is greater than 50 and 60
  8. WAP to read 3 digit number and check if the sum of cube of its digits is equal to that number or not
    input:
    Enter a 3 digit number: 153
    output:
    Success: Sum of cube of 153 is 153
  9. WAP to read 3 numbers and check their last digit is same or not
    input:
    Enter number 1: 50
    Enter number 2: 60
    Enter number 3: 70
    output:
    Last digits of 50, 60 and 70 are same
  10. WAP to read a number and check if it is palindrome number or not
    input:
    Enter a number: 121
    output:
    121 is palindrome number
  11. WAP to read marks of 5 subjects and print their total. Also print percentage and check if student is passed or not
    input:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    output:
    Total Marks: 250
    Percentage: 50%
    Student is passed
  12. WAP to read 3 angles and check if triangle can be formed or not. If triangle can be formed then check it it is equilateral, isosceles or right angled triangle
    input:
    Enter value for angle a: 45
    Enter value for angle b: 45
    Enter value for angle c: 90
    output:
    Triangle can be formed
    The triangle is right angled triangle
  13. WAP to read age and gender of person and check if person is Eligible for marriage or not
    if gender is male then Eligibility is 21 years
    if gender is female then Eligibility is 18 years
    input:
    Enter gender M or F: M
    Enter your age: 30
    output:
    30 ka ho gaya ab to shadi kar le
  14. WAP to read a year and check if it is Leap year or not
    input:
    Enter year: 2004
    output:
    Year 2004 is a leap year
  15. WAP to read a Salary of Employee and print commission according to following Criteria
    SAL               Commission
    <10000             10%
    10000-20000   12%
    >20000             15%
    input:
    Enter Salary: 10000
    output:
    Your commission is 1000 Rupees
  16. WAP to read percentage of student and print Division
    >=75 : 1st class with distinction
    60-75: 1st class
    50-60: 2nd class
    40-50: 3rd class
    <40: fail
    input:
    Enter marks for maths: 75
    Enter marks for science: 75
    Enter marks for history: 75
    Enter marks for english: 75
    Enter marks for marathi: 75
    output:
    Total Marks: 375
    Percentage: 75%
    Student passed with 1st class Distinction

Basic Programs

  1. WAP to read radius of circle and calculate Area and Circumference
    i/p:
    Enter radius: 5
    o/p:
    Area of circle is 31.5
    Circumference of circle is 78.5
  2. WAP to read 3 numbers and find their mean
    i/p:
    Enter number 1: 5
    Enter number 2: 6
    Enter number 3: 7
    o/p:
    Mean of 5, 6 and 7 is 6
  3. WAP to read 2 numbers and find Sum of their last digit
    i/p:
    Enter number 1: 52
    Enter number 2: 65
    o/p:
    2 + 5 = 7
  4. WAP to read 4 digit number and sum of its digits
    i/p: Enter a number: 1234
    o/p:
    1 + 2 + 3 + 4 = 10
  5. WAP to read radius of Sphere and find its Volume
    i/p:
    Enter radius: 5
    o/p:
    Volume of sphere having radius 5 is 523.6
  6. WAP to read 3 digit number and sum of its digit
    i/p:
    Enter a number: 123
    o/p:
    1 + 2 + 3 = 6
  7. WAP to read 4 digit number and find reverse of that number
    i/p:
    Enter a number: 1234
    o/p:
    Reverse of 1234 is 4321
  8. WAP to read temperature in degree Celsius and convert it into Fahrenheit
    i/p:
    Enter temperature in Celsius: 38
    o/p:
    Temperature in Fahrenheit is 100.4
  9. WAP to read value in inches and print it in feet and inches
    i/p:
    Enter length in inches: 20
    o/p:
    20 inches is equal to 1 foot and 8 inches
  10. WAP to read marks of 5 subjects and print total and percentage
    i/p:
    Enter marks for maths: 50
    Enter marks for science: 50
    Enter marks for history: 50
    Enter marks for english: 50
    Enter marks for marathi: 50
    o/p:
    Total Marks: 250
    Percentage: 50%
  11. WAP to read 2 numbers and exchange their values using third variable
    i/p:
    Enter value for x: 5
    Enter value for y: 6
    o/p:
    After swapping value of x is 6 and value of y is 5
  12. WAP to read 2 numbers and exchange their values without using third variable
    i/p:
    Enter value for x: 5
    Enter value for y: 6
    o/p:
    After swapping value of x is 6 and value of y is 5
  13. WAP to read Lenght, Breadth and Height and find its volume and surface area
    i/p:
    Enter length: 5
    Enter breadth: 6
    Enter height: 7
    o/p:
    Volume of box is 210
    Surface are of box is 214
Solutions

# WAP to read radius of circle and calculate Area and Circumference
radius = 5;
area = 3.14 * radius * radius;
print (area);
circumference = 2 * 3.14 * radius;
print (circumference);

# WAP to read marks of 5 subjects and print total and percentage
m = 50;
s = 50;
h = 50;
e = 50;
ma = 50;

total_m = m + s + h + e + ma;
print(total_m);

per = total_m/5;
print(per);

# WAP to read 2 numbers and exchange their values using third variable
x = 5;
y = 6;
z = 0;
z = y;
y = x;
x = z;
print(x,y);

# WAP to read 2 numbers and exchange their values without using third variable
x = 5;
y = 6;

print(x,y);
x = (x*y);
y = (x/y);
x = (x/y);

print(x,y);

# WAP to read Lenght, Breadth and Height and find its volume and surface area

l = 5;
b = 6;
h = 7;

vol = l * b * h;
print(vol);

sa = (2 * l * b) + (2 * l * h) + (2 * b * h);
print(sa);

#WAP to read 3 numbers and find their mean
x = 5;
y = 6;
z = 7;
mean = (x+y+z)/3;
print(mean);

# WAP to read 2 numbers and find Sum of their last digit
x = 52;
y = 65;
sum = x%10 + y%10
print(sum);
# WAP to read 4 digit number and sum of its digits

num = 1234;

n1 = num//1000;

n2 = (num//100) % 10;

n3 = (num//10) % 10;

n4 = num % 10;

total = n1 + n2 + n3 + n4;

print(total);

#WAP to read radius of Sphere and find its Volume
radius = 5;
vol = (4/3) * 3.14 * radius * radius * radius;
print(vol);

# WAP to read 3 digit number and sum of its digit
num = 123;

n1 = num//100;

n2 = (num//10) % 10;

n3 = num % 10;

total = n1 + n2 + n3;

print(total);

# WAP to read 4 digit number and find reverse of that number
num = 1234;

n1 = num//1000;

n2 = (num//100) % 10;

n3 = ( num//10) % 10;

n4 = num % 10;

rev = n4 * 1000 + n3 * 100 + n2 * 10 + n1;

print(rev);

#WAP to read temperature in degree Celsius and convert it into Fahrenheit
c = 38;
F = (38*9/5)+32;
print(F);

#WAP to read value in inches and print it in feet and inches
li = 20;
ft = 20%12;
print(ft);

Escape Sequences and Formatted I/O Functions

Escape sequences

The following escape sequences allow special characters to be put into the source code.

Escape
Sequence
Name Meaning
\a Alert Produces an audible or visible alert.
\b Backspace Moves the cursor back one position (non-destructive).
\f Form Feed Moves the cursor to the first position of the next page.
\n New Line Moves the cursor to the first position of the next line.
\r Carriage Return Moves the cursor to the first position of the current line.
\t Horizontal Tab Moves the cursor to the next horizontal tabular position.
\v Vertial Tab Moves the cursor to the next vertical tabular position.
\’ Produces a single quote.
\” Produces a double quote.
\? Produces a question mark.
\\ Produces a single backslash.
\0 Produces a null character.
\ddd Defines one character by the octal digits (base-8 number)
\xdd Defines one character by the hexadecimal digit.

Examples:

p rintf(“\12”); – Produces the decimal character 10 (x0A Hex).

printf(“\xFF”); – Produces the decimal character – 1 or 255

printf(“\x123”); – Produces a single character

 

Formatted I/O Functions

printf Functions

int printf(const char * format,…);

int sprint(char *str, const char * format, …);

The printf functions provide a means to output formatted information to a stream.

printf sends formatted output to stdout

sprintf sends formatted output to a string

These functions take the format string specified by the format argument and apply each following argument to the format specifiers in the string in a left to right fashion. Each character in the format string is copied to the stream except for conversion characters which specify a format specifier.

 

A conversion specifier begins with the % character. After the % character come the following in this order:

[flags]                   Control the conversion (optional).

[width]                 Defines the number of characters to print (optional).

[.precision]        Defines the amount of precision to print for a number type (optional).

[modifier]           Overrides the size (type) of the argument (optional).

[type]                   The type of conversion to be applied (required).

 

Width:

The width of the field is specified here with a decimal value. If the value is not large enough to fill the width, then the rest of the field is padded with spaces. If the value overflows the width of the field, then the field is expanded to fit the value.

 

Precision:

The precision begins with a dob (.) to distinguish itself from the width specifier. The precision can be given as a decimal value or as an asterisk (*). If a * is used, then the next argument (which is an int type) specifies the precision.

 

scanf Functions

Declarations:

int scanf(const char * format, …);

int sscanf(const char * str, const char * format, …);

The scanf functions provide a means to input formatted information from a stream.

scanf reads formatted input from stdin

sscanf reads formatted input from a string

These functions take input in a manner that is specified by the format argument and store each input field into the following arguments in a left to right fashion. Each input field is specified in the format string with a conversion specifier which specifies how the input is to be stored in appropriate variable.

Char I/O

getchar : getchar reads a single character from standard input.

Syntax :                int getchar();

It requires the user to press enter after entering character.

Putchar : putchar writes a single character to standard output.

Syntax:                 int putchar(int value)