Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 26f88ad

Browse files
Added source code for Blog JSON, Java and the Oracle Database (#253)
* Added sample code and accompanying scripts for Oracle DB advanced Data Types * Updated license * Added examples and updates for Blog
1 parent 87b76dd commit 26f88ad

File tree

5 files changed

+272
-3
lines changed

5 files changed

+272
-3
lines changed

‎java/jdbc-data-types/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
<version>21.1.0.0</version>
3232
<type>pom</type>
3333
</dependency>
34+
<dependency>
35+
<groupId>com.oracle.database.jdbc</groupId>
36+
<artifactId>ucp</artifactId>
37+
<version>21.1.0.0</version>
38+
</dependency>
3439
</dependencies>
3540

3641
</project>

‎java/jdbc-data-types/scripts/init.sql

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,24 @@ values ('{
4848
"Stock": 0
4949
}');
5050

51+
-- Tables referenced in the blog
52+
create table PROFILES_19c (
53+
profileId number generated by default on null as identity primary key,
54+
username varchar2(32) unique,
55+
preferences VARCHAR2(4000),
56+
settings BLOB,
57+
CONSTRAINT ensure_pref_json_a CHECK (preferences IS JSON),
58+
CONSTRAINT ensure_sett_json_a CHECK (settings IS JSON)
59+
);
60+
61+
create table PROFILES (
62+
profileId number generated by default on null as identity primary key,
63+
username varchar2(32),
64+
preferences JSON,
65+
settings JSON
66+
);
67+
68+
5169
-- XMLTYPE as a table example
5270
CREATE TABLE VENDOR_INVOICES of XMLTYPE;
5371

‎java/jdbc-data-types/src/main/java/Main.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
*/
1919

2020
import database.DatabaseService;
21+
import database.DatabaseServiceWithPooling;
22+
import moreexamples.BlogExamples;
2123
import oracle.jdbc.OracleType;
2224
import oracle.jdbc.OracleTypes;
2325
import oracle.jdbc.internal.OracleClob;
@@ -34,20 +36,23 @@
3436
public class Main {
3537

3638
private static DatabaseService ods;
39+
private static DatabaseServiceWithPooling pds;
3740

3841
/**
3942
* Runner method
4043
* @param args unused
4144
*/
4245
public static void main(String[] args) {
4346
try {
44-
ods = new DatabaseService(); // initialize ods
45-
Scanner scanner = new Scanner(System.in);
47+
ods = new DatabaseService();
48+
pds = new DatabaseServiceWithPooling();
49+
50+
Scanner runFunctionChallenge = new Scanner(System.in);
4651
boolean keepGoing = true;
4752

4853
while(keepGoing) {
4954
System.out.print("Run Function: ");
50-
String functionName = scanner.next();
55+
String functionName = runFunctionChallenge.next();
5156
System.out.println("Output: ==========================================");
5257
switch (functionName) {
5358
case "readJSONExampleA" -> readJSONExampleA();
@@ -75,6 +80,11 @@ public static void main(String[] args) {
7580
case "readWithRefCursorA" -> readWithRefCursorA();
7681
case "readWithRefCursorB" -> readWithRefCursorB();
7782
case "readWithRefCursorC" -> readWithRefCursorC();
83+
case "blogExampleA" -> BlogExamples.blogExampleA(pds);
84+
case "blogExampleB" -> BlogExamples.blogExampleB(pds);
85+
case "blogExampleC" -> BlogExamples.blogExampleC(pds);
86+
case "blogExampleD" -> BlogExamples.blogExampleD(pds);
87+
case "blogExampleE" -> BlogExamples.blogExampleE(pds);
7888
case "end" -> keepGoing = false;
7989
default -> System.out.printf("Error: function %s not found.\n", functionName);
8090
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/* Copyright (c) 2021, 2022, Oracle and/or its affiliates.
2+
This software is dual-licensed to you under the Universal Permissive License
3+
(UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License
4+
2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose
5+
either license.
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
https://www.apache.org/licenses/LICENSE-2.0
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
16+
DESCRIPTION
17+
DatabaseServiceWithPooling - Used to retrieve and setup connection to an Oracle Database
18+
*/
19+
package database;
20+
21+
22+
import oracle.jdbc.OracleConnection;
23+
import oracle.ucp.jdbc.PoolDataSource;
24+
import oracle.ucp.jdbc.PoolDataSourceFactory;
25+
26+
import java.sql.SQLException;
27+
28+
public class DatabaseServiceWithPooling {
29+
private PoolDataSource pds;
30+
31+
/**
32+
* Creates an instance of pool-enabled data source and configures connection properties
33+
* @throws SQLException
34+
*/
35+
public DatabaseServiceWithPooling() throws SQLException {
36+
this.pds = PoolDataSourceFactory.getPoolDataSource();
37+
this.pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
38+
this.pds.setURL(DatabaseConfig.getDbUrl());
39+
this.pds.setUser(DatabaseConfig.getDbUser());
40+
this.pds.setPassword(DatabaseConfig.getDbPassword());
41+
}
42+
43+
/**
44+
* Gets a connection using the data source instance.
45+
* @return
46+
* @throws SQLException
47+
*/
48+
public OracleConnection getDatabaseConnection() throws SQLException {
49+
return (OracleConnection) this.pds.getConnection();
50+
51+
}
52+
}
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
/* Copyright (c) 2021, 2022, Oracle and/or its affiliates.
2+
This software is dual-licensed to you under the Universal Permissive License
3+
(UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License
4+
2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose
5+
either license.
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
https://www.apache.org/licenses/LICENSE-2.0
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
18+
package moreexamples;
19+
20+
import database.DatabaseServiceWithPooling;
21+
import oracle.jdbc.OracleType;
22+
import oracle.sql.json.OracleJsonArray;
23+
import oracle.sql.json.OracleJsonFactory;
24+
import oracle.sql.json.OracleJsonObject;
25+
26+
import java.sql.Connection;
27+
import java.sql.PreparedStatement;
28+
import java.sql.ResultSet;
29+
import java.sql.SQLException;
30+
import java.time.LocalDateTime;
31+
32+
public class BlogExamples {
33+
34+
private static OracleJsonFactory factory;
35+
36+
/**
37+
* Retrieves the instance of factory and initializes it
38+
* if the factory is null
39+
* @return
40+
*/
41+
private static OracleJsonFactory getJsonFactory() {
42+
if (BlogExamples.factory == null) {
43+
BlogExamples.factory = new OracleJsonFactory();
44+
}
45+
return BlogExamples.factory;
46+
}
47+
48+
/**
49+
* Demonstrates a simple retrieval of a VARCHAR2 and JSON data type from the profiles table
50+
* @throws SQLException
51+
*/
52+
public static void blogExampleA(DatabaseServiceWithPooling pds) throws SQLException {
53+
final String RETRIEVE_QUERY = "select username, settings from profiles";
54+
55+
try (Connection connection = pds.getDatabaseConnection()) {
56+
try (PreparedStatement retrieve_stmt = connection.prepareStatement(RETRIEVE_QUERY)) {
57+
try (ResultSet rs = retrieve_stmt.executeQuery()) {
58+
while (rs.next()) {
59+
String username = rs.getObject("username", String.class);
60+
String productInformation = rs.getObject("settings", String.class);
61+
System.out.println(username + "=" + productInformation);
62+
}
63+
}
64+
}
65+
}
66+
}
67+
68+
/**
69+
* Demonstrates retrieving of the JSON column settings and uses filter condition JSON_EXISTS to filter in only
70+
* the records where the visibility attribute exists and is set to true. In this example, OracleJSONObject is used
71+
* to process the JSON document and retrieve the values of attributes
72+
* @param pds
73+
* @throws SQLException
74+
*/
75+
public static void blogExampleB(DatabaseServiceWithPooling pds) throws SQLException {
76+
final String RETRIEVE_QUERY = """
77+
SELECT p.settings
78+
FROM profiles p
79+
WHERE json_exists(p.settings, '$.security?(@.visibility == true)')
80+
""";
81+
try (Connection connection = pds.getDatabaseConnection()) {
82+
try (PreparedStatement retrieve_stmt = connection.prepareStatement(RETRIEVE_QUERY)) {
83+
try(ResultSet rs = retrieve_stmt.executeQuery()) {
84+
while (rs.next()) {
85+
OracleJsonObject settings = rs.getObject("settings", OracleJsonObject.class); // 1
86+
OracleJsonObject security = settings.get("security").asJsonObject(); // 2
87+
System.out.println("version=" +settings.getString("version") + "; security.visibility=" + security.getBoolean("visibility")); // 3
88+
}
89+
}
90+
}
91+
}
92+
}
93+
94+
/**
95+
* Demonstrates inserting a new record with JSON data created using OracleJsonFactory and OracleJsonObject
96+
* @param pds
97+
* @throws SQLException
98+
*/
99+
public static void blogExampleC(DatabaseServiceWithPooling pds) throws SQLException {
100+
final String INSERT_QUERY = "INSERT INTO profiles (username, preferences, settings) VALUES (:1, :2, :3)";
101+
102+
OracleJsonFactory factory = getJsonFactory(); // 1
103+
OracleJsonObject preferences = factory.createObject(); // 2
104+
preferences.put("timezone", "America/Chicago"); // 3
105+
preferences.put("language", "English (US)");
106+
preferences.put("theme", "Dark");
107+
preferences.put("compact", true);
108+
109+
OracleJsonObject security = factory.createObject();
110+
security.put("sharing", true);
111+
security.put("visibility", "private");
112+
113+
OracleJsonArray keywords = factory.createArray(); // 4
114+
keywords.add("A");
115+
keywords.add("B");
116+
117+
OracleJsonObject settings = factory.createObject();
118+
settings.put("version", "4.12.1");
119+
settings.put("level", 1);
120+
settings.put("security", security); // 5
121+
settings.put("keywords", keywords); // 6
122+
123+
try (Connection connection = pds.getDatabaseConnection()) {
124+
try(PreparedStatement insert_stmt = connection.prepareStatement(INSERT_QUERY)) {
125+
insert_stmt.setString(1, "normanaberin");
126+
insert_stmt.setObject(2, preferences, OracleType.JSON); // 7
127+
insert_stmt.setObject(3, settings, OracleType.JSON);
128+
int inserted = insert_stmt.executeUpdate();
129+
System.out.println("inserted:" + inserted);
130+
}
131+
}
132+
}
133+
134+
/**
135+
* Demonstrates updating the JSON document settings using JSON_TRANSFORM and adding a new subscription object in an
136+
* array called subscriptions. Note that with the CREATE ON MISSING handler, if the subscriptions attribute
137+
* does not exist, then it is created.
138+
* @param pds
139+
* @throws SQLException
140+
*/
141+
public static void blogExampleD(DatabaseServiceWithPooling pds) throws SQLException {
142+
final String UPDATE_QUERY = """
143+
UPDATE profiles p
144+
SET p.settings = json_transform(p.settings, APPEND '$.subscriptions' = :1 CREATE ON MISSING)
145+
WHERE p.profileId = :2
146+
""";
147+
148+
final int profileId = 1;
149+
OracleJsonFactory factory = getJsonFactory();
150+
OracleJsonObject new_subscription = factory.createObject();
151+
new_subscription.put("subscriptionId", 10191);
152+
new_subscription.put("subscriptionName", "Jules");
153+
new_subscription.put("subscriptionDate", LocalDateTime.now());
154+
155+
try (Connection connection = pds.getDatabaseConnection()) {
156+
try(PreparedStatement update_stmt = connection.prepareStatement(UPDATE_QUERY)) {
157+
update_stmt.setObject(1, new_subscription, OracleType.JSON);
158+
update_stmt.setInt(2, profileId);
159+
int updated = update_stmt.executeUpdate();
160+
System.out.println("updated:" + updated);
161+
}
162+
}
163+
}
164+
165+
/**
166+
* Demonstrates updating the full JSON document profiles with a JSON string
167+
* @param pds
168+
* @throws SQLException
169+
*/
170+
public static void blogExampleE(DatabaseServiceWithPooling pds) throws SQLException {
171+
final String UPDATE_QUERY = "UPDATE profiles SET preferences=:1 WHERE profileId = :2";
172+
final String jsonstring = "{\"timezone\": \"America/Chicago\"}";
173+
final int profileId = 1;
174+
175+
try (Connection connection = pds.getDatabaseConnection()) {
176+
try(PreparedStatement update_stmt = connection.prepareStatement(UPDATE_QUERY)){
177+
update_stmt.setString(1, jsonstring);
178+
update_stmt.setInt(2, profileId );
179+
int updated = update_stmt.executeUpdate();
180+
System.out.println("updated:" + updated);
181+
}
182+
}
183+
}
184+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /