- Сохранение объектов в базу
- Тип данных BLOB
- Сохраняем Java-объект в базу
- Читаем Java-объект из базы
- Create sql blob in java
- Field Summary
- Fields inherited from class oracle.sql.DatumWithConnection
- Fields inherited from class oracle.sql.Datum
- Constructor Summary
- Method Summary
- Methods inherited from class oracle.sql.DatumWithConnection
- Methods inherited from class oracle.sql.Datum
- Methods inherited from class java.lang.Object
- Methods inherited from interface oracle.jdbc.internal.OracleDatumWithConnection
- Field Detail
- MAX_CHUNK_SIZE
- DURATION_INVALID
- DURATION_SESSION
- DURATION_CALL
- OLD_WRONG_DURATION_SESSION
- OLD_WRONG_DURATION_CALL
- MODE_READONLY
- MODE_READWRITE
- target
- Constructor Detail
- BLOB
- BLOB
- Method Detail
- getTarget
- length
- publisherOracle
- subscriberOracle
- subscriberOracle
- freeAsyncOracle
- getBytes
- getBinaryStream
- getBinaryStream
- position
- position
Сохранение объектов в базу
Кроме известных тебе типов данных JDBC позволяет работать со многими родными типами данных для СУБД. Ниже я приведу список типов и функции для получения их:
Тип | Метод |
---|---|
Array | getArray() |
AsciiStream | getAsciiStream() |
BigDecimal | getBigDecimal() |
BinaryStream | getBinaryStream() |
Blob | getBlob() |
Boolean | getBoolean() |
Blob | getBlob() |
Boolean | getBoolean() |
Byte | getByte() |
Bytes | getBytes() |
CharacterStream | getCharacterStream() |
Clob | getClob() |
Date | getDate() |
Double | getDouble() |
Float | getFloat() |
Int | getInt() |
Long | getLong() |
NCharacterStream | getNCharacterStream() |
Object | getObject() |
Ref | getRef() |
RowId | getRowId() |
Short | getShort() |
SQLXML | getSQLXML() |
String | getString() |
Time | getTime() |
Timestamp | getTimestamp() |
UnicodeStream | getUnicodeStream() |
URL | getURL() |
Примитивные типы мы с тобой уже рассматривали. Давай теперь попробуем поработать с объектами.
Тип данных BLOB
Если ты хочешь сохранить какой-то объект в базу данных, то самый простой способ сделать это — воспользовавшись SQL-типом BLOB. У JDBC есть его аналог, который называется Blob.
BLOB расшифровывается как B inary L arge Ob ject. Он используется для хранения массива байт. Тип Blob в JDBC является интерфейсом и в него можно класть (и получать) данные двумя способами:
Пример: колонка номер 3 содержит тип BLOB:
Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM user"); results.first(); Blob blob = results.getBlob(3); InputStream is = blob.getBinaryStream();
Чобы создать свой объект Blob, нужно воспользоваться функцией createBlob() . Пример:
String insertQuery = “INSERT INTO images(name, image) VALUES (?, ?)”; PreparedStatement statement = connection.prepareStatement(insertQuery); // Создаем объект Blob и получаем у него OtputStream для записи в него данных Blob blob = connection.createBlob(); // Заполняем Blob данными … OutputStream os = blob.setBinaryStream(1); // Передаем Вlob как параметр запроса statement.setBlob(2, blob); statement.execute();
Заполнить Blob данными можно двумя способами. Первый — через OutputSteam :
Path avatar = Paths.get("E:\\images\\cat.jpg"); OutputStream os = blob.setBinaryStream(1); Files.copy(avatar, os);
И второй — через заполнение байтами:
Path avatar = Paths.get("E:\\images\\cat.jpg"); byte[] content = Files.readAllBytes(avatar); blob.setBytes(1, content);
Сохраняем Java-объект в базу
Мы научились сохранять в базу бинарные объекты: массивы байт, байтовые потоки и так далее. А что насчет Java-объектов? Как нам сохранить Java-объект в базу данных?
Допустим, у нас есть Java-класс Employee , описывающий сотрудника компании:
Как нам сохранить объект этого класса в базу с помощью JDBC?
На самом деле ты уже знаешь все, что для этого нужно. Сначала необходимо создать таблицу в базе, которая соответствует этому классу. Например, такую:
А теперь напишем код, который добавит объект нашего класса Employee в базу:
public static boolean addEmployee(Connection connection, Employee employee) throws Exception < // Создаем и подготавливаем запрос на вставку данных в таблицу String insertQuery = "INSERT INTO employee(name, occupation, salary, join_date ) VALUES (?, ?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(insertQuery); // Заполняем запрос данными из объекта Employee statement.setString(1, employee.name); statement.setString(2, employee.occupation); statement.setInt(3, employee.salary); statement.setDate(4, employee.joinDate); // Выполняем наш запрос, и он возвращает true, если новая строка добавилась int count = statement.executeUpdate(); return count >0; >
Просто и понятно. Метод будет отлично работать.
Читаем Java-объект из базы
Записывать объект в базу мы научились, теперь давай напишем код, чтобы читать объект из базы. Начнем с кода, который читает объект из базы по его ID:
public static Employee getEployeeById(Connection connection, int id) throws Exception < // Создаем и подготавливаем запрос для получения сотрудника из таблицы PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee WHERE statement.setInt(1, id); // Выполняем наш запрос, и он возвращает null, если строк в результате запроса нет ResultSet results = statement.executeQuery(); if (!results.first()) return null; // Заполняем объект Employee данными из ResultSet Employee employee = new Employee(); employee.id = results.getInt(1); employee.name = results.getString(2); employee.occupation = results.getString(3); employee.salary = results.getInt(4); employee.joinDate = results.getDate(5); return employee; >
А если нам нужен не один объект, а несколько? Такой запрос тоже написать просто. Давай получим всех сотрудников нашей компании:
public static List getAllEployees(Connection connection) throws Exception < // Создаем и выполняем запрос для получения сотрудников из таблицы Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery("SELECT * FROM employee"); ArrayListlist = new ArrayList(); while (results.next()) < // Заполняем объект Employee данными из текущей строки ResultSet Employee employee = new Employee(); employee.id = results.getInt(1); employee.name = results.getString(2); employee.occupation = results.getString(3); employee.salary = results.getInt(4); employee.joinDate = results.getDate(5); list.add(employee); >return list; >
Кстати, если таких методов будет много, то в каждом из них придется писать одинаковый код по преобразованию строки ResultSet в объект Employee . Так что этот код можно вынести в отдельный метод.
Особенно это может быть полезно, если класс Employee содержит сложные поля типа Enum, InputStream, или ссылки на другие объекты, которые мы тоже хотим хранить в базе.
Create sql blob in java
This class implements the java.sql.Blob interface in JDBC 2.0. It provides the native implementation of the Blob methods. Use Blob interface for declaration instead of using concrete class oracle.sql.BLOB. java.sql.Blob has methods declared for all opertions. For Oracle specific methods use the interface OracleBlob . Obtaining Blob from ResultSet java.sql.Blob blob = resultSet.getBlob(. ); Creating temporary Blob from factory method, Connection java.sql.Blob blob = connection.createBlob();
Field Summary
Fields inherited from class oracle.sql.DatumWithConnection
Fields inherited from class oracle.sql.Datum
Constructor Summary
Method Summary
Returns a Publisher that publishes the result of freeing the Blob object and the resources that it holds.
Returns true if this is a SecureFile (LOBs with the STORE AS SECUREFILE option, which were introduced in Oracle Database 11g Release 1).
JDBC 3.0 Retrieves a stream that can be used to write to the BLOB value that this Blob object represents.
JDBC 3.0 Writes the given array of bytes to the BLOB value that this Blob object represents, starting at position pos , and returns the number of bytes written.
JDBC 3.0 Writes all or part of the given byte array to the BLOB value that this Blob object represents and returns the number of bytes written.
Returns a Subscriber that will append the published bytes to this Blob beginning at the specified position.
Returns a Subscriber that will append the published bytes to this Blob beginning at the specified position.
Methods inherited from class oracle.sql.DatumWithConnection
Methods inherited from class oracle.sql.Datum
Methods inherited from class java.lang.Object
Methods inherited from interface oracle.jdbc.internal.OracleDatumWithConnection
Field Detail
MAX_CHUNK_SIZE
public static final int MAX_CHUNK_SIZE
1907584: Changed MAX_CHUNK_SIZE from 32512 to 32768. This was done to accommodate larger DB_BLOCK_SIZEs. Using 32512 would cause getBufferSize() to return 32512 for DB_BLOCK_SIZEs from 8192-32768. For these block sizes getBufferSize() should return getChunkSize(); not 32512. By using 32768 as the MAX_CHUNK_SIZE, getBufferSize() returns the correct chunk size. Please see bug for details.
DURATION_INVALID
public static final int DURATION_INVALID
DURATION_SESSION
public static final int DURATION_SESSION
DURATION_CALL
public static final int DURATION_CALL
OLD_WRONG_DURATION_SESSION
public static final int OLD_WRONG_DURATION_SESSION
OLD_WRONG_DURATION_CALL
public static final int OLD_WRONG_DURATION_CALL
MODE_READONLY
public static final int MODE_READONLY
MODE_READWRITE
public static final int MODE_READWRITE
target
protected oracle.jdbc.driver.OracleBlob target
Constructor Detail
BLOB
BLOB
protected BLOB(oracle.jdbc.driver.OracleBlob b)
Method Detail
getTarget
public oracle.jdbc.driver.OracleBlob getTarget()
length
publisherOracle
public final Flow.PublisherpublisherOracle(long position) throws SQLException
Returns a Publisher that publishes the content of this Blob beginning at the specified position. The argument to each call to Subscriber.onNext will contain an implementation defined number of bytes. The Publisher does not retain the byte arrays it emits to onNext . Calling any method of this Blob except isEmptyLob() , isSecureFile() , isTemporary() , or one defined by Object between the time this method is called and the time when the returned publisher terminates will block. The returned publisher terminates once all subscribers have received Subscriber.onComplete , received Subscriber.onError , or cancelled their subscription. Asynchronous tasks initiated by this method will execute under the current AccessControlContext of the calling thread.
subscriberOracle
public final Flow.SubscribersubscriberOracle(long position) throws SQLException
Returns a Subscriber that will append the published bytes to this Blob beginning at the specified position. The subscriber does not retain byte arrays emitted to onNext . Calling any method of this Blob except isEmptyLob() , isSecureFile() , isTemporary() , or one defined by Object between the time this method is called and the time when the returned Subscriber terminates will block. The returned Subscriber terminates once Subscriber.onComplete is received, Subscriber.onError is received, or its subscription is cancelled. Asynchronous tasks initiated by this method will execute under the current AccessControlContext of the calling thread.
subscriberOracle
public final Flow.SubscribersubscriberOracle(long position, Flow.SubscriberLong> outcomeSubscriber) throws SQLException
- The outcomeSubscriber receives an onNext signal each time a write to the BLOB value is successful. The number of bytes transferred in each successful write is the argument to each invocation of onNext .
- The outcomeSubscriber receives an onComplete signal after the last published byte has been written successfully.
- The outcomeSubscriber receives an onError signal with a SQLException if a failure occurs when writing published bytes.
The outcomeSubscriber must signal demand in order to receive any of the signals listed above. If more than Flow.defaultBufferSize() writes have succeeded without demand from the outcomeSubscriber , then the returned subscriber will not signal further demand until the outcomeSubscriber has also signalled demand.
The number of writes used to transfer published bytes to the BLOB value is implementation defined, and may be different from the number of byte arrays published to the returned Subscriber .
Asynchronous tasks initiated by this method will execute under the current AccessControlContext of the calling thread.
freeAsyncOracle
public final Flow.PublisherVoid> freeAsyncOracle() throws SQLException
Returns a Publisher that publishes the result of freeing the Blob object and the resources that it holds. The object is invalid after the returned Publisher terminates with onComplete . After the returned Publisher terminates with onComplete , any attempt to invoke a method other than Blob.free() or freeAsyncOracle will result in an SQLException being thrown. Calling freeAsyncOracle on a Blob object that has already been freed is treated as a no-op. Calling any method of this Blob except isEmptyLob() , isSecureFile() , isTemporary() , or one defined by Object between the time this method is called and the time when the returned Subscriber terminates will block. The returned publisher terminates once all subscribers have received Subscriber.onComplete , received Subscriber.onError , or cancelled their subscription. The returned publisher will only emit onComplete or onError ; No items are emitted to onNext . Asynchronous tasks initiated by this method will execute under the current AccessControlContext of the calling thread. Implements the Reactive Extensions API by delegating to the ojiOracleBlob ‘s implemenation.
getBytes
Implements the Blob interface function. Return a copy of the contents of the BLOB at the requested position.
getBinaryStream
public InputStream getBinaryStream() throws SQLException
getBinaryStream
public InputStream getBinaryStream(boolean isInternal) throws SQLException
position
position
public long position(Blob pattern, long start) throws SQLException