Skip to content
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

docs: Hibernate sample #373

Merged
merged 31 commits into from
Nov 24, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ada272b
Sample application to use hibernate with PgAdapter
pratickchokhani Oct 4, 2022
13fd70d
Adding missed pom file
pratickchokhani Oct 4, 2022
3ec5a42
Added postgresql dialect
pratickchokhani Oct 4, 2022
f7d2a0e
JPA Delete and Update added
pratickchokhani Oct 6, 2022
95a7627
Sanitary fixes
pratickchokhani Oct 6, 2022
4c9492a
Using try with resources
pratickchokhani Oct 6, 2022
5959d3e
Merge branch 'postgresql-dialect' of github.com:GoogleCloudPlatform/p…
pratickchokhani Nov 2, 2022
5973c6a
Merge branch 'postgresql-dialect' of github.com:GoogleCloudPlatform/p…
pratickchokhani Nov 3, 2022
321f3e4
README.md file addes
pratickchokhani Nov 3, 2022
6e254be
1. Added test case which executes hibernate sample
pratickchokhani Nov 3, 2022
7b1981e
Changed hibernate class name
pratickchokhani Nov 4, 2022
35ecbb4
Lint fixes
pratickchokhani Nov 4, 2022
135cec6
Lint fixes
pratickchokhani Nov 4, 2022
69e86ea
Update samples/java/hibernate/README.md
pratickchokhani Nov 5, 2022
1fa0240
Update samples/java/hibernate/README.md
pratickchokhani Nov 5, 2022
54a1b59
Update samples/java/hibernate/README.md
pratickchokhani Nov 5, 2022
5cb7647
Update samples/java/hibernate/README.md
pratickchokhani Nov 5, 2022
09fbd31
Update samples/java/hibernate/README.md
pratickchokhani Nov 5, 2022
0bf1a25
Update samples/java/hibernate/src/main/resources/hibernate.properties
pratickchokhani Nov 5, 2022
b418f9d
Update src/test/java/com/google/cloud/spanner/pgadapter/hibernate/ITH…
pratickchokhani Nov 5, 2022
5ca546c
1. Test updates
pratickchokhani Nov 7, 2022
915bd39
Merge remote-tracking branch 'origin/hibernate-sample' into hibernate…
pratickchokhani Nov 7, 2022
e17dbc3
Comment lines added
pratickchokhani Nov 10, 2022
e37ad7c
mvn command fixed
pratickchokhani Nov 10, 2022
ab7526d
Debug logs
pratickchokhani Nov 10, 2022
eb19343
Debug logs
pratickchokhani Nov 10, 2022
4dbaa46
Debug logs
pratickchokhani Nov 24, 2022
de6c7ab
Merge branch 'postgresql-dialect' of github.com:GoogleCloudPlatform/p…
pratickchokhani Nov 24, 2022
3c8c6bb
Debug logs
pratickchokhani Nov 24, 2022
432a8d6
Removed debug logs
pratickchokhani Nov 24, 2022
a8b9e85
Merge branch 'postgresql-dialect' of github.com:GoogleCloudPlatform/p…
pratickchokhani Nov 24, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions samples/java/hibernate/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>hibernate</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.version>5.2.13.Final</hibernate.version>
<skipTests>false</skipTests>
<skipUnits>${skipTests}</skipUnits>
<skipITs>true</skipITs>
<it.forkCount>8</it.forkCount>
<clirr.skip>true</clirr.skip>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<excludedTests>
com.google.cloud.spanner.pgadapter.IntegrationTest,
com.google.cloud.spanner.pgadapter.golang.GolangTest,
com.google.cloud.spanner.pgadapter.csharp.DotnetTest,
com.google.cloud.spanner.pgadapter.python.PythonTest,
com.google.cloud.spanner.pgadapter.nodejs.NodeJSTest
</excludedTests>
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we can clean up this pom file a bit. This is not necessary for the Hibernate sample (and probably many of the above property definitions as well)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


<spanner.version>6.31.1</spanner.version>
<junixsocket.version>2.5.1</junixsocket.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.4.2</version>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.google.cloud.postgres;

import java.time.LocalDateTime;
import org.hibernate.Session;
import org.hibernate.tuple.ValueGenerator;

/**
* @author Brett Meyer
*/
public class CustomValueGenerator implements ValueGenerator<LocalDateTime> {
pratickchokhani marked this conversation as resolved.
Show resolved Hide resolved

@Override
public LocalDateTime generateValue(Session session, Object entity) {
return LocalDateTime.now();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
package com.google.cloud.postgres;

import com.google.cloud.postgres.models.Albums;
import com.google.cloud.postgres.models.Concerts;
import com.google.cloud.postgres.models.HibernateConfiguration;
import com.google.cloud.postgres.models.Singers;
import com.google.cloud.postgres.models.Tracks;
import com.google.cloud.postgres.models.Venues;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.query.Query;

public class HibernateSampleTest {

private static final Logger logger = Logger.getLogger(HibernateSampleTest.class.getName());

private HibernateConfiguration hibernateConfiguration;

private List<String> singersId = new ArrayList<>();
private List<String> albumsId = new ArrayList<>();
private List<Long> tracksId = new ArrayList<>();
private List<String> venuesId = new ArrayList<>();
private List<String> concertsId = new ArrayList<>();

public HibernateSampleTest(
HibernateConfiguration hibernateConfiguration) {
this.hibernateConfiguration = hibernateConfiguration;
}

public void testJPACriteria() {
Session s = hibernateConfiguration.openSession();
CriteriaBuilder cb = s.getCriteriaBuilder();
CriteriaQuery<Singers> singersCriteriaQuery = cb.createQuery(Singers.class);
Root<Singers> singersRoot = singersCriteriaQuery.from(Singers.class);
singersCriteriaQuery
.select(singersRoot)
.where(
cb.and(cb.equal(singersRoot.get("firstName"), "David"),
cb.equal(singersRoot.get("lastName"), "Lee")));

Query<Singers> singersQuery = s.createQuery(singersCriteriaQuery);
List<Singers> singers = singersQuery.getResultList();

logger.log(Level.INFO, "Listed singer: {0}", singers.size());
s.close();
}

pratickchokhani marked this conversation as resolved.
Show resolved Hide resolved
public void testHqlUpdate() {
Session s = hibernateConfiguration.openSession();

Singers singers = Utils.createSingers();
singers.setLastName("Cord");
s.getTransaction().begin();
s.saveOrUpdate(singers);
s.getTransaction().commit();

s.getTransaction().begin();
Query query = s.createQuery(
"update Singers set active=:active "
+ "where lastName=:lastName and firstName=:firstName");
query.setParameter("active", false);
query.setParameter("lastName", "Cord");
query.setParameter("firstName", "David");
query.executeUpdate();
s.getTransaction().commit();

logger.log(Level.INFO, "Updated singer: {0}", s.get(Singers.class, singers.getId()));
s.close();
}

public void testHqlList() {
Session s = hibernateConfiguration.openSession();

Query query = s.createQuery("from Singers");
List<Singers> list = query.list();
logger.log(Level.INFO, "Singers list size: {0}", list.size());

query = s.createQuery("from Singers order by fullName");
query.setFirstResult(2);
list = query.list();
logger.log(Level.INFO, "Singers list size with first result: {0}", list.size());

/* Current Limit is not supported. */
// query = s.createQuery("from Singers");
// query.setMaxResults(2);
// list = query.list();
// logger.log(Level.INFO, "Singers list size with first result: {0}", list.size());

query = s.createQuery("select sum(sampleRate) from Tracks");
list = query.list();
logger.log(Level.INFO, "Sample rate sum: {0}", list);
s.close();
}

public void testOneToManyData() {
Session s = hibernateConfiguration.openSession();
pratickchokhani marked this conversation as resolved.
Show resolved Hide resolved

Venues venues = s.get(Venues.class, UUID.fromString(venuesId.get(0)));
if (venues == null) {
logger.log(Level.SEVERE, "Previously Added Venues Not Found.");
}
if (venues.getConcerts().size() <= 1) {
logger.log(Level.SEVERE, "Previously Added Concerts Not Found.");
}

logger.log(Level.INFO, "Venues fetched: {0}", venues);
s.close();
}

public void testDeletingData() {
Session s = hibernateConfiguration.openSession();

Singers singers = Utils.createSingers();
s.getTransaction().begin();
s.saveOrUpdate(singers);
s.getTransaction().commit();

singers = s.get(Singers.class, singers.getId());
if (singers == null) {
logger.log(Level.SEVERE, "Added singers not found.");
}

s.getTransaction().begin();
s.delete(singers);
s.getTransaction().commit();

singers = s.get(Singers.class, singers.getId());
if (singers != null) {
logger.log(Level.SEVERE, "Deleted singers found.");
}
s.close();
}

public void testAddingData() {
Session s = hibernateConfiguration.openSession();
final Singers singers = Utils.createSingers();
final Albums albums = Utils.createAlbums(singers);
final Venues venues = Utils.createVenue();
final Concerts concerts1 = Utils.createConcerts(singers, venues);
final Concerts concerts2 = Utils.createConcerts(singers, venues);
final Concerts concerts3 = Utils.createConcerts(singers, venues);
s.getTransaction().begin();
s.saveOrUpdate(singers);
s.saveOrUpdate(albums);
s.saveOrUpdate(venues);
s.persist(concerts1);
s.persist(concerts2);
final Tracks tracks1 = Utils.createTracks(albums.getId());
s.saveOrUpdate(tracks1);
final Tracks tracks2 = Utils.createTracks(albums.getId());
s.saveOrUpdate(tracks2);
s.persist(concerts3);
s.getTransaction().commit();
s.clear();
pratickchokhani marked this conversation as resolved.
Show resolved Hide resolved

singersId.add(singers.getId().toString());
albumsId.add(albums.getId().toString());
venuesId.add(venues.getId().toString());
concertsId.add(concerts1.getId().toString());
concertsId.add(concerts2.getId().toString());
concertsId.add(concerts3.getId().toString());
tracksId.add(tracks1.getId().getTrackNumber());
tracksId.add(tracks2.getId().getTrackNumber());

logger.log(Level.INFO, "Created Singer: {0}", singers.getId());
logger.log(Level.INFO, "Created Albums: {0}", albums.getId());
logger.log(Level.INFO, "Created Venues: {0}", venues.getId());
logger.log(Level.INFO, "Created Concerts: {0}", concerts1.getId());
logger.log(Level.INFO, "Created Concerts: {0}", concerts2.getId());
logger.log(Level.INFO, "Created Concerts: {0}", concerts3.getId());
logger.log(Level.INFO, "Created Tracks: {0}", tracks1.getId());
logger.log(Level.INFO, "Created Tracks: {0}", tracks2.getId());
s.close();
}

public void testSessionRollback() {
Session s = hibernateConfiguration.openSession();
final Singers singers = Utils.createSingers();
s.getTransaction().begin();
s.saveOrUpdate(singers);
s.getTransaction().rollback();
s.clear();

logger.log(Level.INFO, "Singers that was saved: ", singers.getId());
Singers singersFromDb = s.get(Singers.class, singers.getId());
if (singersFromDb == null) {
logger.log(Level.INFO, "Singers not found as expected.");
} else {
logger.log(Level.SEVERE, "Singers found. Lookout for the error.");
}
s.close();
}

public void testForeignKey() {
Session s = hibernateConfiguration.openSession();

final Singers singers = Utils.createSingers();
final Albums albums = Utils.createAlbums(singers);

s.getTransaction().begin();
s.saveOrUpdate(singers);
s.persist(albums);
s.getTransaction().commit();
s.clear();

singersId.add(singers.getId().toString());
albumsId.add(albums.getId().toString());
logger.log(Level.INFO, "Created Singer: {0}", singers.getId());
logger.log(Level.INFO, "Created Albums: {0}", albums.getId());
s.close();
}

pratickchokhani marked this conversation as resolved.
Show resolved Hide resolved
public void executeTest() {
logger.log(Level.INFO, "Testing Foreign Key");
testForeignKey();
logger.log(Level.INFO, "Foreign Key Test Completed");

logger.log(Level.INFO, "Testing Session Rollback");
testSessionRollback();
logger.log(Level.INFO, "Session Rollback Test Completed");

logger.log(Level.INFO, "Testing Data Insert");
testAddingData();
logger.log(Level.INFO, "Data Insert Test Completed");

logger.log(Level.INFO, "Testing Data Delete");
testDeletingData();
logger.log(Level.INFO, "Data Delete Test Completed");

logger.log(Level.INFO, "Testing One to Many Fetch");
testOneToManyData();
logger.log(Level.INFO, "One To Many Fetch Test Completed");

logger.log(Level.INFO, "Testing HQL List");
testHqlList();
logger.log(Level.INFO, "HQL List Test Completed");

logger.log(Level.INFO, "Testing HQL Update");
testHqlUpdate();
logger.log(Level.INFO, "HQL Update Test Completed");

logger.log(Level.INFO, "Testing JPA List");
testJPACriteria();
logger.log(Level.INFO, "JPA List Test Completed");
}

public static void main(String[] args) {
HibernateSampleTest hibernateSampleTest =
new HibernateSampleTest(HibernateConfiguration.createHibernateConfiguration());
hibernateSampleTest.executeTest();
}

}
Loading