esoe 2 years ago
parent
commit
946776e62b
  1. BIN
      java/labs/j130-lab2-2.pdf
  2. BIN
      java/labs/j130-lab2.pdf
  3. BIN
      java/labs/j130-lab3.pdf
  4. BIN
      java/labs/j130-lab4.pdf
  5. 35
      java/samples/sql/preparedStatement/DEV_J130_lesson2_group1.java
  6. 87
      java/samples/sql/preparedStatement/Domain.java
  7. 137
      java/samples/sql/preparedStatement/Person.java
  8. 110
      java/samples/sql/preparedStatement/Repository.java
  9. 58
      java/samples/sql/querry/SQL_DEV_J130_1.txt
  10. 73
      java/samples/sql/querry/SQL_DEV_J130_2.txt

BIN
java/labs/j130-lab2-2.pdf

Binary file not shown.

BIN
java/labs/j130-lab2.pdf

Binary file not shown.

BIN
java/labs/j130-lab3.pdf

Binary file not shown.

BIN
java/labs/j130-lab4.pdf

Binary file not shown.

35
java/samples/sql/preparedStatement/DEV_J130_lesson2_group1.java

@ -0,0 +1,35 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dev_j130_lesson2_group1;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author denis
*/
public class DEV_J130_lesson2_group1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Repository repository = new Repository();
List<Person>persons = new ArrayList<>();
persons.add(new Person("Baker", "Alan Lan", "+79215847799", "alan@google.com"));
persons.add(new Person("Clerk", "Andrey Dronov", "+79228561295", "andr.dron@google.com"));
persons.add(new Person("Dentist", "Ivan Antonov", "+79214526633", "ivan.ant@google.com"));
//repository.saveAll(persons);
//Получение всех записей таблицы Person по полю jobtitle
//repository.findPersonByJobtitle("Pharmacist").forEach(System.out::println);
//Получение всех записей таблицы Person
repository.findAllPerson().forEach(System.out::println);
}
}

87
java/samples/sql/preparedStatement/Domain.java

@ -0,0 +1,87 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dev_j130_lesson2_group1;
import java.sql.Date;
import java.util.Objects;
/**
*
* @author denis
*/
public class Domain {
int id;
String webname;
String domainname;
String ip;
Date datereg;
String countryreg;
Person person;
public Domain(int id, String webname, String domainname, String ip, Date datereg, String countryreg, Person person) {
this.id = id;
this.webname = webname;
this.domainname = domainname;
this.ip = ip;
this.datereg = datereg;
this.countryreg = countryreg;
this.person = person;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + this.id;
hash = 79 * hash + Objects.hashCode(this.webname);
hash = 79 * hash + Objects.hashCode(this.domainname);
hash = 79 * hash + Objects.hashCode(this.ip);
hash = 79 * hash + Objects.hashCode(this.datereg);
hash = 79 * hash + Objects.hashCode(this.countryreg);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Domain other = (Domain) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.webname, other.webname)) {
return false;
}
if (!Objects.equals(this.domainname, other.domainname)) {
return false;
}
if (!Objects.equals(this.ip, other.ip)) {
return false;
}
if (!Objects.equals(this.countryreg, other.countryreg)) {
return false;
}
if (!Objects.equals(this.datereg, other.datereg)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Domain{" + "id=" + id + ", webname=" + webname + ", domainname=" + domainname + ", ip=" + ip + ", datereg=" + datereg + ", countryreg=" + countryreg + '}';
}
}

137
java/samples/sql/preparedStatement/Person.java

@ -0,0 +1,137 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dev_j130_lesson2_group1;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
/**
*
* @author denis
*/
public class Person {
private int id;
private String jobtitle;
private String firstnamelastname;
private String phone;
private String email;
private Set<Domain> domains = new LinkedHashSet<>();
public Person(int id, String jobtitle, String firstnamelastname, String phone, String email) {
this.id = id;
this.jobtitle = jobtitle;
this.firstnamelastname = firstnamelastname;
this.phone = phone;
this.email = email;
}
public Person(String jobtitle, String firstnamelastname, String phone, String email) {
this.jobtitle = jobtitle;
this.firstnamelastname = firstnamelastname;
this.phone = phone;
this.email = email;
}
public void addDomains(Domain domain) {
domains.add(domain);
}
public int getId() {
return id;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getFirstnamelastname() {
return firstnamelastname;
}
public void setFirstnamelastname(String firstnamelastname) {
this.firstnamelastname = firstnamelastname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + this.id;
hash = 83 * hash + Objects.hashCode(this.jobtitle);
hash = 83 * hash + Objects.hashCode(this.firstnamelastname);
hash = 83 * hash + Objects.hashCode(this.phone);
hash = 83 * hash + Objects.hashCode(this.email);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.jobtitle, other.jobtitle)) {
return false;
}
if (!Objects.equals(this.firstnamelastname, other.firstnamelastname)) {
return false;
}
if (!Objects.equals(this.phone, other.phone)) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Person{").append("id=").append(id).append(", jobtitle=").append(jobtitle);
sb.append(", firstnamelastname=").append(firstnamelastname).append(", phone=").append(phone);
sb.append(", email=").append(email).append("}\n");
if(domains.size()>0){
domains.forEach(domain -> {
sb.append(domain).append("\n");
});
}
return sb.toString();
}
}

110
java/samples/sql/preparedStatement/Repository.java

@ -0,0 +1,110 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dev_j130_lesson2_group1;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
*
* @author denis
*/
public class Repository {
private String url;
private String login;
private String password;
public Repository() {
url = "jdbc:derby://localhost:1527/PersonsDB";
login = "root";
password = "root";
}
public Set<Person> findAllPerson(){
Map<Integer, Person> personMap = new LinkedHashMap<>();
try (Connection connection = DriverManager.getConnection(url, login, password);
Statement statement = connection.createStatement()){
ResultSet rs = statement.executeQuery("SELECT * FROM PERSON LEFT JOIN DOMAINS ON PERSON.ID=DOMAINS.PERSONID");
while(rs.next()){
Person person;
Integer personId = rs.getInt(1);
if(!personMap.containsKey(personId)){
String jobtitle = rs.getString(2);
String firstnamelastname = rs.getString(3);
String phone = rs.getString(4);
String emai = rs.getString(5);
person = new Person(personId, jobtitle, firstnamelastname, phone, emai);
personMap.put(personId, person);
}else person = personMap.get(personId);
int domainId = rs.getInt(6);
String domainname = rs.getString(8);
if(domainname!=null){
String webname = rs.getString(7);
String ip = rs.getString(9);
Date datereg = rs.getDate(10);
String countryreg = rs.getString(11);
Domain domain = new Domain(domainId, webname, domainname, ip, datereg, countryreg, person);
person.addDomains(domain);
}
}
} catch (SQLException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}
return personMap.values().stream().collect(Collectors.toSet());
}
public Set<Person> findPersonByJobtitle(String jobtitle){
Set<Person> persons = new LinkedHashSet<>();
try (Connection connection = DriverManager.getConnection(url, login, password);
PreparedStatement ps = connection.prepareStatement("SELECT ID, JOBTITLE, FIRSTNAMELASTNAME, PHONE, EMAIL FROM PERSON WHERE JOBTITLE=?")){
ps.setString(1, jobtitle);
ResultSet rs = ps.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String job = rs.getString(2);
String firstnamelastname = rs.getString(3);
String phone = rs.getString(4);
String emai = rs.getString(5);
Person person = new Person(id, job, firstnamelastname, phone, emai);
persons.add(person);
}
} catch (SQLException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}
return persons;
}
public void saveAll(List<Person> persons){
try (Connection connection = DriverManager.getConnection(url, login, password);
PreparedStatement ps = connection.prepareStatement("INSERT INTO PERSON (JOBTITLE, FIRSTNAMELASTNAME, PHONE, EMAIL) VALUES (?, ?, ?, ?)")){
for (Person person : persons){
ps.setString(1, person.getJobtitle());
ps.setString(2, person.getFirstnamelastname());
ps.setString(3, person.getPhone());
ps.setString(4, person.getEmail());
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

58
java/samples/sql/querry/SQL_DEV_J130_1.txt

@ -0,0 +1,58 @@
-- ///////////////////////////////////////Создание таблиц///////////////////////////////////
CREATE TABLE person (
id int primary key generated always as identity (start with 1, increment by 1),
full_name varchar(200) not null,
birth date
);
--DROP TABLE PERSON;
CREATE TABLE building (
id int primary key generated always as identity (start with 1, increment by 1),
address varchar(200) not null,
date_build date,
status varchar(50),
type_buiding varchar(50),
count_men int,
check (type_buiding in ('жилое', 'ТЦ', 'БЦ', 'больница')),
check (status='build' and date_build is null or status='done' and date_build is not null)
);
--DROP TABLE BUILDING;
ALTER TABLE building ADD COLUMN person_id int;
ALTER TABLE building ADD CONSTRAINT fk_building_person FOREIGN KEY (person_id) REFERENCES person(id)
-- ////////////////////////////////////////////////////Наполнение таблиц данными//////////////////////////////////////////////////
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Andrey Rozkov', '1996-12-05');
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Maksim Rozkov', '1989-10-15');
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Olga Krot', '1982-02-03');
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Natalia Ivanova', '1999-01-23');
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Vladimir Zorin', '1996-12-05');
INSERT INTO PERSON (FULL_NAME, BIRTH) VALUES ('Ivan Karulin', '1996-08-05');
UPDATE PERSON SET BIRTH = '1998-06-25' WHERE FULL_NAME LIKE '%in';
DELETE FROM PERSON WHERE FULL_NAME='Maksim Rozkov';
SELECT * FROM PERSON;
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING, PERSON_ID) VALUES ('Saint Petersburg', '1956-02-06', 'done', 'жилое', 1);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING, PERSON_ID) VALUES ('Moscow', '1981-05-26', 'done', 'жилое', 1);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING, PERSON_ID) VALUES ('Saint Petersburg', '1843-12-15', 'done', 'жилое', 4);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING, PERSON_ID) VALUES ('Saint Petersburg', '1799-04-09', 'done', 'жилое', 5);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING) VALUES ('Moscow', '1650-01-01', 'done', 'жилое');
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, TYPE_BUIDING) VALUES ('Moscow', '1999-11-01', 'done', 'жилое');
INSERT INTO BUILDING (ADDRESS, STATUS, TYPE_BUIDING) VALUES ('Moscow', 'build', 'БЦ');
SELECT * FROM BUILDING;
-- ////////////////////////////////////////////Запросы данных из БД///////////////////////////////////////////
SELECT * FROM BUILDING ORDER BY ID DESC; -- сортировка по полю id в обратном порядке
SELECT DISTINCT(STATUS) FROM BUILDING; -- выводит уникальные значения поля status
SELECT COUNT(id) FROM BUILDING; -- выводит количество записей поля id
SELECT * FROM PERSON p LEFT JOIN BUILDING b ON p.ID=b.PERSON_ID WHERE b.PERSON_ID is null;
SELECT * FROM PERSON RIGHT JOIN BUILDING ON PERSON.ID=BUILDING.PERSON_ID WHERE BUILDING.PERSON_ID is null;
SELECT p.ID, b.ADDRESS, b.PERSON_ID FROM PERSON p JOIN BUILDING b ON p.ID=b.PERSON_ID; -- тоже что и INNER JOIN;

73
java/samples/sql/querry/SQL_DEV_J130_2.txt

@ -0,0 +1,73 @@
-- ///////////////////////////////////Создание таблиц///////////////////////////////////////////////
DROP TABLE person;
CREATE TABLE person (
id int primary key generated always as identity (start with 1, increment by 1),
full_name varchar(100) not null,
birthday date
);
DROP TABLE BUILDING;
CREATE TABLE building (
id int primary key generated always as identity (start with 1, increment by 1),
address varchar(200) not null unique,
date_build date,
status varchar(50),
CHECK (status in ('строится', 'сдано')),
CHECK (status='строится' and date_build is null or status='сдано' and date_build is not null)
);
ALTER TABLE building ADD COLUMN person_id int;
ALTER TABLE building ADD COLUMN COUNT_MEN int;
ALTER TABLE building ADD CONSTRAINT fk_personId_person FOREIGN KEY (person_id) REFERENCES person(id);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS) VALUES ('Saint Petersburg', '2022-01-16', 'сдано');
INSERT INTO BUILDING (ADDRESS, STATUS) VALUES ('Saint Petersburg, Green st.', 'строится');
-- ////////////////////////////Наполнение таблиц данными//////////////////////////////////////
INSERT INTO PERSON (FULL_NAME, BIRTHDAY) VALUES ('Muhin Vadim', '1985-10-25');
INSERT INTO PERSON (FULL_NAME, BIRTHDAY) VALUES ('Ivanov Andrey', '1999-11-15');
INSERT INTO PERSON (FULL_NAME, BIRTHDAY) VALUES ('Sergeev Sergey', '1991-05-02');
INSERT INTO PERSON (FULL_NAME, BIRTHDAY) VALUES ('Antonov Victor', '1989-09-10');
INSERT INTO PERSON (FULL_NAME, BIRTHDAY) VALUES ('Petrov Sergey', '1987-07-29');
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, PERSON_ID) VALUES ('Saint Petersburg, Nevskiy', '1999-10-10', 'сдано', 6);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS) VALUES ('Saint Petersburg, Chkalovskiy', '1895-10-25', 'сдано');
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, PERSON_ID) VALUES ('Saint Petersburg, Morskaya', '1990-05-06', 'сдано', 6);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS) VALUES ('Saint Petersburg, Konuschenaya', '1999-08-07', 'сдано');
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, PERSON_ID) VALUES ('Saint Petersburg, Nalichnays', '1999-10-07', 'сдано', 7);
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS) VALUES ('Saint Petersburg, Kostuschko', '1998-05-01', 'сдано');
INSERT INTO BUILDING (ADDRESS, DATE_BUILD, STATUS, PERSON_ID) VALUES ('Saint Petersburg, Veteranov', '2003-12-26', 'сдано', 8);
INSERT INTO BUILDING (ADDRESS, STATUS) VALUES ('Saint Petersburg, Kosmonavtov', 'строится');
DELETE FROM BUILDING WHERE ADDRESS LIKE '%N%';
DELETE FROM PERSON;
UPDATE PERSON SET FULL_NAME = 'Krot Evgeniy' WHERE id=6;
-- ////////////////////////////////Запросы данных из БД//////////////////////////////////////////////
SELECT ID, ADDRESS, DATE_BUILD, STATUS, PERSON_ID FROM BUILDING;
SELECT COUNT(ID) FROM BUILDING;
SELECT DISTINCT(STATUS) FROM BUILDING;
SELECT COUNT(DISTINCT(STATUS)) FROM BUILDING;
SELECT * FROM BUILDING WHERE DATE_BUILD > '1995-01-01' AND STATUS='сдано';
SELECT * FROM PERSON LEFT JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID;
SELECT * FROM PERSON RIGHT JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID;
SELECT * FROM PERSON INNER JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID;
SELECT p.ID, p.FULL_NAME, b.ADDRESS FROM PERSON p LEFT JOIN BUILDING b ON p.ID = b.PERSON_ID WHERE b.PERSON_ID is null;
SELECT * FROM PERSON RIGHT JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID WHERE BUILDING.PERSON_ID is null;
SELECT * FROM BUILDING WHERE PERSON_ID is null;
SELECT * FROM PERSON FULL JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID;
-- Получить персон у которых здания построены в 1999 году
SELECT * FROM PERSON LEFT JOIN BUILDING ON PERSON.ID = BUILDING.PERSON_ID WHERE DATE_BUILD >= '1999-01-01' AND DATE_BUILD <= '1999-12-31';
-- Синтетический пример с несуществующей третьей таблицей
SELECT * FROM PERSON
LEFT JOIN
(SELECT * FROM BUILDING RIGHT JOIN CADASTR ON BUILDING.ID = CADASTR.BUILDING_ID) AS cad
ON PERSON.ID = cad.PERSON_ID;
Loading…
Cancel
Save