Monday, 27 April 2020

One to many


1. http://www.mkyong.com/hibernate/different-between-cascade-and-inverse/
2. http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/
3. http://www.mkyong.com/hibernate/inverse-true-example-and-explanation/
4.http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/
5. http://technicalmumbojumbo.wordpress.com/2007/08/18/investigating-hibernate-associations-one-to-many/



CREATE TABLE hibdept
(
id number primary key,
name varchar2(20)
);

create table hibemp
(
id number primary key,
name varchar2(30) ,
deptid number ,
constraint consthibemp FOREIGN KEY (deptid) REFERENCES hibdept(id)
)

create sequence hibdept_seq
create sequence hibemp_seq

1. Department.java


package dptemp;
import java.util.Set;

public class Department {
int id;
String name;
Set employees;


public Department() {
super();
}

public Department(String name) {
super();

this.name = name;
}
   getter/setter
}




2. Employee.java

package dptemp;

public class Employee {
int empid;
String empname;

Department department;



public Employee() {
super();
}


public Employee(String empname) {
super();
this.empname = empname;
}

getter / setter

}


3. department.hbm.xml


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping auto-import="false" package="dptemp">
   <class name="dptemp.Department" table="hibdept">
      <meta attribute="class-description">
         This class contains the department detail.
      </meta>
      <id name="id" type="int" column="id">
      <generator class="sequence">
                <param name="sequence">hibdept_seq</param>
            </generator>      
      </id>
      <set name="employees" cascade="all" inverse="true" lazy="true" fetch="select">
         <key column="deptid"/>
         <one-to-many class="dptemp.Employee"/>
      </set>
      <property name="name" column="name" type="string"/>
   
   </class>

   <class name="dptemp.Employee" table="hibemp">
      <meta attribute="class-description">
         This class contains the certificate records.
      </meta>
      <id name="empid" type="int" column="id">
         <generator class="sequence">
                <param name="sequence">hibemp_seq</param>
         </generator>
      </id>
      <property name="empname" column="name" type="string"/>
   
      <many-to-one name="department" class="dptemp.Department" fetch="select">
            <column name="deptid" not-null="true" />
      </many-to-one>
     
   </class>

</hibernate-mapping>


4. main


package dptemp;


import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import dptemp.Employee;
import dptemp.Department;

public class Main {

private static SessionFactory factory;

public static void main(String[] args) {
try{
        factory = new Configuration().configure().buildSessionFactory();
     }catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
     }
     Main ME = new Main();
   
     HashSet<Employee> employees1 = new HashSet<Employee>();
     Employee e1 = new Employee("A1");
     Employee e2 = new Employee("B1");
     Employee e3 = new Employee("C1");
     employees1.add(e1);
     employees1.add(e2);
     employees1.add(e3);
   
   
   
     int deptid1 = ME.addDepartmentEmployee("Department1", employees1);
     System.out.println("dept1 = "+ deptid1);
   
     HashSet<Employee> employees2 = new HashSet<Employee>();
     Employee e21 = new Employee("A2");
     Employee e22 = new Employee("B2");
     Employee e23 = new Employee("C2");
     employees2.add(e21);
     employees2.add(e22);
     employees2.add(e23);
   
     int deptid2 = ME.addDepartmentEmployee("Department2", employees2);      
     System.out.println("dept2 = "+ deptid2);
 
     ME.displayAll();
   


     Employee e22 = new Employee("D1");
     ME.addEmployee(45, e22);
     System.out.println("Record added");
     ME.displayAll();
   
     System.out.println("showing department no " + 48);
     ME.displayDepartmentName(48);
   
     System.out.println("showing department no " + 81);
     ME.displayDepartmentNameFromEmployeeid(81);

}


public int addDepartmentEmployee(String deptname , HashSet<Employee> employees){
Department department = new Department(deptname);

for(Iterator<Employee> it = employees.iterator();it.hasNext();)
{
Employee e = it.next();
e.setDepartment(department);
}

department.setEmployees(employees);
int departmentid =0;

Session session = factory.openSession();
     Transaction tx = null;
   
     try{
        tx = session.beginTransaction();      
        departmentid = (Integer) session.save(department);
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
     }finally {
        session.close();
     }
     return departmentid;

}

public void displayAll()
{
try{
Session session = factory.openSession();
List<Department> departments =(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Department> it =(Iterator<Department>) departments.iterator();
while(it.hasNext()){
Department dept = it.next();
System.out.println("\n\nDepartment id =" + dept.getId() + " Name = " + dept.getName());

Iterator iti = dept.getEmployees().iterator();
while(iti.hasNext()){
Employee emp = (Employee)iti.next();
System.out.println("     emp id =" + emp.getEmpid() + " Name = " + emp.getEmpname());
}
}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void displayDepartmentName(int deptid)
{
try{
Session session = factory.openSession();
Query q = session.createQuery("FROM dptemp.Department d where d.id = ?");
q.setInteger(0, deptid);


List<Department> departments = q.list();  //(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Department> it =(Iterator<Department>) departments.iterator();
while(it.hasNext()){
Department dept = it.next();
System.out.println("\n\nDepartment id =" + dept.getId() + " Name = " + dept.getName());

Iterator iti = dept.getEmployees().iterator();
while(iti.hasNext()){
Employee emp = (Employee)iti.next();
System.out.println("     emp id =" + emp.getEmpid() + " Name = " + emp.getEmpname());
}
}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void displayDepartmentNameFromEmployeeid(int empid)
{
try{
Session session = factory.openSession();
Query q = session.createQuery("FROM dptemp.Employee e where e.empid = ?");
q.setInteger(0, empid);


List<Employee> employees = q.list();  //(List<Department>) session.createQuery("FROM dptemp.Department").list();
Iterator<Employee> it =(Iterator<Employee>) employees.iterator();
while(it.hasNext()){
Employee emp = it.next();
System.out.println("\n\n Employee id =" + emp.getEmpid()+ " Name = " + emp.getEmpname());

Department d = emp.getDepartment();
System.out.println("\n\n its Department id =" + d.getId() + " Name = " + d.getName());

}
session.close();

}
catch(Exception e){
e.printStackTrace();
}
}

public void addEmployee(int deptid , Employee  employee){



Session session = factory.openSession();
     Transaction tx = null;
   
     try{
        tx = session.beginTransaction();
     
        Department d = (Department) session.load(Department.class, deptid);
        d.getEmployees().add(employee);
        session.saveOrUpdate(d);
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
     }finally {
        session.close();
     }
   

}





}




Friday, 21 December 2012

                                                        Hibernate Access field




By using access field , there is no need to create getter/setter methods in the POJO file.
There are three values for access attribute
(a) field
(b) property   (default)
(c) ClassName

However this attribute is optional but its default value is property.
It can be specified  at any of the following point
(a) Hibernate-mapping node of hbm file 
 or
(b) in each id and property node of class node in the hbm file.










But if we dont create getter/setter methods for attibute and we have also not given access attribute in hbm file and we have also mentioned its mapping in hbm file then hibernate will throw exception

org.hibernate.PropertyNotFoundException: Could not find a getter for firstName in class accesstest.Person





1. Create POJO File


package accesstest;

public class Person {
      private int id;
      String firstName;
      String lastName;
   
      /*
    public String getFirstName() {
        return firstName;
    }
   
    public String getLastName() {
        return lastName;
    }
   
   
     public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
     */

   
}






2. Create any of the following hbm files by name "Person.hbm.xml".


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 21, 2012 7:12:56 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="accesstest.Person" table="Person" >
        <id name="id" type="int" access="field">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="firstName" type="java.lang.String" access="field">
            <column name="FIRSTNAME" />
        </property>
        <property name="lastName" type="java.lang.String" access="field">
            <column name="LASTNAME" />
        </property>
    </class>
</hibernate-mapping> 

OR



<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 21, 2012 7:12:56 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping default-access="field">
    <class name="accesstest.Person" table="Person">
        <id name="id" type="int" >
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="firstName" type="java.lang.String" >
            <column name="FIRSTNAME" />
        </property>
        <property name="lastName" type="java.lang.String" >
            <column name="LASTNAME" />
        </property>
    </class>
</hibernate-mapping>






3.  Create main method


package accesstest;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;


public class Main {

   
    public static void main(String args[]){



        try
        {
        SessionFactory factory = new Configuration().configure("a.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();

        Transaction t = session.beginTransaction();
       

        Person p = new Person();
        p.firstName = "PRASHANT 3";
        p.lastName =" Lal 3";
      
         //p.setFirstName("prashant");
        //p.setLastName("lal");
       
       
       
       
        session.saveOrUpdate(p);
        session.flush();
        t.commit();


        session.close();
        }
        catch(Exception e)
        {
        e.printStackTrace();   
        }   
    }
}






4. Create hibernate configuration file

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.pool-size">10</property>
  <property name="show_sql">true</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
 
  <mapping resource="accesstest/Person.hbm.xml"/>
 
 </session-factory>
</hibernate-configuration>


5. Run the Main.java file


Hibernate Output


Dec 21, 2012 8:16:36 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : accesstest/P.hbm.xml
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: accesstest.P -> P
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Dec 21, 2012 8:16:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
Dec 21, 2012 8:16:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
Dec 21, 2012 8:16:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
Dec 21, 2012 8:16:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/test
Dec 21, 2012 8:16:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {pool-size=10, user=root, password=****}
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.5.22
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.0.15-ga ( $Date: 2004/08/09 22:15:11 $, $Revision: 1.27.2.43 $ )
Dec 21, 2012 8:16:36 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 21, 2012 8:16:36 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Dec 21, 2012 8:16:36 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Dec 21, 2012 8:16:36 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.classic.ClassicQueryTranslatorFactory
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Dec 21, 2012 8:16:37 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Dec 21, 2012 8:16:37 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Dec 21, 2012 8:16:37 PM org.hibernate.tuple.PojoInstantiator <init>
INFO: no default (no-argument) constructor for class: inheritancesub.PersonEmployee (class must be instantiated by Interceptor)
Dec 21, 2012 8:16:37 PM org.hibernate.tuple.PojoInstantiator <init>
INFO: no default (no-argument) constructor for class: inheritancesub.Person (class must be instantiated by Interceptor)
Dec 21, 2012 8:16:37 PM org.hibernate.tuple.PojoInstantiator <init>
INFO: no default (no-argument) constructor for class: inheritancesub.Personowner (class must be instantiated by Interceptor)
Dec 21, 2012 8:16:37 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Hibernate: select max(ID) from P
Hibernate: insert into P (FIRSTNAME, LASTNAME, ID) values (?, ?, ?)












Wednesday, 13 June 2012

Oracle Converting delimited string to column

WITH
test AS
( select
column_value AS c1
FROM
TABLE( SYS.DBMS_DEBUG_VC2COLL( 'CAT','DOG','MOUSE' , 'RAT' , 'BAT' , 'CAR' , 'DOOR' , 'LOCK') )
)
SELECT * FROM test ;




Output will like following

C1
CAT
DOG
MOUSE
RAT
BAT
CAR
DOOR
LOCK
Oracle getting nth string from comma separated string

For example getting 2nd string from 'CAT,DOG,MOUSE,RAT,BAT,CAR,DOOR,LOCK'  will be DOG

SELECT REGEXP_SUBSTR(MYCOL, '[^,]+', 1, 2) AS VAL
FROM
(
   SELECT 'CAT,DOG,MOUSE,RAT,BAT,CAR,DOOR,LOCK' AS MYCOL FROM DUAL
);
Oracle Comma to Row conversion

SELECT substr(str, instr(str, ',', 1, LEVEL) + 1, instr(str, ',', 1, LEVEL + 1) - instr(str, ',', 1, LEVEL) - 1) column_value
FROM   (SELECT ',' || 'first,second,third,fourth,fifth,sixth' || ',' str FROM dual)
CONNECT BY LEVEL <= length(str) - length(REPLACE(str, ',')) - 1;



Just replace your comma separated string 'first,second,third,fourth,fifth,sixth'  with your comma separated words.


You can also use the same query for retrieving the output , put the same query in the inner query and fetch the output

SELECT * FROM  mstlocations WHERE mstloc_pincode IN
 (
SELECT substr(str, instr(str, ',', 1, LEVEL) + 1, instr(str, ',', 1, LEVEL + 1) - instr(str, ',', 1, LEVEL) - 1) column_value
FROM   (SELECT ',' || '411038,411028' || ',' str FROM dual)
CONNECT BY LEVEL <= length(str) - length(REPLACE(str, ',')) - 1

);

The above query can be written by using LIKE operator but the performance will be little bit slow if records are huge.

Friday, 8 June 2012



 JAVA COLLECTION

The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays.

Most of the Java collections are located in the java.util package. Java also has a set of concurrent collections in the java.util.concurrent package

Java Collections

   
Java Collections Introduction


Overview of Interfaces


   

Iterable   

Collection

   

Generic Collections

   
   

List   
Set
SortedSet   

NavigableSet   

Map   

SortedMap

NavigableMap

   

Queue
   
Deque   

Stack

       

hashCode() and equals()

   

Sorting





















































Wednesday, 28 September 2011

Security Constraint


Security Constraints

The deployment descriptor, web.xml is the most important Java EE configuration piece of Java EE Web applications. The security configuration in this descriptor drives the semantics and operation of web container security. Hence it is very critical that web developers and administrators understand the various combinations possible in the security configuration in this descriptor.