Iniciando os estudos em SQL e JDBC em java usando o Banco de Dados PostgreSQL.
CRUD simples para ajudar a reforçar os Conhecimentos tanto em Java como SQL ultilizando o padrão de Arquitetura DAO(Data Access Objects)
Subconjuntos da linguagem SQL
- CREATE TABLE;
- ALTER TABLE;
- DROP TABLE;
- INSERT;
- DELETE;
- UPDATE;
- SELECT;
- CREATE USER;
- ALTER USER;
- BEGIN TRANSACTION;
- COMMIT;
- ROLLBACK;
Criando nosso Banco de Dados usando PostgreSQL.
create database userposjava(
with owner = postgres
encoding = 'UTF8'
tablespace = pg_ddefault
connection limit = -1;
)
DDL (Date Definition Language) (tabela pai)
create table userposjava(
id bigint not null,
nome character varying(255),
email character varying(255),
constraint user_pk primary key (id)
)
DML (Date Manipulation Language)
insert into userposjava (id, nome, email)
values (1, 'José', '[email protected]');
Passando a criação de usuários de modo manual para automático no Banco.
CREATE SEQUENCE public.usersequence
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 7
CACHE 1;
ALTER TABLE public.usersequence
OWNER TO postgres;
Nela será aplicado o conceito de um para muitos.
alter table userposjava add unique (id);
(tabela pai)
create table telefoneuser
(
id bigint not null,
numero character varying (255) not null,
tipo character varying (255) not null,
usuariopessoa bigint not null,
constraint telefone_id primary key (id));
Tranformando em forign key usuariopessoa referenciando a tabela Pai o tributo id.
alter table telefoneuser add foreign key (usuariopessoa) references userposjava(id)
Gerando a criação de telefones automático no Banco.
CREATE SEQUENCE user_telefone_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE user_telefone_seq
OWNER TO postgres;
Tranformando em forign key user_telefone_seq referenciando a tabela Pai o tributo id.
ALTER TABLE telefoneuser ALTER COLUMN id SET DEFAULT nextval('user_telefone_seq'::regclass);
INSERT INTO public.userposjava( nome, email) VALUES ('test10', '[email protected]');
INSERT INTO public.telefoneuser(numero, tipo, usuariopessoa)
VALUES (' (25) 9 9865-7823', 'celular', '10');
INSERT INTO public.telefoneuser(numero, tipo, usuariopessoa)
VALUES (' (25) 9 8881-7823', 'celular', '10');
INSERT INTO public.telefoneuser(numero, tipo, usuariopessoa)
VALUES (' (18) 9 3659-4587', 'celular', '9');
INSERT INTO public.telefoneuser(numero, tipo, usuariopessoa)
VALUES (' (17) 9 4521-8975', 'celular', '9');
INSERT INTO public.telefoneuser(numero, tipo, usuariopessoa)
VALUES (' (19) 9 3684-7841', 'celular', '9');
Trabalhando com relacionamento de tabela com INNER JOIN.
select * from telefoneuser as fone
inner join userposjava as userp
on fone.usuariopessoa = userp.id
primeiro deletando as filhas e depois o Pai.
delete from telefoneuser where usuariopessoa = 10
delete from userposjava where id = 10
Download do projeto para testar em sua máquina: https://github.com/AugustoMello09/SQL-e-JDBC-em-Java/archive/refs/heads/main.zip