Why is TIMESTAMP DEFAULT CURRENT_TIMESTAMP not set? - oracle

I defined an Oracle table this way:
CREATE TABLE MANUAL_CORRECTION
(
ID NUMBER(19,0) NOT NULL,
MODIFIED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
MODIFIED_BY NUMBER(19,0) NOT NULL,
MODIFIED_PROPERTY VARCHAR2(20 BYTE) NOT NULL,
OLD_VALUE VARCHAR2(20 BYTE) NOT NULL,
NEW_VALUE VARCHAR2(20 BYTE) NOT NULL,
CONSTRAINT MODIFIED_BY_FK FOREIGN KEY (MODIFIED_BY) REFERENCES BENUTZER (ID) ENABLE,
PRIMARY KEY (ID)
);
I want to insert records via JPA which works well but the MODIFIED column stays always NULL although I specified that it should be set to the system timestamp by default.
How can I achieve that the system timestamp is set whenever a new entity/record is persisted?
Here is how I defined the column/entity property:
#Column(name = "MODIFIED", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp modified;

I think your JPA is sending explicitly NULL as the value for the column and The default value is applied only when you do not specify it in an insert column clause.
Insert into <table> (col1, col2) values (1, null) -- col2 - default value will not be applied
Insert into <table> (col1) values (1) -- col2 - default value will be applied
So if you want to apply default value even when NULL is explicitly passed as a value of the column, you can use the new feature of the Oracle 12c i.e. default on null
Refer this doc
Cheers!!

Related

Unable to extract JDBC value for position `3`

I am switching from MYSQL to ORACLE.
I have JPA Authentication setup like this:
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
AppUser user = userRepository.findByUseremailIgnoreCase(email);
With MySQL all works fine. But for Oracle, during login using JPA authentication I am getting this exception.
org.springframework.security.authentication.InternalAuthenticationServiceException: Unable to extract JDBC value for position `3`
Followed by these exceptions:
Caused by: org.springframework.orm.jpa.JpaSystemException: Unable to extract JDBC value for position `3`
Caused by: java.sql.SQLException: Invalid conversion requested
Caused by: java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
Any clue what I am missing and where to debug?
My table structure is as per below:
create table CONTENTPLUSPLUS.app_user (
id NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1) NOT NULL,
useremail VARCHAR(150) NOT NULL,
userpassword VARCHAR(150) NOT NULL,
useruuid VARCHAR(50) NOT NULL,
userfirstname VARCHAR(150) NOT NULL,
userlastname VARCHAR(150) NOT NULL,
userenabled NUMBER(1) DEFAULT 0 NOT NULL,
created_by VARCHAR(150) NOT NULL,
created_date VARCHAR(150) NOT NULL,
modified_by VARCHAR(150) NOT NULL,
modified_date VARCHAR(150) NOT NULL,
CONSTRAINT appuser_pk PRIMARY KEY (id), UNIQUE (useremail, useruuid));
create table CONTENTPLUSPLUS.app_role(
id NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1) NOT NULL,
name VARCHAR(150) NOT NULL,
CONSTRAINT approle_pk PRIMARY KEY (id),UNIQUE (name));
CREATE TABLE CONTENTPLUSPLUS.app_department (
id NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1) NOT NULL,
departmentuuid VARCHAR(150),
departmentheadname varchar(255) NOT NULL,
departmentheademail varchar(255) NOT NULL,
departmentname varchar(255) NOT NULL,
userid NUMBER NOT NULL,
created_by VARCHAR(150) NOT NULL,
created_date VARCHAR(150) NOT NULL,
modified_by VARCHAR(150) NOT NULL,
modified_date VARCHAR(150) NOT NULL,
CONSTRAINT appdepartment_pk PRIMARY KEY (id),UNIQUE (departmentname, departmentuuid));
CREATE TABLE CONTENTPLUSPLUS.app_user_department (
userid NUMBER NOT NULL,
departmentid NUMBER NOT NULL
);
ALTER TABLE CONTENTPLUSPLUS.app_user_department ADD CONSTRAINT FK_AUSERDEPTUSERID FOREIGN KEY (userid) REFERENCES app_user (id);
ALTER TABLE CONTENTPLUSPLUS.app_user_department ADD CONSTRAINT FK_AUSERDEPTDEPTID FOREIGN KEY (departmentid) REFERENCES app_department (id);
ALTER TABLE CONTENTPLUSPLUS.app_department ADD CONSTRAINT FK_AUSERUSERID FOREIGN KEY (userid) REFERENCES app_user (id);
CREATE TABLE CONTENTPLUSPLUS.app_user_role (
id NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1) NOT NULL,
userid NUMBER NOT NULL,
roleid NUMBER NOT NULL,
CONSTRAINT appuserrole_pk PRIMARY KEY (id));
ALTER TABLE CONTENTPLUSPLUS.app_user_role ADD CONSTRAINT FK_AURUSERID FOREIGN KEY (userid) REFERENCES app_user (id);
ALTER TABLE CONTENTPLUSPLUS.app_user_role ADD CONSTRAINT FK_AURROLEID FOREIGN KEY (roleid) REFERENCES app_role (id);
Below is the query which gets fired during the login operation (shows up only for MySQL):
Hibernate:
select
a1_0.id,
a1_0.created_by,
a1_0.created_date,
a1_0.modified_by,
a1_0.modified_date,
a1_0.useremail,
a1_0.userenabled,
a1_0.userfirstname,
a1_0.userlastname,
a1_0.userpassword,
a1_0.useruuid
from
app_user a1_0
where
upper(a1_0.useremail)=upper(?)
Hibernate:
select
r1_0.userid,
r1_1.id,
r1_1.name
from
app_user_role r1_0
join
app_role r1_1
on r1_1.id=r1_0.roleid
where
r1_0.userid=?
You map Date in Java with VARCHAR2 in SQL: bad idea. You probably get lucky with the default conversion format of TS and the locale in MySQL: back to my first comment... look at the SQL Office Hours session code...

How to configure Oracle Column's DefaultValue And Collate Value

In Oracle 19c, I want to specify the default value of a column and the collate property at the same time.
create table id_table(
name varchar2(64) collate binary_ai,
id varchar2(8) collate binary_ci
);
insert into id_table values('Christopher', 'ABCD1234');
SELECT collation(name), collation(id) from id_table;
COLLATION(NAME)
COLLATION(ID)
BINARY_AI
BINARY_CI
It was well specified as intended.
but,
create table id_table2(
name char default 'Y' collate binary_ai,
id varchar2(8)
);
insert into id_table2 values('c', 'ABCD1234');
SELECT collation(name), collation(id) from id_table2;
COLLATION(NAME)
COLLATION(ID)
USING_NLS_COMP
USING_NLS_COMP
If you specify the default value and collate together, an unintended value is specified.
The intent was to expect the same values as in the first example.
Are DEFAULT VALUE and COLLATE mutually exclusive?

Laravel how to get list of related fields through pivot table

I have 4 tables : peoples, companies, countries and the pivot table company_people (as peoples & companies both belongs to many) which has both people_id and company_id.
In the People model, I have the following functions:
class People extends Model
{
// main company (only one)
public function company()
{
return $this->belongsTo(Company::class);
}
// all other companies
public function companies()
{
return $this->belongsToMany(Company::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
}
Then in the People controller, I have the following in order to prepare to display a list of all the peoples with the related main company name (only one), country name (only one) and other companies as a list of names. I can do the first 2 but not the last one. How can I do that?
$peoples = People::orderBy($sortField,$sortOrder)
->with(['companies','company','country'])
->get();
foreach ($peoples as $people) {
$people->company = '['.$people->company->company.']'; // main company name
$people->country = '['.$people->country->country.']'; // country name
$people->otherCompanies = ? // list of other company names through pivot table
}
And here all the structure of the 4 tables:
CREATE TABLE `company_people` (
`id` bigint NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`company_id` bigint UNSIGNED NOT NULL,
`people_id` bigint UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `countries` (
`id` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'AA',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` int NOT NULL DEFAULT '1',
`country` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `peoples` (
`id` bigint UNSIGNED NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` int NOT NULL DEFAULT '1',
`firstname` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`lastname` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '',
`country_id` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'ZA',
`company_id` bigint UNSIGNED DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci PACK_KEYS=0;
ALTER TABLE `company_people`
ADD PRIMARY KEY (`id`),
ADD KEY `article_id` (`company_id`),
ADD KEY `tag_id` (`people_id`);
ALTER TABLE `countries`
ADD PRIMARY KEY (`id`);
ALTER TABLE `peoples`
ADD PRIMARY KEY (`id`),
ADD KEY `country_id` (`country_id`),
ADD KEY `company_id` (`company_id`);
ALTER TABLE `company_people`
MODIFY `id` bigint NOT NULL AUTO_INCREMENT;
ALTER TABLE `peoples`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE `peoples`
ADD CONSTRAINT `peoples-company` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `peoples-country` FOREIGN KEY (`country_id`) REFERENCES `countries` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `companies`
ADD CONSTRAINT `peoples-country` FOREIGN KEY (`country_id`) REFERENCES `countries` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `company_people`
ADD CONSTRAINT `companies-peoples` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `peoples-companies` FOREIGN KEY (`people_id`) REFERENCES `peoples` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
you can use pluck() to get all the company name then toArray() to convert in array like this
$peoples = People::orderBy($sortField,$sortOrder)
->with(['companies','company','country'])
->get();
foreach ($peoples as $people) {
$people->company = '['.$people->company->company.']'; // main company name
$people->country = '['.$people->country->country.']'; // country name
$people->otherCompanies = $people->companies->pluck('name')->toArray(); // list of other company names through pivot table
}
And if you want otherCompanies name as comma seprate then use $people->companies->pluck('name')->join(',');

How to select only those rows which are greater than modified time using spring data jpa

For Example ,
I have created a table ,
CREATE DATABASE es_db;
USE es_db;
DROP TABLE IF EXISTS es_table;
CREATE TABLE es_table (
id BIGINT(20) UNSIGNED NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY unique_id (id),
client_name VARCHAR(32) NOT NULL,
modification_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
insertion_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Now assume i have to select those data which are greater than time i give as input .
consider this query for example,
SELECT *, UNIX_TIMESTAMP(modification_time) AS unix_ts_in_secs FROM es_table WHERE (UNIX_TIMESTAMP(modification_time) > :sql_last_modifiedvalue AND modification_time < NOW()) ORDER BY modification_time ASC
Is there away to translate the same to native query ? i can achieve the same with jdbctemplate but would like to know if this is possible with native query?

Oracle - Creating Triggers

I am trying to create a trigger in Oracle whereby we move deleted records to another table. So when deleted column is set to 1, it should move the records from the patient_table to the deleted_patient_table.
Can you please help :)
CREATE TABLE Patient_Table(
PatientID NUMBER(6) Primary Key,
Title char(4) NOT NULL,
Forename varchar2(20) NOT NULL,
Surname varchar2(20) NOT NULL,
Gender char(1) NOT NULL CHECK (Gender in ('M','F')),
DOB date NOT NULL,
TelNo varchar(12) NOT NULL,
Conditions varchar(200) NOT NULL,
Deleted Number(1) NOT NULL CHECK (Deleted in ('0','1'));
-- Table that should contain deleted records --
Create Table Deleted_Patient_table(
PatientID NUMBER(6) Primary Key,
Title char(4) NOT NULL,
Forename varchar2(20) NOT NULL,
Surname varchar2(20) NOT NULL,
Gender char(1) NOT NULL CHECK (Gender in ('M','F')),
DOB date NOT NULL,
TelNo varchar(12) NOT NULL,
Conditions varchar(200) NOT NULL,
Deleted Number(1));
Create or replace trigger trg_del
Before delete on Patient_Table
for each row
Begin
Insert into Deleted_Patient_table value (:old.PatientID,...)
End;
It seems you're soft-deleting your rows. i.e. not deleting but updating related column(Deleted) from 0 to 1. The values of column can be one of two and not null, so you only need to compare only two values of them without nvl operator. During this update operation you can use below trigger to produce log records :
Create or Replace Trigger Trg_Del_Patient
After Update on Patient_Table
For Each Row
Begin
If ( :old.Deleted = 0 and :new.Deleted = 1 ) Then
Insert into Deleted_Patient_table
values(:old.PatientID,:old.Title,:old.Forename,:old.Surname,
:old.Gender,:old.DOB,:old.TelNo,:old.Conditions);
Delete Patient_Table where PatientID = :old.PatientID;
-- Include this Delete statement, if you want to remove after the row has been inserted to the Deleted_Patient_Table
End If;
End;

Resources