Thursday, September 29, 2016

The type oracle.jdbc.driver.OracleResultSet is not visible



 In this post you can resolve the issue "The type oracle.jdbc.driver.OracleResultSet is not visible"
 
Problem
 
 I was working on migrating a project. I experienced an issue with OracleResultSet class. The issue was "Type oracle.jdbc.driver.OracleResultSet is not visible .
 
When i checked the ojdbc6.jar(replacement for ojdbc14) oracle.jdbc.driver.OracleResultSet class is there.
Solution
I have found OracleTypes class in 3 different locations in ojdbc6.jar, they are
  • oracle.jdbc.OracleResultSet
  • oracle.jdbc.driver.OracleResultSet
  • oracle.jdbc.internal.OracleResultSet

 After doing hours of research, I was decided to use  oracle.jdbc.OracleResultSet  (instead of oracle.jdbc.driver.OracleResultSet).

 Changing to oracle.jdbc.OracleResultSet from oracle.jdbc.driver.OracleResultSet, the application work well.


Tuesday, September 20, 2016

Get Count of saturdays and sundays between two dates ?


 

Summary


 In this post, you can learn how to get count of number of Saturdays and sundays in given date range using Oracle and PLSQL.

 Sometimes you want to return the number of week days between two dates (i.e., the number of days excluding the weekend).

 The general strategy is to construct an expression that does the following:

  • Take two dates that you want to get days in between and loop date range.
  • In loop, get day from date.
  • If day is Saturday (6) and Sunday (7) as per Julian Calendar then 1 and take weekend day count otherwise 0 and take weekday day count

 

Using PLSQL


DECLARE

    weekday_CNT        NUMBER := 0;
    weekend_CNT        NUMBER := 0;
    v_date             DATE;
    date_20160716      DATE;
    date_20160817      DATE;
    v_day_of_week      VARCHAR(1);
    v_dayFlg           CHAR(1);
    
BEGIN
  -- Date From 20160716  
  date_20160716 := TO_DATE('2016-07-16', 'YYYY-MM-DD');
  -- Date To 20160817  
  date_20160817 := TO_DATE('2016-08-17', 'YYYY-MM-DD');

  --(From 20160716 To 20160817)loop 
  FOR vTempdate IN TO_NUMBER(TO_CHAR(date_20160716, 'J')) ..
                   TO_NUMBER(TO_CHAR(date_20160817, 'J'))

  LOOP
     v_date := TO_DATE(vTempdate, 'J');
     -- Get day from date
     select TO_CHAR(TO_DATE(v_date, 'YYYY-MM-DD'), 'D') into v_day_of_week from dual;

   -- v_day_of_week is Saturday(6) or sunday(7) as per Julian calendar then dayflg is 1, otherwise 0
     IF v_day_of_week in ('6', '7' ) THEN
        v_dayFlg := '1';
        weekend_CNT := weekend_CNT + 1;
     ELSE
        v_dayFlg := '0';
        weekday_CNT := weekday_CNT + 1;
     END IF;
     
  END LOOP;

  DBMS_OUTPUT.PUT_LINE('weekday_CNT: ' || weekday_CNT);
  DBMS_OUTPUT.PUT_LINE('weekend_CNT: ' || weekend_CNT);

  COMMIT;

END;
/

weekday_CNT: 23
weekend_CNT: 10

PL/SQL procedure successfully completed.

 Why Julian dates actually work is because Julian dates are basically a count of days since a fixed, known point in time you can use basic maths to determine whether or not it was a weekend or not, because you already know what day of the week day 1 was. Since other calendars have varying month lengths, year lengths, leap days and leap years, it is more difficult to derive information about the day of the week for other calendars, given a single date to work with.

Finding day of week given Julian day number


The US day of the week W1 can be determined from the Julian Day Number J with the expression:

W1 = mod(J + 1, 7)[29]
W10123456
Day of the weekSunMonTueWedThuFriSat

The ISO day of the week W0 can be determined from the Julian Day Number J with the expression:

W0 = mod (J, 7) + 1
W01234567
Day of the weekMonTueWedThuFriSatSun

Reference found here.

Using Oracle


SELECT TO_DATE('2016-07-15', 'YYYY-MM-DD') AS START_DATE, 
       TO_DATE('2016-08-17', 'YYYY-MM-DD') AS END_DATE, 
       COUNT(*) saturdays_and_sundays 
FROM dual 
WHERE TO_CHAR(TO_DATE('2016-07-15', 'YYYY-MM-DD') + LEVEL, 'D') IN ('1','7')
CONNECT BY LEVEL <= TO_DATE('2016-08-17','YYYY-MM-DD') - TO_DATE('2016-07-15','YYYY-MM-DD')

Output

START_DATEEND_DATESATURDAYS_AND_SUNDAYS
2016/07/152016/08/1710

Finally you created function to get count of Saturdays and Sundays in given date range.

 

Friday, September 16, 2016

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread


Problem

In this post you will learn how to resolve Could not obtain transaction-synchronized Session for current thread.

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
 at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:132)
 at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:692)
 at org.springframework.orm.hibernate5.support.HibernateDaoSupport.currentSession(HibernateDaoSupport.java:129)
 at nia.common.dao.AtLiabilityRrtkbnMasterDaoImpl.findAtLiRrtkbnMstAll(AtLiabilityRrtkbnMasterDaoImpl.java:58)
 at nia.common.util.AtLiabilityRrtkbnUtil.findAtLiRrtkbnMstAll(AtLiabilityRrtkbnUtil.java:141)
 at nia.common.util.AtLiabilityRrtkbnUtil.(AtLiabilityRrtkbnUtil.java:32)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
 at java.lang.reflect.Constructor.newInstance(Unknown Source)
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
 at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:267)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
 at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
 at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
 at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
 at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
 at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
 at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4812)
 at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
 at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
 at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
 at java.util.concurrent.FutureTask.run(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)

Solution

You must enable the transaction support (tx:annotation-driven or @EnableTransactionManagement) and declare the transactionManager and it should work through the SessionFactory.
You must add @Transactional into your @RepositoryWith @Transactional in your @Repository Spring is able to apply transactional support into your repository.
See this link:

Thursday, September 8, 2016

PL/SQL - Variables



Summary:

 
 In this tutorial, you will learn about PL/SQL variables that help you manipulate data in PL/SQL programs.
 
 In PL/SQL, a variable is a meaningful name of a temporary storage location that supports a particular data type in a program. Before using a variable, you need to declare it first in the declaration section of a PL/SQL block.

PL/SQL variables naming rules


 Like other programming languages, a variable in PL/SQL must follow the naming rules as follows:

 The variable name must be less than 31 characters. Try to make it as meaningful as possible within 31 characters.

 The variable name must begin with an ASCII letter. It can be either lowercase or uppercase. Notice that PL/SQL is case-insensitive, which means  v_data  and  V_DATA  refer to the same variable.

 Followed by the first character are any number, underscore (), and dollar sign () characters. Once again, do not make your variables hard to read and difficult to understand.

PL/SQL variables naming convention


It is highly recommended that you should follow the naming conventions listed in the following table to make the variables obvious in PL/SQL programs:

PREFIX DATA TYPE
v_ VARCHAR2
n_ NUMBER
t_ TABLE
r_ ROW
d_ DATE
b_ BOOLEAN

Each organization has its own development naming convention guidelines. Make sure that you comply with your organization’s naming convention guidelines.

For example, if you want to declare a variable that holds the first name of employee with the 'VARCHAR2' data type, the variable name should be 'v_first_name'.

PL/SQL Variables Declaration


PL/SQL variables must be declared in the declaration section or in a package as a global variable. To declare a variable, you use a variable name followed by the data type and terminated by a semicolon (';'). You can also explicitly add a length constraint to the data type within parentheses.

The syntax for declaring a variable is:

variable_name [CONSTANT] datatype [NOT NULL] [:= |DEFAULT initial_value]

Where,
  • variable_name is a valid identifier in PL/SQL,
  • datatype must be a valid PL/SQL data type or any user defined data type.
Some valid variable declarations along with their definition are shown below:

COUNT   NUMBER(10, 2);
name    VARCHAR2(20);
address VARCHAR2(100);
pi      CONSTANT DOUBLE PRECISION := 3.1415;
 
When you provide a size, scale or precision limit with the data type, it is called a constrained declaration. Constrained declarations require less memory than unconstrained declarations.
 
For example:
 
COUNT   NUMBER(10, 2);
name    VARCHAR2(20);
address VARCHAR2(100);

The following illustrates some examples of declaring variables in a PL/SQL anonymous block:
 

DECLARE 

    v_first_name  VARCHAR2(20); 
    v_last_name   VARCHAR2(20); 
    n_employee_id NUMBER; 
    d_hire_date   DATE; 

BEGIN 

    NULL; 

END; 

/
 Initializing Variables in PL/SQL
 
 Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to initialize a variable with a value other than the NULL value, you can do so during the declaration, using either of the following:

The DEFAULT keyword

The assignment operator


For example:
 
counter BINARY_INTEGER := 0;
greetings VARCHAR2(20) DEFAULT 'Have a Nice Day';
 
 You can also specify that a variable should not have a NULL value using the NOT NULL constraint. If you use the NOT NULL constraint, you must explicitly assign an initial value for that variable.
 
 It is a good programming practice to initialize variables properly otherwise, sometimes program would produce unexpected result. Try the following example which makes use of various types of variables:

 DECLARE 
    a INTEGER := 10; 
    b INTEGER := 20; 
    c INTEGER; 
    f REAL; 
BEGIN 
    c := a + b; 
 
    dbms_output.Put_line('Value of c: ' || c); 
 
    f := 70.0 / 3.0; 
 
    dbms_output.Put_line('Value of f: ' || f); 
END; 
/

When the above code is executed, it produces the following result:
 
Value OF c: 30
Value OF f: 23.333333333333333333
 
PL/SQL procedure successfully completed.
 

Variable Scope in PL/SQL

 
PL/SQL allows the nesting of Blocks, i.e., each program block may contain another inner block. If a variable is declared within an inner block, it is not accessible to the outer block. However, if a variable is declared and accessible to an outer Block, it is also accessible to all nested inner Blocks. There are two types of variable scope:
 
  • Local variables - variables declared in an inner block and not accessible to outer blocks.
  • Global variables - variables declared in the outermost block or a package.
 
Following example shows the usage of Local and Global variables in its simple form:
 
DECLARE 
    -- Global variables  
    num1 NUMBER := 95; 
    num2 NUMBER := 85; 
BEGIN 
    dbms_output.Put_line('Outer Variable num1: ' || num1); 

    dbms_output.Put_line('Outer Variable num2: ' || num2); 

    DECLARE 
        -- Local variables 
        num1 NUMBER := 195; 
        num2 NUMBER := 185; 
    BEGIN 
        dbms_output.Put_line('Inner Variable num1: ' || num1); 

        dbms_output.Put_line('Inner Variable num2: ' || num2); 
    END; 
END; 
/

When the above code is executed, it produces the following result:

Outer variable num1: 95
Outer variable num2: 85 
Inner variable num1: 195
Inner variable num2: 185
 

PL/SQL procedure successfully completed.
 

PL/SQL variable anchors


 In PL/SQL program, one of the most common tasks is to select values from columns in a table into a set of variables. In case the data types of columns of the table changes, you have to change the PL/SQL program to make the types of the variables compatible with the new changes.

 PL/SQL provides you with a very useful feature called variable anchors. It refers to the use of  the  '%TYPE' keyword to declare a variable with the data type is associated with a column’s data type of a particular column in a table. 

 Let’s take a look at the 'employees' table in 'HR' sample database provided by Oracle:

 
employee_table
Employees Table
 

DECLARE 
    v_first_name  employees.first_name%TYPE; 
    v_last_name   employees.last_name%TYPE; 
    n_employee_id employees.employee_id%TYPE; 
    d_hire_date   employees.hire_date%TYPE; 
BEGIN 
    NULL; 
END; 
/

 The  v_first_name  variable has data type that is the same as the data type of the   first_name  column in the   employees   table. In case the data type of the  first_name  column changes, the  type of the  v_first_name  variable is automatically inherits the new data type of the column.