GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add Code Sample for Hibernate dialect for Spanner (#1565) · dmichel1/java-docs-samples@07600f3

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • spanner/hibernate
    • README.md
    • pom.xml
    • src/main
      • java/com/example/spanner
        • CreditCardPayment.java
        • HibernateSampleApplication.java
        • Payment.java
        • Person.java
        • WireTransferPayment.java
      • resources
        • hibernate.cfg.xml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎spanner/hibernate/README.md‎

Copy file name to clipboard
+74Lines changed: 74 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Cloud Spanner Hibernate Example
2+
3+
This sample application demonstrates using [Hibernate 5.4](https://hibernate.org/orm/releases/5.4/)
4+
with [Google Cloud Spanner](https://cloud.google.com/spanner/).
5+
6+
## Maven
7+
8+
This sample uses the [Apache Maven][maven] build system. Before getting started, be
9+
sure to [download][maven-download] and [install][maven-install] it. When you use
10+
Maven as described here, it will automatically download the needed client
11+
libraries.
12+
13+
[maven]: https://maven.apache.org
14+
[maven-download]: https://maven.apache.org/download.cgi
15+
[maven-install]: https://maven.apache.org/install.html
16+
17+
## Setup
18+
19+
1. Follow the set-up instructions in [the documentation](https://cloud.google.com/java/docs/setup).
20+
21+
2. Enable APIs for your project.
22+
[Click here](https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com&showconfirmation=true)
23+
to visit Cloud Platform Console and enable the Google Cloud Spanner API.
24+
25+
3. Create a Cloud Spanner instance and database via the Cloud Plaform Console's
26+
[Cloud Spanner section](http://console.cloud.google.com/spanner).
27+
28+
4. Enable application default credentials by running the command `gcloud auth application-default login`.
29+
30+
5. Set the parameters for your Spanner database in the database connection string in `src/main/resources/hibernate.cfg.xml`:
31+
`jdbc:cloudspanner:/projects/{YOUR_PROJECT_ID}/instances/{YOUR_INSTANCE_ID}/databases/{YOUR_DATABASE_ID}`
32+
33+
## Run the Example
34+
35+
Run the following commands on the command line in the project directory:
36+
37+
```
38+
mvn clean compile exec:java
39+
```
40+
41+
These commands will compile the Java files and run the `main` method in
42+
`HibernateSampleApplication.java`
43+
44+
This example opens a transaction and saves a `Person` entity without specifying its `UUID`.
45+
It also saves associated `Payment` records for the person.
46+
47+
This insert query will appear in the application output:
48+
49+
```
50+
Hibernate: insert into PersonsTable (address, name, nickname, id) values (?, ?, ?, ?)
51+
Hibernate: insert into Payment (amount, id) values (?, ?)
52+
Hibernate: insert into WireTransferPayment (wire_id, id) values (?, ?)
53+
Hibernate: insert into Payment (amount, id) values (?, ?)
54+
Hibernate: insert into CreditCardPayment (credit_card_id, id) values (?, ?)
55+
...
56+
```
57+
58+
The saved entities are then retrieved using an HQL query, and the stored person with the generated ID is printed:
59+
60+
```
61+
Hibernate: select person0_.id as id1_0_, person0_.address as address2_0_, person0_.name as name3_0_, person0_.nickname as nickname4_0_ from PersonsTable person0_
62+
63+
There are 1 persons saved in the table:
64+
Person{
65+
id=688377a3-b884-4beb-886d-6e93317c5542
66+
name='person'
67+
nickname='purson'
68+
address='address'
69+
payment_amount=800
70+
}
71+
```
72+
73+
You will also be able to view the tables and data that Hibernate created in Spanner through the
74+
[Google Cloud Platform Console](https://console.cloud.google.com/spanner).
Collapse file

‎spanner/hibernate/pom.xml‎

Copy file name to clipboard
+84Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
6+
<modelVersion>4.0.0</modelVersion>
7+
8+
<properties>
9+
<maven.compiler.target>1.8</maven.compiler.target>
10+
<maven.compiler.source>1.8</maven.compiler.source>
11+
</properties>
12+
13+
<!--
14+
The parent pom defines common style checks and testing strategies for our samples.
15+
Removing or replacing it should not affect the execution of the samples in anyway.
16+
-->
17+
<parent>
18+
<groupId>com.google.cloud.samples</groupId>
19+
<artifactId>shared-configuration</artifactId>
20+
<version>1.0.11</version>
21+
</parent>
22+
23+
<groupId>com.example.spanner</groupId>
24+
<artifactId>cloud-spanner-hibernate</artifactId>
25+
<name>Cloud Spanner with Hibernate Code Sample</name>
26+
27+
<!-- [START spanner_hibernate_dependencies] -->
28+
<dependencies>
29+
30+
<!-- The Hibernate dialect for Spanner dependency -->
31+
<dependency>
32+
<groupId>com.google.cloud</groupId>
33+
<artifactId>google-cloud-spanner-hibernate-dialect</artifactId>
34+
<version>0.1.0-SNAPSHOT</version>
35+
</dependency>
36+
37+
<!-- The Spanner JDBC driver dependency -->
38+
<dependency>
39+
<groupId>com.google.cloud</groupId>
40+
<artifactId>google-cloud-spanner-jdbc</artifactId>
41+
<version>0.3.0</version>
42+
</dependency>
43+
44+
<!-- Hibernate core dependency -->
45+
<dependency>
46+
<groupId>org.hibernate</groupId>
47+
<artifactId>hibernate-core</artifactId>
48+
<version>5.4.2.Final</version>
49+
</dependency>
50+
</dependencies>
51+
<!-- [END spanner_hibernate_dependencies] -->
52+
53+
<build>
54+
<plugins>
55+
<plugin>
56+
<groupId>org.codehaus.mojo</groupId>
57+
<artifactId>exec-maven-plugin</artifactId>
58+
<version>1.6.0</version>
59+
<executions>
60+
<execution>
61+
<goals>
62+
<goal>java</goal>
63+
</goals>
64+
</execution>
65+
</executions>
66+
<configuration>
67+
<mainClass>com.example.spanner.HibernateSampleApplication</mainClass>
68+
<cleanupDaemonThreads>false</cleanupDaemonThreads>
69+
</configuration>
70+
</plugin>
71+
</plugins>
72+
</build>
73+
74+
<!-- [START spanner_hibernate_snapshot_repo] -->
75+
<repositories>
76+
<repository>
77+
<id>snapshots-repo</id>
78+
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
79+
<releases><enabled>false</enabled></releases>
80+
<snapshots><enabled>true</enabled></snapshots>
81+
</repository>
82+
</repositories>
83+
<!-- [END spanner_hibernate_snapshot_repo] -->
84+
</project>
Collapse file

‎spanner/hibernate/src/main/java/com/example/spanner/CreditCardPayment.java‎

Copy file name to clipboard
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Copyright 2019 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package com.example.spanner;
18+
19+
import javax.persistence.Column;
20+
import javax.persistence.Entity;
21+
22+
@Entity
23+
class CreditCardPayment extends Payment {
24+
25+
@Column(name = "credit_card_id")
26+
private String creditCardId;
27+
28+
public String getCreditCardId() {
29+
return creditCardId;
30+
}
31+
32+
public void setCreditCardId(String creditCardId) {
33+
this.creditCardId = creditCardId;
34+
}
35+
}
Collapse file

‎spanner/hibernate/src/main/java/com/example/spanner/HibernateSampleApplication.java‎

Copy file name to clipboard
+86Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Copyright 2019 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package com.example.spanner;
18+
19+
import java.util.List;
20+
import org.hibernate.Session;
21+
import org.hibernate.SessionFactory;
22+
import org.hibernate.boot.MetadataSources;
23+
import org.hibernate.boot.registry.StandardServiceRegistry;
24+
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
25+
26+
/**
27+
* An example Hibernate application using the Google Cloud Spanner Dialect for Hibernate ORM.
28+
*/
29+
public class HibernateSampleApplication {
30+
31+
/**
32+
* Main method that runs a simple console application that saves a {@link Person} entity and then
33+
* retrieves it to print to the console.
34+
*/
35+
public static void main(String[] args) {
36+
37+
// Create Hibernate environment objects.
38+
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
39+
.configure()
40+
.build();
41+
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata()
42+
.buildSessionFactory();
43+
Session session = sessionFactory.openSession();
44+
45+
// Save an entity into Spanner Table.
46+
savePerson(session);
47+
48+
session.close();
49+
}
50+
51+
/**
52+
* Saves a {@link Person} entity into a Spanner table.
53+
*/
54+
public static void savePerson(Session session) {
55+
session.beginTransaction();
56+
57+
WireTransferPayment payment1 = new WireTransferPayment();
58+
payment1.setWireId("1234ab");
59+
payment1.setAmount(200L);
60+
61+
CreditCardPayment payment2 = new CreditCardPayment();
62+
payment2.setCreditCardId("creditcardId");
63+
payment2.setAmount(600L);
64+
65+
Person person = new Person();
66+
person.setName("person");
67+
person.setNickName("purson");
68+
person.setAddress("address");
69+
70+
person.addPayment(payment1);
71+
person.addPayment(payment2);
72+
73+
session.save(person);
74+
session.getTransaction().commit();
75+
76+
List<Person> personsInTable =
77+
session.createQuery("from Person", Person.class).list();
78+
79+
System.out.println(
80+
String.format("There are %d persons saved in the table:", personsInTable.size()));
81+
82+
for (Person personInTable : personsInTable) {
83+
System.out.println(personInTable);
84+
}
85+
}
86+
}
Collapse file

‎spanner/hibernate/src/main/java/com/example/spanner/Payment.java‎

Copy file name to clipboard
+59Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2019 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
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+
package com.example.spanner;
18+
19+
// [START spanner_hibernate_inheritance]
20+
import java.util.UUID;
21+
import javax.persistence.Entity;
22+
import javax.persistence.GeneratedValue;
23+
import javax.persistence.GenerationType;
24+
import javax.persistence.Id;
25+
import javax.persistence.Inheritance;
26+
import javax.persistence.InheritanceType;
27+
import org.hibernate.annotations.Type;
28+
29+
/**
30+
* An example {@link Entity} which demonstrates usage of {@link Inheritance}.
31+
*/
32+
@Entity
33+
@Inheritance(strategy = InheritanceType.JOINED)
34+
public abstract class Payment {
35+
36+
@Id
37+
@GeneratedValue(strategy = GenerationType.AUTO)
38+
@Type(type = "uuid-char")
39+
private UUID id;
40+
41+
private Long amount;
42+
43+
public UUID getId() {
44+
return id;
45+
}
46+
47+
public void setId(UUID id) {
48+
this.id = id;
49+
}
50+
51+
public Long getAmount() {
52+
return amount;
53+
}
54+
55+
public void setAmount(Long amount) {
56+
this.amount = amount;
57+
}
58+
}
59+
// [END spanner_hibernate_inheritance]

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.