-
Notifications
You must be signed in to change notification settings - Fork 13
Home work 4 #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ARKUSNET
wants to merge
16
commits into
sh-vasily:main
Choose a base branch
from
ARKUSNET:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Home work 4 #12
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
dcdb157
Release method split in NumberSample.java and create new class Quanti…
arthur60284-source 972a14a
Create test class QuantityTest.java
arthur60284-source efd2871
Merge branch 'main' into home_work_1_2
arthur60284-source 429aa10
Create test class QuantityTest.java
arthur60284-source 29a0c1d
Create test class QuantityTest.java
arthur60284-source 28531da
Merge pull request #4 from ARKUSNET/home_work_1_2
ARKUSNET 6a6f8f7
Change code by recommendation
arthur60284-source c812502
Merge pull request #5 from ARKUSNET/home_work_1_2
ARKUSNET 600dda2
Merge branch 'sh-vasily:main' into main
ARKUSNET 5489606
Merge pull request #6 from ARKUSNET/main
ARKUSNET 76a1e27
Merge branch 'sh-vasily:main' into main
ARKUSNET c88020e
Merge branch 'main' into home_work_1_2
arthur60284-source dcebafd
Merge pull request #7 from ARKUSNET/home_work_1_2
ARKUSNET e173a23
Home work 4
arthur60284-source 8b51b75
Merge pull request #8 from ARKUSNET/home_work_1_2
ARKUSNET bc58776
Merge branch 'sh-vasily:main' into main
ARKUSNET File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,55 @@ | ||
| package ru.msu.vmk; | ||
|
|
||
| import java.util.Objects; | ||
|
|
||
| public class Book { | ||
|
|
||
| private int bookId; | ||
| private String title; | ||
|
|
||
| private int isReserved; | ||
|
|
||
| public Book() { | ||
| } | ||
|
|
||
| public Book(String title){ | ||
| this.title = title; | ||
| } | ||
|
|
||
| public int getBookId() { | ||
| return bookId; | ||
| } | ||
|
|
||
| public void setBookId(int bookId) { | ||
| this.bookId = bookId; | ||
| } | ||
|
|
||
| public String getTitle(){ | ||
| return title; | ||
| } | ||
|
|
||
| public void setTitle(String title) { | ||
| this.title = title; | ||
| } | ||
|
|
||
| public int getIsReserved() { | ||
| return isReserved; | ||
| } | ||
|
|
||
| public void setIsReserved(int isReserved) { | ||
| this.isReserved = isReserved; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) return true; | ||
| if (o == null || getClass() != o.getClass()) return false; | ||
| Book book = (Book) o; | ||
| return bookId == book.bookId && isReserved == book.isReserved && Objects.equals(title, book.title); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(bookId, title, isReserved); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,15 +1,41 @@ | ||
| package ru.msu.vmk; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.SQLException; | ||
| import java.util.List; | ||
|
|
||
| /* Институтская библиотека */ | ||
| public interface Library { | ||
| /* Регистрация новой книги */ | ||
| void addNewBook(Book book); | ||
| void addNewBook(Book book) throws SQLException; | ||
|
|
||
| /* Студент берет книгу */ | ||
| void borrowBook(Book book, String student); | ||
| void borrowBook(Book book, String student) throws SQLException; | ||
|
|
||
| /* Студент возвращает книгу */ | ||
| void returnBook(Book book, String student); | ||
| void returnBook(Book book, String student) throws SQLException; | ||
|
|
||
| /* Получить список свободных книг */ | ||
| List<Book> findAvailableBooks(); | ||
| List<Book> findAvailableBooks() throws SQLException; | ||
| /*Инициализация базы данных*/ | ||
| void init() throws SQLException; | ||
|
|
||
| Connection getConnection() throws SQLException; | ||
|
|
||
| Book getBookByTitle(String title) throws SQLException; | ||
|
|
||
| void updateIsReservedFlag(int bookId, int isReserved) throws SQLException; | ||
|
|
||
| Student getStudentByName(String name) throws SQLException; | ||
|
|
||
| List<Relation> getRelationByStudentId(int studentId) throws SQLException; | ||
|
|
||
| void insertNewStudent(String student) throws SQLException; | ||
|
|
||
| void insertNewRelation(int bookId, int studentId) throws SQLException; | ||
|
|
||
| boolean deleteRelation(int relationId) throws SQLException; | ||
|
|
||
|
|
||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,240 @@ | ||
| package ru.msu.vmk; | ||
|
|
||
| import java.sql.*; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.logging.Logger; | ||
|
|
||
| public class LibraryImpl implements Library { | ||
|
|
||
| private final Logger logger = Logger.getLogger(LibraryImpl.class.getName()); | ||
|
|
||
| private final String jdbcUrl; | ||
| private final String user; | ||
| private final String password; | ||
|
|
||
| public LibraryImpl(String jdbcUrl, String user, String password) { | ||
| this.jdbcUrl = jdbcUrl; | ||
| this.user = user; | ||
| this.password = password; | ||
| } | ||
|
|
||
| public class LibraryImpl implements Library{ | ||
| @Override | ||
| public void addNewBook(Book book) { | ||
| public void addNewBook(Book book) throws SQLException { | ||
| Book bookInLibrary = getBookByTitle(book.getTitle()); | ||
| if (bookInLibrary == null) { | ||
| String sql = "insert into LIBRARY.BOOK (TITLE, IS_RESERVED) values (?,?)"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setString(1, book.getTitle()); | ||
| pr.setInt(2, 0); | ||
| int row = pr.executeUpdate(); | ||
| if (row > 0) { | ||
| logger.info("Книга добавлена."); | ||
| } | ||
| } | ||
| } else { | ||
| logger.info("Книга уже есть в библиотеке!"); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void borrowBook(Book book, String student) throws SQLException { | ||
| Book bookInLibrary = getBookByTitle(book.getTitle()); | ||
| if (bookInLibrary != null && bookInLibrary.getIsReserved() != 1) { | ||
| updateIsReservedFlag(bookInLibrary.getBookId(), 1); | ||
| Student studentInDB = getStudentByName(student); | ||
| if (studentInDB == null) { | ||
| insertNewStudent(student); | ||
| studentInDB = getStudentByName(student); | ||
| } | ||
| List<Relation> relations = getRelationByStudentId(studentInDB.getStudentId()); | ||
| if (!relations.isEmpty()) { | ||
| if (relations.stream().anyMatch(rel -> rel.getBookId() != bookInLibrary.getBookId())) { | ||
| insertNewRelation(bookInLibrary.getBookId(), studentInDB.getStudentId()); | ||
| } | ||
| } else { | ||
| insertNewRelation(bookInLibrary.getBookId(), studentInDB.getStudentId()); | ||
| } | ||
| logger.info("Книга выдана."); | ||
| } else { | ||
| logger.info("Книги нет в библиотеки."); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void borrowBook(Book book, String student) { | ||
| public void returnBook(Book book, String student) throws SQLException { | ||
| Student studentInDB = getStudentByName(student); | ||
| if (studentInDB != null) { | ||
| List<Relation> relations = getRelationByStudentId(studentInDB.getStudentId()); | ||
| if (!relations.isEmpty()) { | ||
| relations.stream().filter(rel -> rel.getBookId() == book.getBookId()).forEach(relation -> { | ||
| try { | ||
| updateIsReservedFlag(relation.getBookId(), 0); | ||
| deleteRelation(relation.getRelationId()); | ||
| logger.info("Книгу вернули."); | ||
| } catch (SQLException e) { | ||
| logger.severe(e.getMessage()); | ||
| } | ||
| }); | ||
| } else { | ||
| logger.info("За студентом не числится эта книга!"); | ||
| } | ||
| } else { | ||
| logger.info("Студент не найден!"); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public List<Book> findAvailableBooks() throws SQLException { | ||
| List<Book> out = new ArrayList<>(); | ||
| String sql = "select * from LIBRARY.BOOK where is_reserved = 0"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| ResultSet resultSet = pr.executeQuery(); | ||
| while (resultSet.next()) { | ||
| Book book = new Book(); | ||
| book.setBookId(resultSet.getInt("BOOK_ID")); | ||
| book.setTitle(resultSet.getString("TITLE")); | ||
| book.setIsReserved(resultSet.getInt("IS_RESERVED")); | ||
| out.add(book); | ||
| } | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| @Override | ||
| public void returnBook(Book book, String student) { | ||
| public void init() throws SQLException { | ||
| try (Statement stmt = getConnection().createStatement()) { | ||
| stmt.execute("create schema LIBRARY"); | ||
| stmt.execute("set schema LIBRARY"); | ||
| stmt.execute("CREATE TABLE LIBRARY.BOOK " + | ||
| " (BOOK_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY " + | ||
| " (START WITH 1, INCREMENT BY 1), TITLE VARCHAR(1000), IS_RESERVED INT)"); | ||
| stmt.execute("CREATE TABLE LIBRARY.STUDENT " + | ||
| " (STUDENT_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY " + | ||
| " (START WITH 1, INCREMENT BY 1), NAME VARCHAR(100))"); | ||
| stmt.execute("CREATE TABLE LIBRARY.RELATION " + | ||
| " (RELATION_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY " + | ||
| " (START WITH 1, INCREMENT BY 1), STUDENT_ID INT NOT NULL, BOOK_ID INT NOT NULL)"); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public Connection getConnection() throws SQLException { | ||
| return DriverManager.getConnection(jdbcUrl, user, password); | ||
| } | ||
|
|
||
| @Override | ||
| public Book getBookByTitle(String title) throws SQLException { | ||
| Book out = null; | ||
| String sql = "select * from LIBRARY.BOOK where title = ?"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setString(1, title); | ||
| ResultSet resultSet = pr.executeQuery(); | ||
| while (resultSet.next()) { | ||
| out = new Book(); | ||
| out.setBookId(resultSet.getInt("BOOK_ID")); | ||
| out.setTitle(resultSet.getString("TITLE")); | ||
| out.setIsReserved(resultSet.getInt("IS_RESERVED")); | ||
| } | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| @Override | ||
| public void updateIsReservedFlag(int bookId, int isReserved) throws SQLException { | ||
| String sql = "update LIBRARY.BOOK set is_reserved = ? where book_id = ?"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setInt(1, isReserved); | ||
| pr.setInt(2, bookId); | ||
| pr.executeUpdate(); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public Student getStudentByName(String name) throws SQLException { | ||
| Student out = null; | ||
| String sql = "select * from LIBRARY.STUDENT where name = ?"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setString(1, name); | ||
| ResultSet resultSet = pr.executeQuery(); | ||
| while (resultSet.next()) { | ||
| out = new Student(); | ||
| out.setStudentId(resultSet.getInt("STUDENT_ID")); | ||
| out.setStudentName(resultSet.getString("NAME")); | ||
| } | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| @Override | ||
| public List<Relation> getRelationByStudentId(int studentId) throws SQLException { | ||
| List<Relation> out = new ArrayList<>(); | ||
| String sql = "select * from LIBRARY.RELATION where student_id = ?"; | ||
| try (Connection connection = getConnection(); PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setInt(1, studentId); | ||
| ResultSet resultSet = pr.executeQuery(); | ||
| while (resultSet.next()) { | ||
| Relation relation = new Relation(); | ||
| relation.setRelationId(resultSet.getInt("RELATION_ID")); | ||
| relation.setStudentId(resultSet.getInt("STUDENT_ID")); | ||
| relation.setBookId(resultSet.getInt("BOOK_ID")); | ||
| out.add(relation); | ||
| } | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| @Override | ||
| public void insertNewStudent(String student) throws SQLException { | ||
| String sql = "insert into LIBRARY.STUDENT (NAME) " + | ||
| "values (?)"; | ||
| try (Connection connection = getConnection()) { | ||
| connection.setAutoCommit(false); | ||
| try (PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setString(1, student); | ||
| pr.execute(); | ||
| connection.commit(); | ||
| } catch (SQLException e) { | ||
| logger.severe(e.getMessage()); | ||
| getConnection().rollback(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void insertNewRelation(int bookId, int studentId) throws SQLException { | ||
| String sql = "insert into LIBRARY.RELATION (STUDENT_ID, BOOK_ID) " + | ||
| "values (?, ?)"; | ||
| try (Connection connection = getConnection()) { | ||
| connection.setAutoCommit(false); | ||
| try (PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setInt(1, studentId); | ||
| pr.setInt(2, bookId); | ||
| pr.execute(); | ||
| connection.commit(); | ||
| } catch (SQLException e) { | ||
| logger.severe(e.getMessage()); | ||
| getConnection().rollback(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public List<Book> findAvailableBooks() { | ||
| return null; | ||
| public boolean deleteRelation(int relationId) throws SQLException { | ||
| boolean flag = false; | ||
| String sql = "delete from LIBRARY.RELATION where relation_id = ?"; | ||
| try (Connection connection = getConnection()) { | ||
| try (PreparedStatement pr = connection.prepareStatement(sql)) { | ||
| pr.setInt(1, relationId); | ||
| int row = pr.executeUpdate(); | ||
| if (row > 0) { | ||
| flag = true; | ||
| } | ||
| } catch (SQLException e) { | ||
| logger.severe(e.getMessage()); | ||
| getConnection().rollback(); | ||
| } | ||
| } | ||
| return flag; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
запросы со звездочкой в коде программы лучше не писать, нужно явно писать нужные столбцы
здесь не критично, но представьте, у вас со временем в новых версиях приложения может меняться схема данных, могут добавляться столбцы, их может быть достаточно много, что может привести к проблемам с производительностью
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Спасибо, поправлю.