Oracle :- Numbers Table

Background

Let us create and populate a numbers table.

Code

Outline

Creating a numbers table is a bit more complicated.

And, it’s complexity is dependent on Version of Oracle.

Steps

  1. Create Table
    • Identity Column
      • To me identity column is a bit easier that Sequence
  2. Run Statement N Times
    • In Transact SQL, we use go
    • In Oracle
      • We can use the Hierarchy function “connect by level”
      • For Statement

SQL

SQL – Identity – Assign Default


create table "number"
    (
        "id" INTEGER
            GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
            NOT NULL

        , constraint "PK_Lab_Number"
            primary key
            (
                "id"
            )
    )

;
/

truncate table "number";
/

DECLARE
    l_time PLS_INTEGER;
    l_cpu PLS_INTEGER;

begin

    l_time := DBMS_UTILITY.get_time;
    l_cpu := DBMS_UTILITY.get_cpu_time;

    FOR iLoop IN 1..5000
    LOOP

        insert into "number"
        (
	        "id"
        )
        values
        (
	        default
        );

	END LOOP;

   DBMS_OUTPUT.put_line
      (
        'Time = ' || TO_CHAR(DBMS_UTILITY.get_time - l_time) || ' hsecs '
      );

   DBMS_OUTPUT.put_line
        (
          'CPU Time = ' || (DBMS_UTILITY.get_cpu_time - l_cpu) || ' hsecs '
        );

end;

/

drop table "number";
/

SQL – Identity – Assign Explicit


create table "number"
    (
        "id" INTEGER
            -- GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
            GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1)
            NOT NULL

        , constraint "PK_Lab_Number"
            primary key
            (
                "id"
            )
    )

;
/

truncate table "number";
/

DECLARE
        l_time     PLS_INTEGER;
        l_cpu      PLS_INTEGER;
        lMaxNumber integer;

begin

    l_time := DBMS_UTILITY.get_time;
    l_cpu := DBMS_UTILITY.get_cpu_time;

    FOR iLoop IN 1..1
    LOOP

		insert into "number"
        (
	        "id"
        )
        with cte
		(
		    "vail"
		)
		as
		(
		    select rownum
            FROM   dual
            CONNECT BY LEVEL <= 5000
		)
        select
           cte."vail"

        from cte
		;

	END LOOP;

    DBMS_OUTPUT.put_line
      (
        'Time = ' || TO_CHAR(DBMS_UTILITY.get_time - l_time) || ' hsecs '
      );

   DBMS_OUTPUT.put_line
        (
          'CPU Time = ' || (DBMS_UTILITY.get_cpu_time - l_cpu) || ' hsecs '
        );	

    select max("id")
    into   lMaxNumber
    from   "number"
    ;

   DBMS_OUTPUT.put_line
        (
          'lMaxNumber = ' || TO_CHAR(lMaxNumber)
        );	    

end;

/

drop table "number";
/

 

Hibernate – Error Message – “Unknown entity”

Background

Learning new tooling is not easy for me.

Error

Image

unknownEntity.20190509.0942AM

Textual

Unknown entity: sakila.Country

Trouble Shooting

Metadata

Entities Registered

Outline

  1. Start a Session or use an existing one
  2. Get Session’s Transaction handle
  3. Start a new transaction
  4. Get Session’s metamodel
  5. Get Metamodel entity list
  6. Iterate Metamodel entity list
  7. Commit Transaction

Code

/*
     * This function lists the entities declared in our session
     * It principally relies on session.getMetaModel.getEntities
     */
    private void entityList
    (
		  Session session
	)
    { 

    	String strEntity;
    	int i;
    	int iNumberofElements;
    	Transaction transaction;
    	Metamodel objEntityManager;
        Set objEntityTypeList;

    	try
        {

        	System.out.println("Retrieve entities ...."); 

        	//Get Session's Transaction
        	transaction
        		= session.getTransaction();

        	//Start Transaction
            transaction.begin();

            //Get MetaModel
            objEntityManager
            	= session.getMetamodel();

            //Get Entities
            objEntityTypeList
            	= objEntityManager.getEntities();

            //get Number of Entities
            iNumberofElements
            	= objEntityTypeList.size();

        	System.out.println
        		(
					CHAR_TAB
					+ "Number of elements is "
					+ iNumberofElements
				); 

        	//reset i
            i = 0;

            //Iterate through collection
            for (javax.persistence.metamodel.EntityType objEntityType:  objEntityTypeList)
            {

            	//increment
            	i = i +1;

            	//Get Entity
            	strEntity = objEntityType.toString();

            	//Display Entity
            	System.out.println
            	(
    				CHAR_TAB + CHAR_TAB
    				+ i
    				+ ") "
            	    + strEntity
        	    ); 

            }

        	System.out.println("Entities Retrieved"); 

        	//Close Transaction
            transaction.commit();

        }

    	catch (Exception ex)
    	{

    		System.out.println(ex.getMessage()); 

            if (session.getTransaction().isActive())
            {
                session.getTransaction().rollback();
            }

        } //Iterate through collection catch

	} //entityList<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Similar Errors

@OneToOne or @ManyToOne on [entity] references an unknown entity

Image

@OneToOne or @ManyToOne on sakila.City.country references an unknown entity.

Text


Failed to create sessionFactory object.org.hibernate.AnnotationException:
@OneToOne or @ManyToOne on sakila.City.country references an unknown entity: sakila.Country

@OneToOne or @ManyToOne on sakila.City.country references an unknown entity: sakila.Country

Summary

Was able to confirm that the entities were not registering correctly.

And, moved on from there and sought help from a real Java developer.

Apache – jMeter – Preparation – Java JRE

Background

Pardon the pun, but measuring out jMeter appropriateness for a task we have at hand.

Error

image

NotAbleToFindJavaExecutableOrVersion_20171023_0536PM

 

textual

jmeter
Not able to find Java executable or version. Please check your Java installation.
errorlevel=2
Press any key to continue . . .

 

Troubleshooting

Validation

JRE

Outline

Let us see if we have JRE installed, and if so what version.

 

Steps

  1. Launch MS Windows Control Panel
  2. If Java Applet is not present, then we do not have Java installed, and we can skip the rest of our validation steps
  3. If Java Applet is present, access the Java Applet
  4. The “Java Control Panel” window appears
  5. Access the Java Tab
  6. Click the View button
  7. The “Java Runtime Environment Settings” window appears
    • There are two tabs, User and System
      • User Tab
        • In our User tab, we noticed that we have JRE 1.7 installed
        • We also noticed that its path indicates an install path of “C:\Program Files (x86)\Java\jre7\bin\javaw.exe”
        • Having it in x86 is ominous for us, as our OS in 64-bit

 

Image

javaRuntimeEnvironmentSettings_20171023_0539PM

 

Remediation

Download and install 64-bit Java JRE if your OS is 64-bit

 

Validation

Image

javaRuntimeEnvironmentSettings_20171023_0548PM

 

Tabulated

  1. We have two versions of JRE
    • v1.8
      • Path :- C:\Program Files\java\jre1.8.0_131\bin\javaw.exe
      • Architecture :- x86_64
    • v1.7
      • C:\Program Files (x86) \ Java\jre7\bin\javaw.exe
      • Architecture :- x86

 

Explanation

It looks like we can rumble with x86_64.

 

Success

Ran jmeter.bat again and we are good!

jmeter_20171024_0903AM

DBeaver – Database Connection Configuration – Oracle – Oracle JDBC Driver

Background

Towards a couple of sample Oracle Database sample exercises that we have in mind wanted to make sure that our all purpose database client, DBeaver, is able to communicate with an Oracle Database.

 

Preparation

Oracle

Java Version

Objective

The version of JDBC Client that we need will be based on the version of JRE that is installed or will be installed on the computer.

And, so let us establish that first; that is determine the JRE Version Number.

Outline

Using Control Panel, find and launch the Java applet.

Once Java Control Panel window appears, please access the “General” tab.

Within the “General” tab, click the “About” button

Review the Version Numbers listed and exit the “About” panel, once satisfied.

Next access the “Java” tab and review the System and User settings.

Within the Java tab, we are able to enable and disable each installed JRE package.  They are listed by Version #.

Image

Image – About

controlPanel_java_about__20171013__0831PM

 

Explanation
  1. The version number is “Version 8 Update 40” ( build 1.8.0_40)
    • We have Version 8
    • Build 1.8
Image – Java Runtime Environment Settings
Image – Java Runtime Environment Settings – System

Image – Java Runtime Environment Settings – User

Image – Java Runtime Environment Settings – System

Download

Download URL

Please visit Oracle’s JDBC download web site.

The URL is Link.

And, the current version# is 12.1.0.2.

 

Image

Matrix

Jar Package Description Detail
ojdbc7.jar JDBC driver classes except classes for NLS support in Oracle Object and Collection types. NLS Support which enables Internalization are excluded
ojdbc7_g.jar Same as ojdbc7.jar except compiled with “javac -g” and contains tracing code. Tracing & Debugging support included
ojdbc7dms.jar Same as ojdbc7.jar, except that it contains instrumentation to support DMS and limited java.util.logging calls. Instrumentation & Logging Supported included
ojdbc7dms_g.jar Same as ojdbc7_g.jar except that it contains instrumentation to support DMS. Instrumentation included

 

Explanation

We do not need support for NLS, National Language, english is sufficient.

And, we do not need tracing and logging as will not be developing code and thus need to capture code related errors and instrumentation.

In short, the base package, ojdbc7.jar, is sufficient.

Download

Please download the Jar file and move it to a location where you will like to have it available to our Client, DBeaver.

Configuration

Please launch DBeaver and let us review and configure the list of JDBC Drivers.  And, also configure connections to our various Oracle Database hosts.

Outline

  1. Driver Manager
  2. Connection

 

Driver Manager

The list of Drivers currently availed is accessible through the menu items Database \ Driver Manager.

Outline

  1. Please click the menu item Database / Driver Manager
  2. In the “Driver Manager” window
    • Choose Oracle
    • Click the “Edit” button
  3. In the “Edit Driver Oracle” window
    • Tab – Libraries
      • Review the list of libraries registered
      • Add
        • If the ojdbc driver is missing
          • Please click the “Add File” button
          • Navigate to the folder where the JDBC Driver is kept
          • And, select the jdbc jar file
          • Ensure that jar file is listed
      • Driver Class
        • Click the “Find Class” button
        • In the “Driver Class” dropdown, the Driver classes are availed
          • Driver Class
            • oracle.jdbc.OracleDriver
            • oracle.jdbc.driver.OracleDriver
          • The original driver class is oracle.jdbc.driver.OracleDriver
          • And, the modern one is oracle.jdbc.OracleDriver
          • Please choose the modern one
      • Please press the OK button once you are satisfied

Images

Driver Manager – Oracle

Edit Driver “Oracle” – Before Adding Jar File

Edit Driver “Oracle” – After adding Jar file

Edit Driver “Oracle” – Choose Driver Class – Choosing

Edit Driver “Oracle” – Choose Driver Class – Chosen

 

Connection

New Connection

Please click the “Database” / “New Connection” menu item to create a new connection.

Outline

  1. In the “Select new connection type” panel
    • Please select the Oracle driver
  2. In the “Oracle Connection Settings” panel
    • Tabs
      • Tab – General
        • Group Box
          • Group Box – Connection Type
            • In the “Basic” group box
              • Host
                • Please enter the Oracle DB Server Hostname
                  • In our case localhost
              • Port
                • Please enter the Port Number for the Oracle Instance
                  • In our case 1521
              • Database
                • Please enter the database name
                  • As we are local, we clicked on the database name scroll bar and we chose XE from the discovered local instances
              • Service or SID
                • Chose SID
            • Test Connection
              • Please click the “Test Connection” button to validate your connection settings
                • If connection attempt fails, you will get an error message similar to
                  • I/O error :- The Network adapter could not establish a connection
      • Tab – Oracle Properties
        • Group Box
          • Group Box – Session Settings
            • Language
              • Please choose Default from the list of languages
            • Territory
              • Please choose Default from the list of territories
            • NLS Date Format
              • We left the “NLS Date Format” textbox empty
                • As there is no need for Internalization
          • Group Box – Content
            • Hide empty schemas
              • Please unclick the default setting of hiding empty schemas
                • Hiding empty schemas could create potential for not seeing the entire schema footprint
            • Always Show DBA Objects
              • Left unchecked as we will are not currently interested in seeing metadata information availed through the DBA schema
          • Tab – Driver Properties
            • Will not expand on this tab at this time
    • Click the Next button
  3. In the “Network” panel
    • No need for SSH Tunnel / Proxy

Image

Select new connection type

Oracle Connection Settings
Oracle Connection Settings – General – Initial

Oracle Connection Settings – General – Completed – Incorrect

Oracle Connection Settings – General – Completed – Correct

 

Create new Connection – Network

Create new Connection – Test Connection

When test connection fails…

Create new Connection – Test Connection – IO Error : The Network Adapter could not establish the connection – Image

Explanation
  1. Oracle services not started
Create new Connection – Test Connection – ORA-12514, TNS:listener does not currently know of service requested in connect descriptor – Image

 


Create new Connection – Test Connection – ORA-12514, TNS:listener does not currently know of service requested in connect descriptor – Textual

Listener refused the connection with the following error:
ORA-12514, TNS:listener does not currently know of service requested in connect descriptor

Explanation

When test connection fails…

Create new Connection – Test Connection – When things are good

Create new Connection – Finish Connection Creation
Create new Connection – Finish Connection Creation – Initial

Create new Connection – Finish Connection Creation – Completed

 

Usage

Sample Query

Session Information

Query


SELECT 
         SYSDATE AS currentDate 
       , SYS_CONTEXT ('USERENV', 'SESSION_USER') AS currentUser
       , SYS_CONTEXT('USERENV','HOST') AS host       
       , SYS_CONTEXT('USERENV','TERMINAL') AS terminal
       
FROM SYS.DUAL

Output

References

  1. Oracle Docs
  2.  Oracle-Base
    • Identifying Host Names and IP Addresses
      Link

Oracle Database Client on Windows

Background

In the last couple of posts we touched on installing Oracle XE to avail a small footprint Oracle DB Server.

Later we used SQLPlus to validate connectivity and add a new ‘regular‘ user.

 

Lineage

  1. “Oracle Database 11g Express Edition” – Installation on Windows
    Link
  2. Oracle – SQLPlus – Create new User
    Link

Download Area

The current version of the Oracle Database Engine Client is Oracle Database 11g Release 2 (11.2.0.1.0).

It is available for download here.

Which App

We will be using the Oracle Client DB Connectivity layer on MS Windows x64 bit.

Unfortunately, the client tool is Microsoft’s Business Intelligence Development and that client is 32 bit, we will have to take the Oracle 32-bit Client.

Here it is….

Size wise It is 700 MB.

Install

Select Installation Type

Image

Details

  1. InstantClient ( 174 MB )

 

Specify Installation Location ( Step 2 )

Image

Before

After

Details

  1. Changed from user specific folder to generic folder

Perform Prerequisite Checks ( Step 3 )

Image

Before

After

Details

  1. Path
    • Path’s Length
      • Value
        • Expected Value :- 1023
        • Actual Value :- 1239
      • Oracle will like for the path length to be less than 1024
      • Chose to Ignore

 

Summary ( Step 4 )

Image

Details

  1. Global Settings
    • Disk Space :-  174 MB
    • Install Type :- Instant Client
    • Oracle Home Location :- D:\app\oracle\product\11.2.0\client_1
  2. Inventory Information
    • Inventory Location :-  C:\Program Files (x86)\Oracle\Inventory

 

Install Product ( Step 5 )

Image

Validation

tnsping

Let us tnsping to see if we can connect to our locally installed Oracle XE ( Oracle Express Engine ).

Command


tnsping XE

Output

tnsnames.ora

Please review and modify tnsnames.ora to add new & modify existing alias.

Commendation

Please review Tyler Chessman very generous write-up for a good, solid, write-up on connectivity installation & configuration between SQL Server and Oracle.

 

References

  1. Tyler Chessman
    • Connecting to an Oracle Database from SQL Server and Microsoft BI Tools
      Avoid common pitfalls
      Published On :- 2014-May-14th
      Link

Oracle – SQLPlus – Create new User

 

Background

Now that we have Oracle DB Express installed, let us create a new normal user.

The reason being that there are some hoops you have to jump over if you try to use the sys or sysdba system accounts.

 

SQLPLus

There is a minimalist Client bundled with Oracle XE, it is called SQLPlus.

Launch

To launch on Windows access menu and underneath “Oracle Database 11g Express Edition” \ “Run SQL Command Line“.

 

Use

Connect as SYS

SQL


SQL> connect SYS as SYSDBA

Output

Output – Connecting …

Output – Connected

 

Create User

SQL


create user msftbids identified by mylittpwd;
grant connect to msftbids;

Connect User

Please launch another SQLPlus session and attempt to connect as the user you just created.

SQL


connect msftbids

Output

“Oracle Database 11g Express Edition” – Installation on Windows

Background

A week ago today, DH called me to speak about an interoperability problem he was facing accessing data on an Oracle DB from SQL Server.

The tool he was using is Microsoft’s Business Intelligence Development ( BIDs)

We tried to debug the problem over phone and email.

Did not get far and so I ended up connecting remotely to his machine and found a workaround using Microsoft Linked Server.

The problem was vexing enough and I wanted to reproduce locally in our Lab environment.

And, so here we go downloading and installing a Light version of the Oracle DB Engine, Oracle Express.

Download

Overview

To download please visit Oracle’s Express Edition Overview page here.

The current version is Express Edition 11g Release 2.

Download

Image

Textual

  1. Oracle Database Express Edition 11g Release 2 for Windows x64
  2. Oracle Database Express Edition 11g Release 2 for Windows x32
  3. Oracle Database Express Edition 11g Release 2 for Linux x64

 

Installation

Image

Welcome

License Agreement

Choose Destination Location

Original

Revised

Explanation
  1. Changed destination folder from C:\Oraclexe to D:\Oraclexe
  2. Space Required to 631124 K ( 630 MB)

 

Specify Database Passwords

Original

Revised

Explanation
  1. Enter password for the System Account
    • Btw, the system accounts are
      • SYS
      • SYSTEM

Summary

Image

Explanation
  1. Oracle Database Listener :- 1521
  2. Oracle Services for Microsoft Transaction Server :- 2030
  3. Oracle HTTP Listener :- 8080

Complete

Image