Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, July 18, 2022

SQL Mapping with Java

SQL Mapping Java, Core Java Exam, Oracle Java Certification, Java Tutorial and Materials

SQL Mapping is an easier technique in which a normal user imagined columns(normally we say as metadata) are stored in the form of different tables. Each and every table information can be joined with other tables by means of special relationships like a Foreign key in a database. In each and every table, we will have Primary Key or Unique key to uniquely identify a column value in a table. There are subtle differences between Unique and Primary keys.

◉ Unique key will uniquely identify a record but it can allow null values. 

◉ Primary key will uniquely identify a record but it will not allow null values.

◉ Additionally, we have Foreign keys to combine the details between 2 or more tables (Care must be taken during the time of SQL mapping)

For example, for an employee, personal information is stored on a table. official information is stored in another table. Personal details table: ’employeeId’ is the Primary Key for table A (Parent table). In table B (where official details are stored), table A Primary Key is maintained as a Foreign key. Child table). Only when a parent exists, the child will also exist. In the same concept, when an employee ‘E001’ is present in table A, the same employee ‘E0001’ can be present in table B. Otherwise it cannot exist. Similarly while deleting, we need to delete all the records of the child first and then only the parent one. For keeping all these kinds of relationships, several keys exist in databases like SQL Server. Now coming to the SQL mapping part, nowadays object-oriented programming languages like Java are all providing fantastic support for SQL Mapping

Java Datatype Equivalent SQL Server Datatype 
String  varchar, nvarchar
int, short, byte  Bit, tinyInt,SmallInt,Integer,BigInt etc., 
float, double  Real, Float, Decimal 

In Java, if we are creating a class, then it is a plain old java object (POJO) class and it will have different attributes depending upon requirements. Let us see with an example for the ’employee’ POJO class in java

public class Employee {
// differnt attributes
// for Employee class
// This is required to
// identify the employee uniquely
private int id;
// firstName of an employee
private String firstName;
// lastName of an employee
private String lastName;
// salary of an employee
private int salary;
// qualification of an employee
private String qualification;
//.....
}

We can map these employee attributes in SQL Server tables easily. Let us see how to do that

CREATE TABLE [dbo].[Employee] (
    [id]         INT          NOT NULL, -- Primary Key and hence not null
    [firstName] VARCHAR (20) NULL,
    [lastName]    VARCHAR (20) NULL,
    [salary]  INT          NULL,
    [qualificatio]  VARCHAR (50)  NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([id] ASC)
);

Whenever we need to save the data or need deal with the database. In an object-oriented programming language like Java, we need to create a POJO class and all the attribute names and their data type should match with the corresponding table in a database like SQL Server. 

Way to map the tables and relationships present in SQL to the objects and their relationships in Java

1. Property and
2. Relationship mapping

1. Property Mapping

In property mapping, the mapping involves the physical attributes and virtual attributes of the objects to one or more columns. Sometimes it is not mandatory and also not necessary to map all the attributes of objects to their respective columns in tables. The reason is, that we are using data(String datatype in java/varchar in SQL Server) abase for persistence. Few columns are mandatory and they are helpful to identify the records uniquely. All Primary key columns are mandatory. Hence in Java also it should be present and it is mapped to the Primary key of a table. In the above example, ID is the Primary Key column. Additionally, we may need to have the following in the employee class

status (String datatype in java/varchar in SQL Server)
emailId (String datatype in java/varchar in SQL Server)
mobileNumber  (String datatype in java/varchar in SQL Server)
gender (String datatype in java/varchar in SQL Server)
emergencyContactNumber (String datatype in java/varchar in SQL Server)
emergencyContactPerson (String datatype in java/varchar in SQL Server)
etc.,

Consider another example inventory. There for each and every item, the price is stored and the quantity of an item is given by the user hence because of this amount calculation for an item is handled at the application level and finally stored in the table. During this time calculation formula is simple and from time to time it may vary depending upon the discounts that got applied. Hence it is not necessary to store the calculation formula in the database. So, practically check whichever is necessary and map those attributes to the corresponding columns in the database. This way of doing the mapping is called property mapping

2. Relationship Mapping

There are three types of relationships namely one to one/one to many or many to one/many to many relationships to be considered while mapping the objects to SQL. In terms of SQL Server,

◉ one-to-one is straightforward: A student can have only one rank.
◉ one-to-many relationship: A single student can take multiple programming courses like Java, Python, etc., A student can participate in multiple sports like Cricket, Volleyball, etc.,
◉ many-to-many relationship: A single student can be assigned to multiple projects, and similarly a single project can be assigned to multiple students.

In objects, the relationships are classified depending on the directionality. It can be either unidirectional/bidirectional. In unidirectional, one object is not aware of the other one but the other one is aware of the first one. i.e. student object is aware of the rank object but the rank object is not aware of the student object. Bidirectional is just the opposite. Both the objects know about each other. The employee object is aware of the department head object and the department head object is aware of the employee.

UML Way of Representation


◉ Unidirectional is denoted by the single arrow
◉ Bidirectional is denoted by a single line

These are followed in UML diagrams.

◉ For one-to-one associativity 1…1 is denoted
◉ For one-to-many, 1..* is denoted
◉ For many-to-many, *..* is denoted

Care must be taken when there are foreign keys are present in the relationship. If they are available, it has to be handled differently. Otherwise, it is quite easier only. 

Source: geeksforgeeks.org

Friday, December 18, 2020

Converting Between LocalDate and SQL Date In Java 8

Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Guides, Oracle Java Prep

A quick guide to convert between LocalDate and java.sql.Date objects in java 8 with examples.

1. Overview

In this tutorial, We’ll learn how to convert java.time.LocalDate to java.sql Date in java 8 and vice versa.

This is simple to do but when working jpa framework it is bit different to deal with the table column type.

First look at the simple conversions between LocalDate and sql Date objects in java. Next, look at the JPA problem.

2. Direction conversion between LocalDate and SQL Date

2.1 Convert LocalDate to SQL Date

Use direct method from sql Date.valueOf() method which takes the LocalDate object. So, We can pass the object of LocalDate.now() or LocalDate.of() method.

Look at the below example.

package com.javaprogramto.java8.dates.conversion.sql;

import java.sql.Date;

import java.time.LocalDate;

public class LocalDateToSQLDateExample {

    public static void main(String[] args) {

        // creating current local date using now() method and which will return the

        // curren date.

        LocalDate currentDate = LocalDate.now();

        // LocalDate to SQL date using valueOf() method.

        Date sqlDate = Date.valueOf(currentDate);

        // printing

        System.out.println("With current local date");

        System.out.println("LocalDate : " + currentDate);

        System.out.println("SQL Date : " + sqlDate);

        // working with different dates.

        LocalDate pastDate = LocalDate.of(1990, 01, 01);

        LocalDate futureDate = LocalDate.of(2050, 01, 01);

        // converting Local dates to sql dates

        Date pastSqlDate = Date.valueOf(pastDate);

        Date futureSqlDate = Date.valueOf(futureDate);

        System.out.println("\nWith different local dates");

        System.out.println("Past LocalDate : " + pastDate);

        System.out.println("Past SQL Date : " + pastSqlDate);

        System.out.println("Future LocalDate : " + futureDate);

        System.out.println("Future SQL Date : " + futureSqlDate);

    }

}

Output:

With current local date

LocalDate : 2020-12-04

SQL Date : 2020-12-04

With different local dates

Past LocalDate : 1990-01-01

Past SQL Date : 1990-01-01

Future LocalDate : 2050-01-01

Future SQL Date : 2050-01-01

If null value is passed to the Date.valueOf() method, it will throw NullPointerException.

LocalDate nullLocalDate = null;
Date nullDate = Date.valueOf(nullLocalDate);

Output:

Exception in thread "main" java.lang.NullPointerException
    at java.sql/java.sql.Date.valueOf(Date.java:291)
    at com.javaprogramto.java8.dates.conversion.sql.LocalDateToSQLDateExample.main(LocalDateToSQLDateExample.java:38)

2.2 Convert SQL Date to LocalDate

Use toLocalDate() method to convert sql date to time LocalDate in java 8.

package com.javaprogramto.java8.dates.conversion.sql;
 
import java.sql.Date;
import java.time.LocalDate;
 
public class SQLDateToLocalDateExample {
 
    public static void main(String[] args) {
 
        // Creating sql date
        Date sqlDate = Date.valueOf("2020-12-31");
         
        // converting sql date to localdate using toLocalDate() method.
        LocalDate localDate1 = sqlDate.toLocalDate();
 
        // printing the local date.
        System.out.println("Local Date 1 : "+localDate1);
    }
}

Output:

Local Date 1 : 2020-12-31

3. JPA Problem Solving AttributeConverter


If you are using the LocalDate as column type in the JPA entity and this is should be having some mapping to the the database columns type. For this type, we assume that sql Date is the right one for the column type. But, database can not recognize the type LocalDate and JPA will map this to blob type rather than java sql Date object.

Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Guides, Oracle Java Prep
This is the problem now. To solve this, we should tell to JPA that if there is any column with LocalDate type, convert it into java.sql.Date when inserting into database and convert sql date to LocalDate while retrieving the records from database.

Java persistence api is added with AttributeConverter interface in jdk 1.7.

We need to implement AttributeConverter interface and need to specify the input object type and converted result object type.

This interface has two abstract methods convertToDatabaseColumn() and 
convertToEntityAttribute().

convertToDatabaseColumn() is to convert the LocalDate to sql date and saves into database.

convertToEntityAttribute() method is executed when fetching the records from database and converts into LocalDate.

We have used Optional inside these two methods to better handle null references to avoid null pointer exception.

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Optional;
 
@Converter(autoApply = true)
public class LocalDateConverterExample implements AttributeConverter<LocalDate, Date> {
 
 
    // converts LocalDate to sql date using valueOf() method
    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Optional.ofNullable(localDate)
          .map(Date::valueOf)
          .orElse(null);
    }
 
    // converts sql date to LocalDate using toLocalDate() method
    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return Optional.ofNullable(date)
          .map(Date::toLocalDate)
          .orElse(null);
    }
}

Observe the above code, We’ve used the @Converter annotation with element autoApply to true. That means apply this conversion is applied to all targeted types by the persistence provider.

But by default this property autoApply is set to false.

If there is more than one converter defined for the same target type, the Convert annotation should be used to explicitly specify which converter to use.

Monday, April 13, 2020

DROP table Command Example in Oracle, MySQL and SQL Server

Oracle Java Cert Exam, Oracle Java Certifications, Oracle Java SQL Server, Java Prep

DROP is one of the basic SQL commands, which is used to DROP database objects. Since it's part of ANSI SQL, the DROP command is supported by all major database vendors, including Oracle, MySQL, and Microsoft SQL Server. A SQL DROP TABLE statement is used to delete a table definition and all data from a table, but DROP can also be used drop index, view, trigger, or any other database object. By the way, be careful with using the DROP table command because once a table is deleted, all the information available in the table is lost forever.

DROP is sometimes also used to clear tables; for example, removing a large table with millions of records by using SQL DELETE command may take a long time; alternatively, you can DROP and recreate the table. In-fact, the difference between TRUNCATE, DELETE, and DROP is one of the popular SQL Interview questions.

Though DELETE allows you to remove selective records, DROP doesn't provide that option. Also, DELETE is a DML command and can be rolled back, but DROP cannot be rolled back. DROP will also remove all indexes, rows, and privileges, and no DML triggers will be fired.

Though DROP behavior is more or less consistent across MySQL, Oracle, and SQL Server, there are some differences like from Oracle 10g table can be "undropped". Execution of the DROP command is also controlled by access control, so you just cannot drop a table if you don't have sufficient privileges.

How to DROP tables in Oracle, MySQL and SQL Server


Let's see the syntax to drop the table from the database.

DROP TABLE "table_name";

This syntax is the purest form, which DROP table with "table_name" in the current database or schema.

1. SQL DROP TABLE Example in MySQL

Let's see the command to drop a table from the MySQL database.

DROP TABLE Session;

2. SQL DROP TABLE Example in Oracle

Let's see the command to drop a table from the Oracle database.

DROP TABLE marketing_emp;

3. How to drop table in Microsoft SQLServer

Here is the SQL DROP table command for Microsoft SQLServer. It's actually similar to MySQL and Oracle. The following command will drop table Employee in your current database or selected schema.

If you are running this from an SQL Script, you can either use USE database command or can prefix, schema name to the table name. This will give enough hint to the database about dropping a table from which schema.

DROP TABLE Employee;   // drop table from currently selected schema

USE company;
DROP TABLE Employee;   // drop table from company schema

DROP TABLE company.Employee;  // another way to drop table from the arbitrary schema

Oracle Java Cert Exam, Oracle Java Certifications, Oracle Java SQL Server, Java Prep

Things to remember about DROP command in SQL


1) DROP is a DDL command.

2) DROP Command cannot be rolled back, except Oracle 10g which provides additional functionality to "undrop" a table as shown in the following example :

SQL&gt; FLASHBACK TABLE Product TO BEFORE DROP;

Flashback complete.

3) DROP table command removes all rows, indexes, and privileges for that table.

4) No DML triggers will be fired as a result of the DROP table command.

5) DROP can be used to clear the database by dropping and recreating them.

6) Difference between DROP and the TRUNCATE command is, DROP command will delete the entire row also the structure. But TRUNCATE command will only remove the contents only, not the structure, so no need to give specifications for another table creation.

That's all about how to drop a table in MySQL, SQL Server, and Oracle. We have not only see DROP table command examples in these three primary databases but also learned a bit about the DROP command in SQL. Since two database/schema may contain tables with the same name, it's wise to prefix schema name before table name while using the DROP command in SQL Server or Oracle. If you do use the DROP command for database clean-up, remember it cannot be rolled back, and no DML trigger is fired.