[BAEL-9696] - Moved persistence-related modules into the persistence folder
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to ActiveJDBC](http://www.baeldung.com/active-jdbc)
|
||||
@@ -0,0 +1,91 @@
|
||||
<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>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>activejdbc</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>opensymphony</groupId>
|
||||
<artifactId>oscache</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.connector.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<configuration>
|
||||
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||
<environments>${environments}</environments>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.connector.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<activejdbc.version>2.0</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung;
|
||||
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
import com.baeldung.model.Role;
|
||||
import org.javalite.activejdbc.Base;
|
||||
import org.javalite.activejdbc.LazyList;
|
||||
import org.javalite.activejdbc.Model;
|
||||
|
||||
public class ActiveJDBCApp
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
try {
|
||||
Base.open();
|
||||
ActiveJDBCApp app = new ActiveJDBCApp();
|
||||
app.create();
|
||||
app.update();
|
||||
app.delete();
|
||||
app.deleteCascade();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
Base.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected void create() {
|
||||
Employee employee = new Employee("Hugo","C","M","BN");
|
||||
employee.saveIt();
|
||||
employee.add(new Role("Java Developer","BN"));
|
||||
LazyList<Model> all = Employee.findAll();
|
||||
System.out.println(all.size());
|
||||
}
|
||||
|
||||
protected void update() {
|
||||
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||
employee.set("last_namea","Choi").saveIt();
|
||||
employee = Employee.findFirst("last_name = ?","Choi");
|
||||
System.out.println(employee.getString("first_name") + " " + employee.getString("last_name"));
|
||||
}
|
||||
|
||||
protected void delete() {
|
||||
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||
employee.delete();
|
||||
employee = Employee.findFirst("last_name = ?","Choi");
|
||||
if(null == employee){
|
||||
System.out.println("No such Employee found!");
|
||||
}
|
||||
}
|
||||
|
||||
protected void deleteCascade() {
|
||||
create();
|
||||
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||
employee.deleteCascade();
|
||||
employee = Employee.findFirst("last_name = ?","C");
|
||||
if(null == employee){
|
||||
System.out.println("No such Employee found!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
|
||||
import org.javalite.activejdbc.Model;
|
||||
|
||||
public class Employee extends Model {
|
||||
|
||||
public Employee(){
|
||||
|
||||
}
|
||||
|
||||
public Employee(String firstName, String lastName, String gender, String createdBy) {
|
||||
set("first_name1",firstName);
|
||||
set("last_name",lastName);
|
||||
set("gender",gender);
|
||||
set("created_by",createdBy);
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return getString("last_name");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
|
||||
import org.javalite.activejdbc.Model;
|
||||
import org.javalite.activejdbc.annotations.Table;
|
||||
|
||||
@Table("EMP_ROLES")
|
||||
public class Role extends Model {
|
||||
|
||||
public Role(){
|
||||
|
||||
}
|
||||
|
||||
public Role(String role,String createdBy){
|
||||
set("role_name",role);
|
||||
set("created_by",createdBy);
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return getString("role_name");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
# noinspection SqlNoDataSourceInspectionForFile
|
||||
|
||||
create table organisation.employees
|
||||
(
|
||||
id int not null auto_increment
|
||||
primary key,
|
||||
first_name varchar(100) not null,
|
||||
last_name varchar(100) not null,
|
||||
gender varchar(1) not null,
|
||||
created_at datetime not null,
|
||||
updated_at datetime null,
|
||||
created_by varchar(100) not null,
|
||||
updated_by varchar(100) null
|
||||
)ENGINE = InnoDB DEFAULT CHARSET = utf8;
|
||||
|
||||
create table organisation.emp_roles
|
||||
(
|
||||
id int not null auto_increment primary key,
|
||||
employee_id int not null,
|
||||
role_name varchar(100) not null,
|
||||
created_at datetime not null,
|
||||
updated_at datetime null,
|
||||
created_by varchar(100) not null,
|
||||
updated_by varchar(100) null
|
||||
)ENGINE = InnoDB DEFAULT CHARSET = utf8;
|
||||
@@ -0,0 +1,10 @@
|
||||
development.driver=com.mysql.jdbc.Driver
|
||||
development.username=root
|
||||
development.password=123456
|
||||
development.url=jdbc:mysql://localhost/organisation
|
||||
|
||||
|
||||
development.test.driver=com.mysql.jdbc.Driver
|
||||
development.test.username=root
|
||||
development.test.password=123456
|
||||
development.test.url=jdbc:mysql://localhost/organisation_test
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
import com.baeldung.model.Role;
|
||||
import org.javalite.activejdbc.test.DBSpec;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ActiveJDBCAppManualTest extends DBSpec
|
||||
{
|
||||
@Test
|
||||
public void ifEmployeeCreated_thenIsValid() {
|
||||
Employee employee = new Employee("B", "N", "M", "BN");
|
||||
the(employee).shouldBe("valid");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifEmployeeCreatedWithRoles_thenShouldPersist() {
|
||||
Employee employee = new Employee("B", "N", "M", "BN");
|
||||
employee.saveIt();
|
||||
employee.add(new Role("Java Developer","BN"));
|
||||
employee.add(new Role("Lead Java Developer","BN"));
|
||||
a(Role.count()).shouldBeEqual(2);
|
||||
List<Role> roles = employee.getAll(Role.class).orderBy("created_at");
|
||||
the(roles.get(0).getRoleName()).shouldBeEqual("Java Developer");
|
||||
the(roles.get(1).getRoleName()).shouldBeEqual("Lead Java Developer");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifEmployeeCreatedWithRoles_whenNameUpdated_thenShouldShowNewName() {
|
||||
Employee employee = new Employee("Binesh", "N", "M", "BN");
|
||||
employee.saveIt();
|
||||
employee.add(new Role("Java Developer","BN"));
|
||||
employee.add(new Role("Lead Java Developer","BN"));
|
||||
employee = Employee.findFirst("first_name = ?", "Binesh");
|
||||
employee.set("last_name","Narayanan").saveIt();
|
||||
Employee updated = Employee.findFirst("first_name = ?", "Binesh");
|
||||
the(updated.getLastName()).shouldBeEqual("Narayanan");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ifEmployeeCreatedWithRoles_whenDeleted_thenShouldNotBeFound() {
|
||||
Employee employee = new Employee("Binesh", "N", "M", "BN");
|
||||
employee.saveIt();
|
||||
employee.add(new Role("Java Developer","BN"));
|
||||
employee.delete();
|
||||
employee = Employee.findFirst("first_name = ?", "Binesh");
|
||||
the(employee).shouldBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Advanced Querying in Apache Cayenne](http://www.baeldung.com/apache-cayenne-query)
|
||||
- [Introduction to Apache Cayenne ORM](http://www.baeldung.com/apache-cayenne-orm)
|
||||
@@ -0,0 +1,49 @@
|
||||
<?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>
|
||||
|
||||
<artifactId>apache-cayenne</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>apache-cayenne</name>
|
||||
<description>Introduction to Apache Cayenne</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cayenne</groupId>
|
||||
<artifactId>cayenne-server</artifactId>
|
||||
<version>${cayenne.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.connector.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.cayenne.plugins</groupId>
|
||||
<artifactId>cayenne-modeler-maven-plugin</artifactId>
|
||||
<version>${cayenne.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<mysql.connector.version>5.1.44</mysql.connector.version>
|
||||
<cayenne.version>4.0.M5</cayenne.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.apachecayenne.persistent;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.auto._Article;
|
||||
|
||||
public class Article extends _Article {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.apachecayenne.persistent;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.auto._Author;
|
||||
|
||||
public class Author extends _Author {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.apachecayenne.persistent.auto;
|
||||
|
||||
import org.apache.cayenne.CayenneDataObject;
|
||||
import org.apache.cayenne.exp.Property;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.Author;
|
||||
|
||||
/**
|
||||
* Class _Article was generated by Cayenne.
|
||||
* It is probably a good idea to avoid changing this class manually,
|
||||
* since it may be overwritten next time code is regenerated.
|
||||
* If you need to make any customizations, please use subclass.
|
||||
*/
|
||||
public abstract class _Article extends CayenneDataObject {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final String ID_PK_COLUMN = "id";
|
||||
|
||||
public static final Property<String> CONTENT = Property.create("content", String.class);
|
||||
public static final Property<String> TITLE = Property.create("title", String.class);
|
||||
public static final Property<Author> AUTHOR = Property.create("author", Author.class);
|
||||
|
||||
public void setContent(String content) {
|
||||
writeProperty("content", content);
|
||||
}
|
||||
public String getContent() {
|
||||
return (String)readProperty("content");
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
writeProperty("title", title);
|
||||
}
|
||||
public String getTitle() {
|
||||
return (String)readProperty("title");
|
||||
}
|
||||
|
||||
public void setAuthor(Author author) {
|
||||
setToOneTarget("author", author, true);
|
||||
}
|
||||
|
||||
public Author getAuthor() {
|
||||
return (Author)readProperty("author");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.apachecayenne.persistent.auto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.cayenne.CayenneDataObject;
|
||||
import org.apache.cayenne.exp.Property;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.Article;
|
||||
|
||||
/**
|
||||
* Class _Author was generated by Cayenne.
|
||||
* It is probably a good idea to avoid changing this class manually,
|
||||
* since it may be overwritten next time code is regenerated.
|
||||
* If you need to make any customizations, please use subclass.
|
||||
*/
|
||||
public abstract class _Author extends CayenneDataObject {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public static final String ID_PK_COLUMN = "id";
|
||||
|
||||
public static final Property<String> NAME = Property.create("name", String.class);
|
||||
public static final Property<List<Article>> ARTICLES = Property.create("articles", List.class);
|
||||
|
||||
public void setName(String name) {
|
||||
writeProperty("name", name);
|
||||
}
|
||||
public String getName() {
|
||||
return (String)readProperty("name");
|
||||
}
|
||||
|
||||
public void addToArticles(Article obj) {
|
||||
addToManyTarget("articles", obj, true);
|
||||
}
|
||||
public void removeFromArticles(Article obj) {
|
||||
removeToManyTarget("articles", obj, true);
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<Article> getArticles() {
|
||||
return (List<Article>)readProperty("articles");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<domain project-version="9">
|
||||
<map name="datamap"/>
|
||||
|
||||
<node name="datanode"
|
||||
factory="org.apache.cayenne.configuration.server.XMLPoolingDataSourceFactory"
|
||||
schema-update-strategy="org.apache.cayenne.access.dbsync.CreateIfNoSchemaStrategy"
|
||||
>
|
||||
<map-ref name="datamap"/>
|
||||
<data-source>
|
||||
<driver value="com.mysql.jdbc.Driver"/>
|
||||
<url value="jdbc:mysql://localhost:3306/intro_cayenne"/>
|
||||
<connectionPool min="1" max="1"/>
|
||||
<login userName="root" password="root"/>
|
||||
</data-source>
|
||||
</node>
|
||||
</domain>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-map xmlns="http://cayenne.apache.org/schema/9/modelMap"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://cayenne.apache.org/schema/9/modelMap http://cayenne.apache.org/schema/9/modelMap.xsd"
|
||||
project-version="9">
|
||||
<property name="defaultPackage" value="com.baeldung.apachecayenne.persistent"/>
|
||||
<db-entity name="article" catalog="intro_cayenne">
|
||||
<db-attribute name="author_id" type="INTEGER" isMandatory="true" length="10"/>
|
||||
<db-attribute name="content" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
<db-attribute name="id" type="INTEGER" isPrimaryKey="true" isGenerated="true" isMandatory="true" length="10"/>
|
||||
<db-attribute name="title" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
</db-entity>
|
||||
<db-entity name="author" catalog="intro_cayenne">
|
||||
<db-attribute name="id" type="INTEGER" isPrimaryKey="true" isGenerated="true" isMandatory="true" length="10"/>
|
||||
<db-attribute name="name" type="VARCHAR" isMandatory="true" length="254"/>
|
||||
</db-entity>
|
||||
<obj-entity name="Article" className="com.baeldung.apachecayenne.persistent.Article" dbEntityName="article">
|
||||
<obj-attribute name="content" type="java.lang.String" db-attribute-path="content"/>
|
||||
<obj-attribute name="title" type="java.lang.String" db-attribute-path="title"/>
|
||||
</obj-entity>
|
||||
<obj-entity name="Author" className="com.baeldung.apachecayenne.persistent.Author" dbEntityName="author">
|
||||
<obj-attribute name="name" type="java.lang.String" db-attribute-path="name"/>
|
||||
</obj-entity>
|
||||
<db-relationship name="author" source="article" target="author" toMany="false">
|
||||
<db-attribute-pair source="author_id" target="id"/>
|
||||
</db-relationship>
|
||||
<db-relationship name="articles" source="author" target="article" toMany="true">
|
||||
<db-attribute-pair source="id" target="author_id"/>
|
||||
</db-relationship>
|
||||
<obj-relationship name="author" source="Article" target="Author" deleteRule="Nullify" db-relationship-path="author"/>
|
||||
<obj-relationship name="articles" source="Author" target="Article" deleteRule="Deny" db-relationship-path="articles"/>
|
||||
</data-map>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package com.baeldung.apachecayenne;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.Author;
|
||||
import org.apache.cayenne.ObjectContext;
|
||||
import org.apache.cayenne.QueryResponse;
|
||||
import org.apache.cayenne.configuration.server.ServerRuntime;
|
||||
import org.apache.cayenne.exp.Expression;
|
||||
import org.apache.cayenne.exp.ExpressionFactory;
|
||||
import org.apache.cayenne.query.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CayenneAdvancedOperationLiveTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupTheCayenneContext() {
|
||||
ServerRuntime cayenneRuntime = ServerRuntime.builder()
|
||||
.addConfig("cayenne-project.xml")
|
||||
.build();
|
||||
context = cayenneRuntime.newContext();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void saveThreeAuthors() {
|
||||
Author authorOne = context.newObject(Author.class);
|
||||
authorOne.setName("Paul Xavier");
|
||||
Author authorTwo = context.newObject(Author.class);
|
||||
authorTwo.setName("pAuL Smith");
|
||||
Author authorThree = context.newObject(Author.class);
|
||||
authorThree.setName("Vicky Sarra");
|
||||
context.commitChanges();
|
||||
}
|
||||
|
||||
@After
|
||||
public void deleteAllAuthors() {
|
||||
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
|
||||
context.performGenericQuery(deleteAuthors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindAllSQLTmplt_thenWeGetThreeAuthors() {
|
||||
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author");
|
||||
List<Author> authors = context.performQuery(select);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindByNameSQLTmplt_thenWeGetOneAuthor() {
|
||||
SQLTemplate select = new SQLTemplate(Author.class, "select * from Author where name = 'Vicky Sarra'");
|
||||
List<Author> authors = context.performQuery(select);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenLikeSltQry_thenWeGetOneAuthor() {
|
||||
Expression qualifier = ExpressionFactory.likeExp(Author.NAME.getName(), "Paul%");
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authorsTwo = context.performQuery(query);
|
||||
|
||||
assertEquals(authorsTwo.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenCtnsIgnorCaseSltQry_thenWeGetTwoAuthors() {
|
||||
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul");
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
assertEquals(authors.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenCtnsIgnorCaseEndsWSltQry_thenWeGetTwoAuthors() {
|
||||
Expression qualifier = ExpressionFactory.containsIgnoreCaseExp(Author.NAME.getName(), "Paul")
|
||||
.andExp(ExpressionFactory.endsWithExp(Author.NAME.getName(), "h"));
|
||||
SelectQuery query = new SelectQuery(Author.class, qualifier);
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "pAuL Smith");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenAscOrderingSltQry_thenWeGetOrderedAuthors() {
|
||||
SelectQuery query = new SelectQuery(Author.class);
|
||||
query.addOrdering(Author.NAME.asc());
|
||||
|
||||
List<Author> authors = query.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
assertEquals(firstAuthor.getName(), "Paul Xavier");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenDescOrderingSltQry_thenWeGetOrderedAuthors() {
|
||||
SelectQuery query = new SelectQuery(Author.class);
|
||||
query.addOrdering(Author.NAME.desc());
|
||||
|
||||
List<Author> authors = query.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
assertEquals(firstAuthor.getName(), "pAuL Smith");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_onContainsObjS_thenWeGetOneRecord() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.contains("Paul"))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenLikeObjS_thenWeGetTwoAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.likeIgnoreCase("Paul%"))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenEndsWithObjS_thenWeGetOrderedAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.endsWith("Sarra"))
|
||||
.select(context);
|
||||
Author firstAuthor = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(firstAuthor.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenInObjS_thenWeGetAuthors() {
|
||||
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith", "Vicky Sarra");
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.in(names))
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenNinObjS_thenWeGetAuthors() {
|
||||
List<String> names = Arrays.asList("Paul Xavier", "pAuL Smith");
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.nin(names))
|
||||
.select(context);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenIsNotNullObjS_thenWeGetAuthors() {
|
||||
List<Author> authors = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.isNotNull())
|
||||
.select(context);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindAllEJBQL_thenWeGetThreeAuthors() {
|
||||
EJBQLQuery query = new EJBQLQuery("select a FROM Author a");
|
||||
List<Author> authors = context.performQuery(query);
|
||||
|
||||
assertEquals(authors.size(), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenFindByNameEJBQL_thenWeGetOneAuthor() {
|
||||
EJBQLQuery query = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Sarra'");
|
||||
List<Author> authors = context.performQuery(query);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertEquals(authors.size(), 1);
|
||||
assertEquals(author.getName(), "Vicky Sarra");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenUpdadingByNameEJBQL_thenWeGetTheUpdatedAuthor() {
|
||||
EJBQLQuery query = new EJBQLQuery("UPDATE Author AS a SET a.name = 'Vicky Edison' WHERE a.name = 'Vicky Sarra'");
|
||||
QueryResponse queryResponse = context.performGenericQuery(query);
|
||||
|
||||
EJBQLQuery queryUpdatedAuthor = new EJBQLQuery("select a FROM Author a WHERE a.name = 'Vicky Edison'");
|
||||
List<Author> authors = context.performQuery(queryUpdatedAuthor);
|
||||
Author author = authors.get(0);
|
||||
|
||||
assertNotNull(author);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenSeletingNamesEJBQL_thenWeGetListWithSizeThree() {
|
||||
String [] args = {"Paul Xavier", "pAuL Smith", "Vicky Sarra"};
|
||||
List<String> names = Arrays.asList(args);
|
||||
EJBQLQuery query = new EJBQLQuery("select a.name FROM Author a");
|
||||
List<String> nameList = context.performQuery(query);
|
||||
|
||||
Collections.sort(names);
|
||||
Collections.sort(nameList);
|
||||
|
||||
assertEquals(names.size(), 3);
|
||||
assertEquals(nameList.size(), 3);
|
||||
assertEquals(names, nameList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenDeletingAllWithEJB_thenWeGetNoAuthor() {
|
||||
EJBQLQuery deleteQuery = new EJBQLQuery("delete FROM Author");
|
||||
EJBQLQuery findAllQuery = new EJBQLQuery("select a FROM Author a");
|
||||
|
||||
context.performQuery(deleteQuery);
|
||||
List<Author> objects = context.performQuery(findAllQuery);
|
||||
|
||||
assertEquals(objects.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenInsertingSQLExec_thenWeGetNewAuthor() {
|
||||
int inserted = SQLExec
|
||||
.query("INSERT INTO Author (name) VALUES ('Baeldung')")
|
||||
.update(context);
|
||||
|
||||
assertEquals(inserted, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthors_whenUpdatingSQLExec_thenItsUpdated() {
|
||||
int updated = SQLExec
|
||||
.query("UPDATE Author SET name = 'Baeldung' WHERE name = 'Vicky Sarra'")
|
||||
.update(context);
|
||||
|
||||
assertEquals(updated, 1);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.apachecayenne;
|
||||
|
||||
import com.baeldung.apachecayenne.persistent.Article;
|
||||
import com.baeldung.apachecayenne.persistent.Author;
|
||||
import org.apache.cayenne.ObjectContext;
|
||||
import org.apache.cayenne.configuration.server.ServerRuntime;
|
||||
import org.apache.cayenne.query.ObjectSelect;
|
||||
import org.apache.cayenne.query.SQLTemplate;
|
||||
import org.junit.After;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
|
||||
public class CayenneOperationLiveTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupTheCayenneContext() {
|
||||
ServerRuntime cayenneRuntime = ServerRuntime.builder()
|
||||
.addConfig("cayenne-project.xml")
|
||||
.build();
|
||||
context = cayenneRuntime.newContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void deleteAllRecords() {
|
||||
SQLTemplate deleteArticles = new SQLTemplate(Article.class, "delete from article");
|
||||
SQLTemplate deleteAuthors = new SQLTemplate(Author.class, "delete from author");
|
||||
|
||||
context.performGenericQuery(deleteArticles);
|
||||
context.performGenericQuery(deleteAuthors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenInsert_thenWeGetOneRecordInTheDatabase() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setName("Paul");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
long records = ObjectSelect.dataRowQuery(Author.class).selectCount(context);
|
||||
assertEquals(1, records);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenInsert_andQueryByFirstName_thenWeGetTheAuthor() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setName("Paul");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
|
||||
assertEquals("Paul", expectedAuthor.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoAuthor_whenInsert_andQueryAll_thenWeGetTwoAuthors() {
|
||||
Author firstAuthor = context.newObject(Author.class);
|
||||
firstAuthor.setName("Paul");
|
||||
|
||||
Author secondAuthor = context.newObject(Author.class);
|
||||
secondAuthor.setName("Ludovic");
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
List<Author> authors = ObjectSelect.query(Author.class).select(context);
|
||||
assertEquals(2, authors.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenUpdating_thenWeGetAnUpatedeAuthor() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setName("Paul");
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
expectedAuthor.setName("Garcia");
|
||||
context.commitChanges();
|
||||
|
||||
assertEquals(author.getName(), expectedAuthor.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenDeleting_thenWeLostHisDetails() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setName("Paul");
|
||||
context.commitChanges();
|
||||
|
||||
Author savedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.eq("Paul")).selectOne(context);
|
||||
if(savedAuthor != null) {
|
||||
context.deleteObjects(author);
|
||||
context.commitChanges();
|
||||
}
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.eq("Paul")).selectOne(context);
|
||||
assertNull(expectedAuthor);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthor_whenAttachingToArticle_thenTheRelationIsMade() {
|
||||
Author author = context.newObject(Author.class);
|
||||
author.setName("Paul");
|
||||
|
||||
Article article = context.newObject(Article.class);
|
||||
article.setTitle("My post title");
|
||||
article.setContent("The content");
|
||||
article.setAuthor(author);
|
||||
|
||||
context.commitChanges();
|
||||
|
||||
Author expectedAuthor = ObjectSelect.query(Author.class)
|
||||
.where(Author.NAME.eq("Paul"))
|
||||
.selectOne(context);
|
||||
|
||||
Article expectedArticle = (expectedAuthor.getArticles()).get(0);
|
||||
assertEquals(article.getTitle(), expectedArticle.getTitle());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
.classpath
|
||||
.project
|
||||
.settings
|
||||
target/
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)
|
||||
- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks)
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS `employee` (
|
||||
|
||||
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
`name` varchar(20),
|
||||
`email` varchar(50),
|
||||
`date_of_birth` timestamp
|
||||
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
|
||||
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS `department` (
|
||||
|
||||
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
`name` varchar(20)
|
||||
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
|
||||
|
||||
ALTER TABLE `employee` ADD `dept_id` int AFTER `email`;
|
||||
@@ -0,0 +1,5 @@
|
||||
flyway.user=sa
|
||||
flyway.password=
|
||||
flyway.schemas=app-db
|
||||
flyway.url=jdbc:h2:mem:DATABASE
|
||||
flyway.locations=filesystem:db/migration
|
||||
@@ -0,0 +1,71 @@
|
||||
<?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>
|
||||
<artifactId>flyway</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>flyway</name>
|
||||
<description>Flyway Callbacks Demo</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-1</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
<version>${flyway-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-maven-plugin</artifactId>
|
||||
<version>${flyway-maven-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<flyway-core.version>5.0.2</flyway-core.version>
|
||||
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
|
||||
<h2.version>1.4.195</h2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.flywaycallbacks;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.flywaydb.core.api.MigrationInfo;
|
||||
import org.flywaydb.core.api.callback.BaseFlywayCallback;
|
||||
|
||||
public class ExampleFlywayCallback extends BaseFlywayCallback {
|
||||
|
||||
private Log log = LogFactory.getLog(getClass());
|
||||
|
||||
@Override
|
||||
public void afterEachMigrate(Connection connection, MigrationInfo info) {
|
||||
log.info("> afterEachMigrate");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterMigrate(Connection connection) {
|
||||
log.info("> afterMigrate");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEachMigrate(Connection connection, MigrationInfo info) {
|
||||
log.info("> beforeEachMigrate");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeMigrate(Connection connection) {
|
||||
log.info("> beforeMigrate");
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.flywaycallbacks;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class FlywayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(FlywayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SELECT 1
|
||||
@@ -0,0 +1 @@
|
||||
SELECT 1
|
||||
@@ -0,0 +1,5 @@
|
||||
create table table_one (
|
||||
id numeric,
|
||||
name varchar(50),
|
||||
constraint pk_table_one primary key (id)
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
create table table_two (
|
||||
id numeric,
|
||||
name varchar(50),
|
||||
constraint pk_table_two primary key (id)
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.flywaycallbacks;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.annotation.DirtiesContext.ClassMode;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
|
||||
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
|
||||
public class FlywayApplicationUnitTest {
|
||||
|
||||
private Log log = LogFactory.getLog(getClass());
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
@Test
|
||||
public void migrateWithNoCallbacks() {
|
||||
logTestBoundary("migrateWithNoCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration");
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithJavaCallbacks() {
|
||||
logTestBoundary("migrateWithJavaCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration");
|
||||
flyway.setCallbacks(new ExampleFlywayCallback());
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithSqlCallbacks() {
|
||||
logTestBoundary("migrateWithSqlCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration", "db/callbacks");
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void migrateWithSqlAndJavaCallbacks() {
|
||||
logTestBoundary("migrateWithSqlAndJavaCallbacks");
|
||||
Flyway flyway = new Flyway();
|
||||
flyway.setDataSource(dataSource);
|
||||
flyway.setLocations("db/migration", "db/callbacks");
|
||||
flyway.setCallbacks(new ExampleFlywayCallback());
|
||||
flyway.migrate();
|
||||
}
|
||||
|
||||
private void logTestBoundary(String testName) {
|
||||
System.out.println("\n");
|
||||
log.info("> " + testName);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.flywaycallbacks;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||
|
||||
@Configuration
|
||||
public class FlywayCallbackTestConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource createDatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2)
|
||||
.setName("DATABASE")
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [HBase with Java](http://www.baeldung.com/hbase)
|
||||
@@ -0,0 +1,38 @@
|
||||
<?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>
|
||||
<artifactId>hbase</artifactId>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.hbase</groupId>
|
||||
<artifactId>hbase-client</artifactId>
|
||||
<version>${hbase.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.hbase</groupId>
|
||||
<artifactId>hbase</artifactId>
|
||||
<version>${hbase.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hbase.version>1.3.1</hbase.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package org.baeldung.hbase;
|
||||
|
||||
import org.apache.hadoop.conf.Configuration;
|
||||
import org.apache.hadoop.hbase.HColumnDescriptor;
|
||||
import org.apache.hadoop.hbase.HTableDescriptor;
|
||||
import org.apache.hadoop.hbase.TableName;
|
||||
import org.apache.hadoop.hbase.client.*;
|
||||
import org.apache.hadoop.hbase.filter.*;
|
||||
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
|
||||
import org.apache.hadoop.hbase.filter.FilterList.Operator;
|
||||
import org.apache.hadoop.hbase.util.Bytes;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class HBaseClientOperations {
|
||||
private final static byte[] cellData = Bytes.toBytes("cell_data");
|
||||
|
||||
/**
|
||||
* Drop tables if this value is set true.
|
||||
*/
|
||||
static boolean INITIALIZE_AT_FIRST = true;
|
||||
|
||||
/**
|
||||
* <table>
|
||||
* <tr>
|
||||
* <tb>Row1</tb> <tb>Family1:Qualifier1</tb> <tb>Family1:Qualifier2</tb>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <tb>Row2</tb> <tb>Family1:Qualifier1</tb> <tb>Family2:Qualifier3</tb>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <tb>Row3</tb> <tb>Family1:Qualifier1</tb> <tb>Family2:Qualifier3</tb>
|
||||
* </tr>
|
||||
* </table>
|
||||
*/
|
||||
private final TableName table1 = TableName.valueOf("Table1");
|
||||
private final String family1 = "Family1";
|
||||
private final String family2 = "Family2";
|
||||
|
||||
private final byte[] row1 = Bytes.toBytes("Row1");
|
||||
private final byte[] row2 = Bytes.toBytes("Row2");
|
||||
private final byte[] row3 = Bytes.toBytes("Row3");
|
||||
private final byte[] qualifier1 = Bytes.toBytes("Qualifier1");
|
||||
private final byte[] qualifier2 = Bytes.toBytes("Qualifier2");
|
||||
private final byte[] qualifier3 = Bytes.toBytes("Qualifier3");
|
||||
|
||||
private void createTable(Admin admin) throws IOException {
|
||||
HTableDescriptor desc = new HTableDescriptor(table1);
|
||||
desc.addFamily(new HColumnDescriptor(family1));
|
||||
desc.addFamily(new HColumnDescriptor(family2));
|
||||
admin.createTable(desc);
|
||||
}
|
||||
|
||||
private void delete(Table table) throws IOException {
|
||||
final byte[] rowToBeDeleted = Bytes.toBytes("RowToBeDeleted");
|
||||
System.out.println("\n*** DELETE ~Insert data and then delete it~ ***");
|
||||
|
||||
System.out.println("Inserting a data to be deleted later.");
|
||||
Put put = new Put(rowToBeDeleted);
|
||||
put.addColumn(family1.getBytes(), qualifier1, cellData);
|
||||
table.put(put);
|
||||
|
||||
Get get = new Get(rowToBeDeleted);
|
||||
Result result = table.get(get);
|
||||
byte[] value = result.getValue(family1.getBytes(), qualifier1);
|
||||
System.out.println("Fetch the data: " + Bytes.toString(value));
|
||||
assert Arrays.equals(cellData, value);
|
||||
|
||||
System.out.println("Deleting");
|
||||
Delete delete = new Delete(rowToBeDeleted);
|
||||
delete.addColumn(family1.getBytes(), qualifier1);
|
||||
table.delete(delete);
|
||||
|
||||
result = table.get(get);
|
||||
value = result.getValue(family1.getBytes(), qualifier1);
|
||||
System.out.println("Fetch the data: " + Bytes.toString(value));
|
||||
assert Arrays.equals(null, value);
|
||||
|
||||
System.out.println("Done. ");
|
||||
}
|
||||
|
||||
private void deleteTable(Admin admin) throws IOException {
|
||||
if (admin.tableExists(table1)) {
|
||||
admin.disableTable(table1);
|
||||
admin.deleteTable(table1);
|
||||
}
|
||||
}
|
||||
|
||||
private void filters(Table table) throws IOException {
|
||||
System.out.println("\n*** FILTERS ~ scanning with filters to fetch a row of which key is larget than \"Row1\"~ ***");
|
||||
Filter filter1 = new PrefixFilter(row1);
|
||||
Filter filter2 = new QualifierFilter(CompareOp.GREATER_OR_EQUAL, new BinaryComparator(
|
||||
qualifier1));
|
||||
|
||||
List<Filter> filters = Arrays.asList(filter1, filter2);
|
||||
|
||||
Scan scan = new Scan();
|
||||
scan.setFilter(new FilterList(Operator.MUST_PASS_ALL, filters));
|
||||
|
||||
try (ResultScanner scanner = table.getScanner(scan)) {
|
||||
int i = 0;
|
||||
for (Result result : scanner) {
|
||||
System.out.println("Filter " + scan.getFilter() + " matched row: " + result);
|
||||
i++;
|
||||
}
|
||||
assert i == 2 : "This filtering sample should return 1 row but was " + i + ".";
|
||||
}
|
||||
System.out.println("Done. ");
|
||||
}
|
||||
|
||||
private void get(Table table) throws IOException {
|
||||
System.out.println("\n*** GET example ~fetching the data in Family1:Qualifier1~ ***");
|
||||
|
||||
Get g = new Get(row1);
|
||||
Result r = table.get(g);
|
||||
byte[] value = r.getValue(family1.getBytes(), qualifier1);
|
||||
|
||||
System.out.println("Fetched value: " + Bytes.toString(value));
|
||||
assert Arrays.equals(cellData, value);
|
||||
System.out.println("Done. ");
|
||||
}
|
||||
|
||||
private void put(Admin admin, Table table) throws IOException {
|
||||
System.out.println("\n*** PUT example ~inserting \"cell-data\" into Family1:Qualifier1 of Table1 ~ ***");
|
||||
|
||||
// Row1 => Family1:Qualifier1, Family1:Qualifier2
|
||||
Put p = new Put(row1);
|
||||
p.addImmutable(family1.getBytes(), qualifier1, cellData);
|
||||
p.addImmutable(family1.getBytes(), qualifier2, cellData);
|
||||
table.put(p);
|
||||
|
||||
// Row2 => Family1:Qualifier1, Family2:Qualifier3
|
||||
p = new Put(row2);
|
||||
p.addImmutable(family1.getBytes(), qualifier1, cellData);
|
||||
p.addImmutable(family2.getBytes(), qualifier3, cellData);
|
||||
table.put(p);
|
||||
|
||||
// Row3 => Family1:Qualifier1, Family2:Qualifier3
|
||||
p = new Put(row3);
|
||||
p.addImmutable(family1.getBytes(), qualifier1, cellData);
|
||||
p.addImmutable(family2.getBytes(), qualifier3, cellData);
|
||||
table.put(p);
|
||||
|
||||
admin.disableTable(table1);
|
||||
try {
|
||||
HColumnDescriptor desc = new HColumnDescriptor(row1);
|
||||
admin.addColumn(table1, desc);
|
||||
System.out.println("Success.");
|
||||
} catch (Exception e) {
|
||||
System.out.println("Failed.");
|
||||
System.out.println(e.getMessage());
|
||||
} finally {
|
||||
admin.enableTable(table1);
|
||||
}
|
||||
System.out.println("Done. ");
|
||||
}
|
||||
|
||||
public void run(Configuration config) throws IOException {
|
||||
try (Connection connection = ConnectionFactory.createConnection(config)) {
|
||||
|
||||
Admin admin = connection.getAdmin();
|
||||
if (INITIALIZE_AT_FIRST) {
|
||||
deleteTable(admin);
|
||||
}
|
||||
|
||||
if (!admin.tableExists(table1)) {
|
||||
createTable(admin);
|
||||
}
|
||||
|
||||
Table table = connection.getTable(table1);
|
||||
put(admin, table);
|
||||
get(table);
|
||||
scan(table);
|
||||
filters(table);
|
||||
delete(table);
|
||||
}
|
||||
}
|
||||
|
||||
private void scan(Table table) throws IOException {
|
||||
System.out.println("\n*** SCAN example ~fetching data in Family1:Qualifier1 ~ ***");
|
||||
|
||||
Scan scan = new Scan();
|
||||
scan.addColumn(family1.getBytes(), qualifier1);
|
||||
|
||||
try (ResultScanner scanner = table.getScanner(scan)) {
|
||||
for (Result result : scanner)
|
||||
System.out.println("Found row: " + result);
|
||||
}
|
||||
System.out.println("Done.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.baeldung.hbase;
|
||||
|
||||
|
||||
import com.google.protobuf.ServiceException;
|
||||
import org.apache.hadoop.conf.Configuration;
|
||||
import org.apache.hadoop.fs.Path;
|
||||
import org.apache.hadoop.hbase.HBaseConfiguration;
|
||||
import org.apache.hadoop.hbase.MasterNotRunningException;
|
||||
import org.apache.hadoop.hbase.client.HBaseAdmin;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
//install hbase locally & hbase master start
|
||||
public class HbaseClientExample {
|
||||
|
||||
public static void main(String[] args) throws IOException, ServiceException {
|
||||
new HbaseClientExample().connect();
|
||||
}
|
||||
|
||||
private void connect() throws IOException, ServiceException {
|
||||
Configuration config = HBaseConfiguration.create();
|
||||
|
||||
String path = this.getClass().getClassLoader().getResource("hbase-site.xml").getPath();
|
||||
|
||||
config.addResource(new Path(path));
|
||||
|
||||
try {
|
||||
HBaseAdmin.checkHBaseAvailable(config);
|
||||
} catch (MasterNotRunningException e) {
|
||||
System.out.println("HBase is not running." + e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
HBaseClientOperations HBaseClientOperations = new HBaseClientOperations();
|
||||
HBaseClientOperations.run(config);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
|
||||
<configuration>
|
||||
<property>
|
||||
<name>hbase.zookeeper.quorum</name>
|
||||
<value>localhost</value>
|
||||
</property>
|
||||
<property>
|
||||
<name>hbase.zookeeper.property.clientPort</name>
|
||||
<value>2181</value>
|
||||
</property>
|
||||
</configuration>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,19 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping)
|
||||
- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers)
|
||||
- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time)
|
||||
- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance)
|
||||
- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy)
|
||||
- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial)
|
||||
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
|
||||
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
|
||||
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
|
||||
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
|
||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
||||
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
|
||||
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
|
||||
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
|
||||
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
|
||||
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
|
||||
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
|
||||
@@ -0,0 +1,68 @@
|
||||
<?xml version="1.0"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>hibernate5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2database.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-spatial</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.vorburger.mariaDB4j</groupId>
|
||||
<artifactId>mariaDB4j</artifactId>
|
||||
<version>${mariaDB4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>hibernate5</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.2.Final</hibernate.version>
|
||||
<mysql.version>6.0.6</mysql.version>
|
||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<h2database.version>1.4.196</h2database.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pessimisticlocking.Individual;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pojo.*;
|
||||
import com.baeldung.hibernate.pojo.Person;
|
||||
import com.baeldung.hibernate.pojo.inheritance.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Course;
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
import com.baeldung.hibernate.pojo.OrderEntry;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryPK;
|
||||
import com.baeldung.hibernate.pojo.Person;
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import com.baeldung.hibernate.pojo.PointEntity;
|
||||
import com.baeldung.hibernate.pojo.PolygonEntity;
|
||||
import com.baeldung.hibernate.pojo.Product;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
import com.baeldung.hibernate.pojo.User;
|
||||
import com.baeldung.hibernate.pojo.UserProfile;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Animal;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Bag;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Book;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Car;
|
||||
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
|
||||
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pen;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pet;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addPackage("com.baeldung.hibernate.pojo");
|
||||
metadataSources.addAnnotatedClass(Employee.class);
|
||||
metadataSources.addAnnotatedClass(Phone.class);
|
||||
metadataSources.addAnnotatedClass(EntityDescription.class);
|
||||
metadataSources.addAnnotatedClass(TemporalValues.class);
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
metadataSources.addAnnotatedClass(Student.class);
|
||||
metadataSources.addAnnotatedClass(Course.class);
|
||||
metadataSources.addAnnotatedClass(Product.class);
|
||||
metadataSources.addAnnotatedClass(OrderEntryPK.class);
|
||||
metadataSources.addAnnotatedClass(OrderEntry.class);
|
||||
metadataSources.addAnnotatedClass(OrderEntryIdClass.class);
|
||||
metadataSources.addAnnotatedClass(UserProfile.class);
|
||||
metadataSources.addAnnotatedClass(Book.class);
|
||||
metadataSources.addAnnotatedClass(MyEmployee.class);
|
||||
metadataSources.addAnnotatedClass(MyProduct.class);
|
||||
metadataSources.addAnnotatedClass(Pen.class);
|
||||
metadataSources.addAnnotatedClass(Person.class);
|
||||
metadataSources.addAnnotatedClass(Animal.class);
|
||||
metadataSources.addAnnotatedClass(Pet.class);
|
||||
metadataSources.addAnnotatedClass(Vehicle.class);
|
||||
metadataSources.addAnnotatedClass(Car.class);
|
||||
metadataSources.addAnnotatedClass(Bag.class);
|
||||
metadataSources.addAnnotatedClass(PointEntity.class);
|
||||
metadataSources.addAnnotatedClass(PolygonEntity.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
|
||||
metadataSources.addAnnotatedClass(Individual.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
|
||||
metadataSources.addAnnotatedClass(DeptEmployee.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
public class UnsupportedTenancyException extends Exception {
|
||||
public UnsupportedTenancyException (String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.converters;
|
||||
|
||||
import javax.persistence.AttributeConverter;
|
||||
import javax.persistence.Converter;
|
||||
|
||||
import com.baeldung.hibernate.pojo.PersonName;
|
||||
|
||||
@Converter
|
||||
public class PersonNameConverter implements AttributeConverter<PersonName, String> {
|
||||
|
||||
private static final String SEPARATOR = ", ";
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(PersonName personName) {
|
||||
if (personName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (personName.getSurname() != null && !personName.getSurname()
|
||||
.isEmpty()) {
|
||||
sb.append(personName.getSurname());
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
|
||||
if (personName.getName() != null && !personName.getName()
|
||||
.isEmpty()) {
|
||||
sb.append(personName.getName());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersonName convertToEntityAttribute(String dbPersonName) {
|
||||
if (dbPersonName == null || dbPersonName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] pieces = dbPersonName.split(SEPARATOR);
|
||||
|
||||
if (pieces == null || pieces.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PersonName personName = new PersonName();
|
||||
String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
|
||||
if (dbPersonName.contains(SEPARATOR)) {
|
||||
personName.setSurname(firstPiece);
|
||||
|
||||
if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) {
|
||||
personName.setName(pieces[1]);
|
||||
}
|
||||
} else {
|
||||
personName.setName(firstPiece);
|
||||
}
|
||||
|
||||
return personName;
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.hibernate.entities;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Department {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy="department")
|
||||
private List<DeptEmployee> employees;
|
||||
|
||||
public Department(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<DeptEmployee> getEmployees() {
|
||||
return employees;
|
||||
}
|
||||
|
||||
public void setEmployees(List<DeptEmployee> employees) {
|
||||
this.employees = employees;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.hibernate.entities;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class DeptEmployee {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String employeeNumber;
|
||||
|
||||
private String designation;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
private Department department;
|
||||
|
||||
public DeptEmployee(String name, String employeeNumber, Department department) {
|
||||
this.name = name;
|
||||
this.employeeNumber = employeeNumber;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmployeeNumber() {
|
||||
return employeeNumber;
|
||||
}
|
||||
|
||||
public void setEmployeeNumber(String employeeNumber) {
|
||||
this.employeeNumber = employeeNumber;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Department getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public void setDepartment(Department department) {
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public String getDesignation() {
|
||||
return designation;
|
||||
}
|
||||
|
||||
public void setDesignation(String designation) {
|
||||
this.designation = designation;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import org.hibernate.EmptyInterceptor;
|
||||
import org.hibernate.type.Type;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.hibernate.interceptors.entity.User;
|
||||
|
||||
public class CustomInterceptor extends EmptyInterceptor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
|
||||
|
||||
@Override
|
||||
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
|
||||
if (entity instanceof User) {
|
||||
logger.info(((User) entity).toString());
|
||||
}
|
||||
return super.onSave(entity, id, state, propertyNames, types);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
|
||||
if (entity instanceof User) {
|
||||
((User) entity).setLastModified(new Date());
|
||||
logger.info(((User) entity).toString());
|
||||
}
|
||||
return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.hibernate.CallbackException;
|
||||
import org.hibernate.EntityMode;
|
||||
import org.hibernate.Interceptor;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.type.Type;
|
||||
|
||||
public class CustomInterceptorImpl implements Interceptor, Serializable {
|
||||
|
||||
@Override
|
||||
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void preFlush(Iterator entities) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postFlush(Iterator entities) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean isTransient(Object entity) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEntityName(Object object) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getEntity(String entityName, Serializable id) throws CallbackException {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransactionBegin(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTransactionCompletion(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterTransactionCompletion(Transaction tx) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String onPrepareStatement(String sql) {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.hibernate.interceptors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.Interceptor;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.SessionFactoryBuilder;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.interceptors.entity.User;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
|
||||
.build();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
|
||||
return getSessionFactory().withOptions()
|
||||
.interceptor(interceptor)
|
||||
.openSession();
|
||||
}
|
||||
|
||||
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.hibernate.interceptors.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.persistence.Basic;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Temporal;
|
||||
import javax.persistence.TemporalType;
|
||||
|
||||
@Entity(name = "hbi_user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
private String name;
|
||||
private String about;
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private Date lastModified;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Date getLastModified() {
|
||||
return lastModified;
|
||||
}
|
||||
|
||||
public void setLastModified(Date lastModified) {
|
||||
this.lastModified = lastModified;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public void setAbout(String about) {
|
||||
this.about = about;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "ZIP")
|
||||
private String zipCode;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Email {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String address;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
private Employee employee;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Employee getEmployee() {
|
||||
return employee;
|
||||
}
|
||||
|
||||
public void setEmployee(Employee employee) {
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
|
||||
private List<Email> emails;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Email> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<Email> emails) {
|
||||
this.emails = emails;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinColumns;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Office {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumns({
|
||||
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
|
||||
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
|
||||
})
|
||||
private Address address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.application;
|
||||
|
||||
import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
|
||||
import com.baeldung.hibernate.jpabootstrap.entities.User;
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
EntityManager entityManager = getJpaEntityManager();
|
||||
User user = entityManager.find(User.class, 1);
|
||||
System.out.println(user);
|
||||
entityManager.getTransaction().begin();
|
||||
user.setName("John");
|
||||
user.setEmail("john@domain.com");
|
||||
entityManager.merge(user);
|
||||
entityManager.getTransaction().commit();
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(new User("Monica", "monica@domain.com"));
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
// additional CRUD operations
|
||||
|
||||
}
|
||||
|
||||
private static class EntityManagerHolder {
|
||||
private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
|
||||
new Class[]{User.class}).getEntityManager();
|
||||
}
|
||||
|
||||
public static EntityManager getJpaEntityManager() {
|
||||
return EntityManagerHolder.ENTITY_MANAGER;
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.config;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import javax.sql.DataSource;
|
||||
import javax.persistence.SharedCacheMode;
|
||||
import javax.persistence.ValidationMode;
|
||||
import javax.persistence.spi.ClassTransformer;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import javax.persistence.spi.PersistenceUnitTransactionType;
|
||||
import org.hibernate.jpa.HibernatePersistenceProvider;
|
||||
|
||||
public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
|
||||
|
||||
public static final String JPA_VERSION = "2.1";
|
||||
private final String persistenceUnitName;
|
||||
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
|
||||
private final List<String> managedClassNames;
|
||||
private final List<String> mappingFileNames = new ArrayList<>();
|
||||
private final Properties properties;
|
||||
private DataSource jtaDataSource;
|
||||
private DataSource nonjtaDataSource;
|
||||
private final List<ClassTransformer> transformers = new ArrayList<>();
|
||||
|
||||
public HibernatePersistenceUnitInfo(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
|
||||
this.persistenceUnitName = persistenceUnitName;
|
||||
this.managedClassNames = managedClassNames;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceUnitName() {
|
||||
return persistenceUnitName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceProviderClassName() {
|
||||
return HibernatePersistenceProvider.class.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersistenceUnitTransactionType getTransactionType() {
|
||||
return transactionType;
|
||||
}
|
||||
|
||||
public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
|
||||
this.jtaDataSource = jtaDataSource;
|
||||
this.nonjtaDataSource = null;
|
||||
transactionType = PersistenceUnitTransactionType.JTA;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource getJtaDataSource() {
|
||||
return jtaDataSource;
|
||||
}
|
||||
|
||||
public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
|
||||
this.nonjtaDataSource = nonJtaDataSource;
|
||||
this.jtaDataSource = null;
|
||||
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource getNonJtaDataSource() {
|
||||
return nonjtaDataSource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getMappingFileNames() {
|
||||
return mappingFileNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<URL> getJarFileUrls() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getPersistenceUnitRootUrl() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getManagedClassNames() {
|
||||
return managedClassNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean excludeUnlistedClasses() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SharedCacheMode getSharedCacheMode() {
|
||||
return SharedCacheMode.UNSPECIFIED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValidationMode getValidationMode() {
|
||||
return ValidationMode.AUTO;
|
||||
}
|
||||
|
||||
public Properties getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceXMLSchemaVersion() {
|
||||
return JPA_VERSION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTransformer(ClassTransformer transformer) {
|
||||
transformers.add(transformer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassLoader getNewTempClassLoader() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.config;
|
||||
|
||||
import com.mysql.cj.jdbc.MysqlDataSource;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.sql.DataSource;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
|
||||
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
|
||||
|
||||
public class JpaEntityManagerFactory {
|
||||
|
||||
private final String DB_URL = "jdbc:mysql://databaseurl";
|
||||
private final String DB_USER_NAME = "username";
|
||||
private final String DB_PASSWORD = "password";
|
||||
private final Class[] entityClasses;
|
||||
|
||||
public JpaEntityManagerFactory(Class[] entityClasses) {
|
||||
this.entityClasses = entityClasses;
|
||||
}
|
||||
|
||||
public EntityManager getEntityManager() {
|
||||
return getEntityManagerFactory().createEntityManager();
|
||||
}
|
||||
|
||||
protected EntityManagerFactory getEntityManagerFactory() {
|
||||
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
|
||||
Map<String, Object> configuration = new HashMap<>();
|
||||
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
|
||||
.build();
|
||||
}
|
||||
|
||||
protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
|
||||
return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
|
||||
}
|
||||
|
||||
protected List<String> getEntityClassNames() {
|
||||
return Arrays.asList(getEntities())
|
||||
.stream()
|
||||
.map(Class::getName)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected Properties getProperties() {
|
||||
Properties properties = new Properties();
|
||||
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
|
||||
properties.put("hibernate.id.new_generator_mappings", false);
|
||||
properties.put("hibernate.connection.datasource", getMysqlDataSource());
|
||||
return properties;
|
||||
}
|
||||
|
||||
protected Class[] getEntities() {
|
||||
return entityClasses;
|
||||
}
|
||||
|
||||
protected DataSource getMysqlDataSource() {
|
||||
MysqlDataSource mysqlDataSource = new MysqlDataSource();
|
||||
mysqlDataSource.setURL(DB_URL);
|
||||
mysqlDataSource.setUser(DB_USER_NAME);
|
||||
mysqlDataSource.setPassword(DB_PASSWORD);
|
||||
return mysqlDataSource;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.entities;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(){}
|
||||
|
||||
public User(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.hibernate.lifecycle;
|
||||
|
||||
import org.hibernate.EmptyInterceptor;
|
||||
import org.hibernate.type.Type;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DirtyDataInspector extends EmptyInterceptor {
|
||||
private static final ArrayList<FootballPlayer> dirtyEntities = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
|
||||
dirtyEntities.add((FootballPlayer) entity);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static List<FootballPlayer> getDirtyEntities() {
|
||||
return dirtyEntities;
|
||||
}
|
||||
|
||||
public static void clearDirtyEntitites() {
|
||||
dirtyEntities.clear();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.hibernate.lifecycle;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Football_Player")
|
||||
public class FootballPlayer {
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private long id;
|
||||
|
||||
@Column
|
||||
private String name;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.hibernate.lifecycle;
|
||||
|
||||
import org.h2.tools.RunScript;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.SessionFactoryBuilder;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.engine.spi.EntityEntry;
|
||||
import org.hibernate.engine.spi.SessionImplementor;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URL;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class HibernateLifecycleUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static Connection connection;
|
||||
|
||||
public static void init() throws Exception {
|
||||
Properties hbConfigProp = getHibernateProperties();
|
||||
Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
|
||||
connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
|
||||
|
||||
try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
|
||||
InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
|
||||
RunScript.execute(connection, h2InitReader);
|
||||
}
|
||||
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
|
||||
}
|
||||
|
||||
public static void tearDown() throws Exception {
|
||||
sessionFactory.close();
|
||||
connection.close();
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(FootballPlayer.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getHibernateProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties).build();
|
||||
}
|
||||
|
||||
private static Properties getHibernateProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
public static List<EntityEntry> getManagedEntities(Session session) {
|
||||
Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries();
|
||||
return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static Transaction startTransaction(Session s) {
|
||||
Transaction tx = s.getTransaction();
|
||||
tx.begin();
|
||||
return tx;
|
||||
}
|
||||
|
||||
public static int queryCount(String query) throws Exception {
|
||||
try (ResultSet rs = connection.createStatement().executeQuery(query)) {
|
||||
rs.next();
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.lob;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.lob.model.User;
|
||||
|
||||
public class HibernateSessionUtil {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.hibernate.lob.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Lob;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(name = "name", columnDefinition="VARCHAR(128)")
|
||||
private String name;
|
||||
|
||||
@Lob
|
||||
@Column(name = "photo", columnDefinition="BLOB")
|
||||
private byte[] photo;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public byte[] getPhoto() {
|
||||
return photo;
|
||||
}
|
||||
|
||||
public void setPhoto(byte[] photo) {
|
||||
this.photo = photo;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.namingstrategy;
|
||||
|
||||
import org.hibernate.boot.model.naming.Identifier;
|
||||
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
|
||||
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
|
||||
|
||||
public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
|
||||
return convertToSnakeCase(identifier);
|
||||
}
|
||||
|
||||
private Identifier convertToSnakeCase(final Identifier identifier) {
|
||||
if (identifier == null) {
|
||||
return identifier;
|
||||
}
|
||||
|
||||
final String regex = "([a-z])([A-Z])";
|
||||
final String replacement = "$1_$2";
|
||||
final String newName = identifier.getText()
|
||||
.replaceAll(regex, replacement)
|
||||
.toLowerCase();
|
||||
return Identifier.toIdentifier(newName);
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.hibernate.namingstrategy;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "Customers")
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "email")
|
||||
private String emailAddress;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getEmailAddress() {
|
||||
return emailAddress;
|
||||
}
|
||||
|
||||
public void setEmailAddress(String emailAddress) {
|
||||
this.emailAddress = emailAddress;
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.hibernate.optimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class OptimisticLockingCourse {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
@JoinTable(name = "optimistic_student_course")
|
||||
private OptimisticLockingStudent student;
|
||||
|
||||
public OptimisticLockingCourse(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public OptimisticLockingCourse() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public OptimisticLockingStudent getStudent() {
|
||||
return student;
|
||||
}
|
||||
|
||||
public void setStudent(OptimisticLockingStudent student) {
|
||||
this.student = student;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.hibernate.optimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class OptimisticLockingStudent {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String lastName;
|
||||
@Version
|
||||
private Integer version;
|
||||
|
||||
@OneToMany(mappedBy = "student")
|
||||
private List<OptimisticLockingCourse> courses;
|
||||
|
||||
public OptimisticLockingStudent(Long id, String name, String lastName, List<OptimisticLockingCourse> courses) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
this.courses = courses;
|
||||
}
|
||||
|
||||
public OptimisticLockingStudent() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(Integer version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List<OptimisticLockingCourse> getCourses() {
|
||||
return courses;
|
||||
}
|
||||
|
||||
public void setCourses(List<OptimisticLockingCourse> courses) {
|
||||
this.courses = courses;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Address {
|
||||
|
||||
private String country;
|
||||
private String city;
|
||||
|
||||
public Address(String country, String city) {
|
||||
this.country = country;
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
private Long customerId;
|
||||
private String name;
|
||||
private String lastName;
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "customer_address")
|
||||
private List<Address> addressList;
|
||||
|
||||
public Customer() {
|
||||
}
|
||||
|
||||
public Customer(Long customerId, String name, String lastName, List<Address> addressList) {
|
||||
this.customerId = customerId;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
this.addressList = addressList;
|
||||
}
|
||||
|
||||
public Long getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(Long customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List<Address> getAddressList() {
|
||||
return addressList;
|
||||
}
|
||||
|
||||
public void setAddressList(List<Address> addressList) {
|
||||
this.addressList = addressList;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Inheritance;
|
||||
import javax.persistence.InheritanceType;
|
||||
|
||||
@Entity
|
||||
@Inheritance(strategy = InheritanceType.JOINED)
|
||||
public class Individual {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
private String lastName;
|
||||
|
||||
public Individual(Long id, String name, String lastName) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Individual() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingCourse {
|
||||
|
||||
@Id
|
||||
private Long courseId;
|
||||
private String name;
|
||||
@ManyToOne
|
||||
@JoinTable(name = "student_course")
|
||||
private PessimisticLockingStudent student;
|
||||
|
||||
public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
|
||||
this.courseId = courseId;
|
||||
this.name = name;
|
||||
this.student = student;
|
||||
}
|
||||
|
||||
public PessimisticLockingCourse() {
|
||||
}
|
||||
|
||||
public Long getCourseId() {
|
||||
return courseId;
|
||||
}
|
||||
|
||||
public void setCourseId(Long courseId) {
|
||||
this.courseId = courseId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PessimisticLockingStudent getStudent() {
|
||||
return student;
|
||||
}
|
||||
|
||||
public void setStudent(PessimisticLockingStudent students) {
|
||||
this.student = students;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingEmployee extends Individual {
|
||||
|
||||
private BigDecimal salary;
|
||||
|
||||
public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) {
|
||||
super(id, name, lastName);
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public PessimisticLockingEmployee() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BigDecimal getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(BigDecimal average) {
|
||||
this.salary = average;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingStudent {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "student")
|
||||
private List<PessimisticLockingCourse> courses;
|
||||
|
||||
public PessimisticLockingStudent(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PessimisticLockingStudent() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<PessimisticLockingCourse> getCourses() {
|
||||
return courses;
|
||||
}
|
||||
|
||||
public void setCourses(List<PessimisticLockingCourse> courses) {
|
||||
this.courses = courses;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Course {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private UUID courseId;
|
||||
|
||||
public UUID getCourseId() {
|
||||
return courseId;
|
||||
}
|
||||
|
||||
public void setCourseId(UUID courseId) {
|
||||
this.courseId = courseId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.TableGenerator;
|
||||
|
||||
@Entity
|
||||
public class Department {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator")
|
||||
@TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value")
|
||||
private long depId;
|
||||
|
||||
public long getDepId() {
|
||||
return depId;
|
||||
}
|
||||
|
||||
public void setDepId(long depId) {
|
||||
this.depId = depId;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import org.hibernate.annotations.*;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Where(clause = "deleted = false")
|
||||
@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int"))
|
||||
@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit")
|
||||
public class Employee implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
private long grossIncome;
|
||||
|
||||
private int taxInPercents;
|
||||
|
||||
private boolean deleted;
|
||||
|
||||
public long getTaxJavaWay() {
|
||||
return grossIncome * taxInPercents / 100;
|
||||
}
|
||||
|
||||
@Formula("grossIncome * taxInPercents / 100")
|
||||
private long tax;
|
||||
|
||||
@OneToMany
|
||||
@JoinColumn(name = "employee_id")
|
||||
@Where(clause = "deleted = false")
|
||||
private Set<Phone> phones = new HashSet<>(0);
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(long grossIncome, int taxInPercents) {
|
||||
this.grossIncome = grossIncome;
|
||||
this.taxInPercents = taxInPercents;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public long getGrossIncome() {
|
||||
return grossIncome;
|
||||
}
|
||||
|
||||
public int getTaxInPercents() {
|
||||
return taxInPercents;
|
||||
}
|
||||
|
||||
public long getTax() {
|
||||
return tax;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setGrossIncome(long grossIncome) {
|
||||
this.grossIncome = grossIncome;
|
||||
}
|
||||
|
||||
public void setTaxInPercents(int taxInPercents) {
|
||||
this.taxInPercents = taxInPercents;
|
||||
}
|
||||
|
||||
public boolean getDeleted() {
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public void setDeleted(boolean deleted) {
|
||||
this.deleted = deleted;
|
||||
}
|
||||
|
||||
public Set<Phone> getPhones() {
|
||||
return phones;
|
||||
}
|
||||
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import org.hibernate.annotations.Any;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class EntityDescription implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
private String description;
|
||||
|
||||
@Any(
|
||||
metaDef = "EntityDescriptionMetaDef",
|
||||
metaColumn = @Column(name = "entity_type")
|
||||
)
|
||||
@JoinColumn(name = "entity_id")
|
||||
private Serializable entity;
|
||||
|
||||
public EntityDescription() {
|
||||
}
|
||||
|
||||
public EntityDescription(String description, Serializable entity) {
|
||||
this.description = description;
|
||||
this.entity = entity;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Serializable getEntity() {
|
||||
return entity;
|
||||
}
|
||||
|
||||
public void setEntity(Serializable entity) {
|
||||
this.entity = entity;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.EmbeddedId;
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
public class OrderEntry {
|
||||
|
||||
@EmbeddedId
|
||||
private OrderEntryPK entryId;
|
||||
|
||||
public OrderEntryPK getEntryId() {
|
||||
return entryId;
|
||||
}
|
||||
|
||||
public void setEntryId(OrderEntryPK entryId) {
|
||||
this.entryId = entryId;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.IdClass;
|
||||
|
||||
@Entity
|
||||
@IdClass(OrderEntryPK.class)
|
||||
public class OrderEntryIdClass {
|
||||
@Id
|
||||
private long orderId;
|
||||
@Id
|
||||
private long productId;
|
||||
|
||||
public long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class OrderEntryPK implements Serializable {
|
||||
|
||||
private long orderId;
|
||||
private long productId;
|
||||
|
||||
public long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
OrderEntryPK pk = (OrderEntryPK) o;
|
||||
return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(orderId, productId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Convert;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import com.baeldung.hibernate.converters.PersonNameConverter;
|
||||
|
||||
@Entity(name = "PersonTable")
|
||||
public class Person {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
@Convert(converter = PersonNameConverter.class)
|
||||
private PersonName personName;
|
||||
|
||||
public PersonName getPersonName() {
|
||||
return personName;
|
||||
}
|
||||
|
||||
public void setPersonName(PersonName personName) {
|
||||
this.personName = personName;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class PersonName implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 7883094644631050150L;
|
||||
|
||||
private String name;
|
||||
|
||||
private String surname;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
public class Phone implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
private boolean deleted;
|
||||
|
||||
private String number;
|
||||
|
||||
public Phone() {
|
||||
}
|
||||
|
||||
public Phone(String number) {
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public boolean isDeleted() {
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public void setDeleted(boolean deleted) {
|
||||
this.deleted = deleted;
|
||||
}
|
||||
|
||||
public String getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public void setNumber(String number) {
|
||||
this.number = number;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class PointEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private Point point;
|
||||
|
||||
public PointEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Point getPoint() {
|
||||
return point;
|
||||
}
|
||||
|
||||
public void setPoint(Point point) {
|
||||
this.point = point;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PointEntity{" + "id=" + id + ", point=" + point + '}';
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import com.vividsolutions.jts.geom.Polygon;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class PolygonEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private Polygon polygon;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Polygon getPolygon() {
|
||||
return polygon;
|
||||
}
|
||||
|
||||
public void setPolygon(Polygon polygon) {
|
||||
this.polygon = polygon;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
|
||||
@Entity
|
||||
public class Product {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator = "prod-generator")
|
||||
@GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator")
|
||||
private String prodId;
|
||||
|
||||
public String getProdId() {
|
||||
return prodId;
|
||||
}
|
||||
|
||||
public void setProdId(String prodId) {
|
||||
this.prodId = prodId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
public class Result {
|
||||
private String employeeName;
|
||||
|
||||
private String departmentName;
|
||||
|
||||
public Result(String employeeName, String departmentName) {
|
||||
this.employeeName = employeeName;
|
||||
this.departmentName = departmentName;
|
||||
}
|
||||
|
||||
public Result() {
|
||||
}
|
||||
|
||||
public String getEmployeeName() {
|
||||
return employeeName;
|
||||
}
|
||||
|
||||
public void setEmployeeName(String employeeName) {
|
||||
this.employeeName = employeeName;
|
||||
}
|
||||
|
||||
public String getDepartmentName() {
|
||||
return departmentName;
|
||||
}
|
||||
|
||||
public void setDepartmentName(String departmentName) {
|
||||
this.departmentName = departmentName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue (strategy = GenerationType.SEQUENCE)
|
||||
private long studentId;
|
||||
|
||||
public long getStudentId() {
|
||||
return studentId;
|
||||
}
|
||||
|
||||
public void setStudent_id(long studentId) {
|
||||
this.studentId = studentId;
|
||||
}
|
||||
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Date;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.*;
|
||||
import java.util.Calendar;
|
||||
|
||||
@Entity
|
||||
public class TemporalValues implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@Basic
|
||||
private java.sql.Date sqlDate;
|
||||
|
||||
@Basic
|
||||
private java.sql.Time sqlTime;
|
||||
|
||||
@Basic
|
||||
private java.sql.Timestamp sqlTimestamp;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private java.util.Date utilDate;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIME)
|
||||
private java.util.Date utilTime;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private java.util.Date utilTimestamp;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.DATE)
|
||||
private java.util.Calendar calendarDate;
|
||||
|
||||
@Basic
|
||||
@Temporal(TemporalType.TIMESTAMP)
|
||||
private java.util.Calendar calendarTimestamp;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalDate localDate;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalTime localTime;
|
||||
|
||||
@Basic
|
||||
private java.time.OffsetTime offsetTime;
|
||||
|
||||
@Basic
|
||||
private java.time.Instant instant;
|
||||
|
||||
@Basic
|
||||
private java.time.LocalDateTime localDateTime;
|
||||
|
||||
@Basic
|
||||
private java.time.OffsetDateTime offsetDateTime;
|
||||
|
||||
@Basic
|
||||
private java.time.ZonedDateTime zonedDateTime;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Date getSqlDate() {
|
||||
return sqlDate;
|
||||
}
|
||||
|
||||
public void setSqlDate(Date sqlDate) {
|
||||
this.sqlDate = sqlDate;
|
||||
}
|
||||
|
||||
public Time getSqlTime() {
|
||||
return sqlTime;
|
||||
}
|
||||
|
||||
public void setSqlTime(Time sqlTime) {
|
||||
this.sqlTime = sqlTime;
|
||||
}
|
||||
|
||||
public Timestamp getSqlTimestamp() {
|
||||
return sqlTimestamp;
|
||||
}
|
||||
|
||||
public void setSqlTimestamp(Timestamp sqlTimestamp) {
|
||||
this.sqlTimestamp = sqlTimestamp;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilDate() {
|
||||
return utilDate;
|
||||
}
|
||||
|
||||
public void setUtilDate(java.util.Date utilDate) {
|
||||
this.utilDate = utilDate;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTime() {
|
||||
return utilTime;
|
||||
}
|
||||
|
||||
public void setUtilTime(java.util.Date utilTime) {
|
||||
this.utilTime = utilTime;
|
||||
}
|
||||
|
||||
public java.util.Date getUtilTimestamp() {
|
||||
return utilTimestamp;
|
||||
}
|
||||
|
||||
public void setUtilTimestamp(java.util.Date utilTimestamp) {
|
||||
this.utilTimestamp = utilTimestamp;
|
||||
}
|
||||
|
||||
public Calendar getCalendarDate() {
|
||||
return calendarDate;
|
||||
}
|
||||
|
||||
public void setCalendarDate(Calendar calendarDate) {
|
||||
this.calendarDate = calendarDate;
|
||||
}
|
||||
|
||||
public Calendar getCalendarTimestamp() {
|
||||
return calendarTimestamp;
|
||||
}
|
||||
|
||||
public void setCalendarTimestamp(Calendar calendarTimestamp) {
|
||||
this.calendarTimestamp = calendarTimestamp;
|
||||
}
|
||||
|
||||
public LocalDate getLocalDate() {
|
||||
return localDate;
|
||||
}
|
||||
|
||||
public void setLocalDate(LocalDate localDate) {
|
||||
this.localDate = localDate;
|
||||
}
|
||||
|
||||
public LocalTime getLocalTime() {
|
||||
return localTime;
|
||||
}
|
||||
|
||||
public void setLocalTime(LocalTime localTime) {
|
||||
this.localTime = localTime;
|
||||
}
|
||||
|
||||
public OffsetTime getOffsetTime() {
|
||||
return offsetTime;
|
||||
}
|
||||
|
||||
public void setOffsetTime(OffsetTime offsetTime) {
|
||||
this.offsetTime = offsetTime;
|
||||
}
|
||||
|
||||
public Instant getInstant() {
|
||||
return instant;
|
||||
}
|
||||
|
||||
public void setInstant(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
|
||||
public LocalDateTime getLocalDateTime() {
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
public void setLocalDateTime(LocalDateTime localDateTime) {
|
||||
this.localDateTime = localDateTime;
|
||||
}
|
||||
|
||||
public OffsetDateTime getOffsetDateTime() {
|
||||
return offsetDateTime;
|
||||
}
|
||||
|
||||
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
|
||||
this.offsetDateTime = offsetDateTime;
|
||||
}
|
||||
|
||||
public ZonedDateTime getZonedDateTime() {
|
||||
return zonedDateTime;
|
||||
}
|
||||
|
||||
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
this.zonedDateTime = zonedDateTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(generator = "sequence-generator")
|
||||
@GenericGenerator(
|
||||
name = "sequence-generator",
|
||||
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||
parameters = {
|
||||
@Parameter(name = "sequence_name", value = "user_sequence"),
|
||||
@Parameter(name = "initial_value", value = "4"),
|
||||
@Parameter(name = "increment_size", value = "1")
|
||||
}
|
||||
)
|
||||
private long userId;
|
||||
|
||||
public long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.MapsId;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity
|
||||
public class UserProfile {
|
||||
|
||||
@Id
|
||||
private long profileId;
|
||||
|
||||
@OneToOne
|
||||
@MapsId
|
||||
private User user;
|
||||
|
||||
public long getProfileId() {
|
||||
return profileId;
|
||||
}
|
||||
|
||||
public void setProfileId(long profileId) {
|
||||
this.profileId = profileId;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.hibernate.pojo.generator;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.MappingException;
|
||||
import org.hibernate.engine.spi.SharedSessionContractImplementor;
|
||||
import org.hibernate.id.Configurable;
|
||||
import org.hibernate.id.IdentifierGenerator;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.hibernate.type.Type;
|
||||
|
||||
public class MyGenerator implements IdentifierGenerator, Configurable {
|
||||
|
||||
private String prefix;
|
||||
|
||||
@Override
|
||||
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
|
||||
|
||||
String query = String.format("select %s from %s",
|
||||
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(),
|
||||
obj.getClass().getSimpleName());
|
||||
|
||||
Stream<String> ids = session.createQuery(query).stream();
|
||||
|
||||
Long max = ids.map(o -> o.replace(prefix + "-", ""))
|
||||
.mapToLong(Long::parseLong)
|
||||
.max()
|
||||
.orElse(0L);
|
||||
|
||||
return prefix + "-" + (max + 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
|
||||
prefix = properties.getProperty("prefix");
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.hibernate.pojo.inheritance;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Inheritance;
|
||||
import javax.persistence.InheritanceType;
|
||||
|
||||
@Entity
|
||||
@Inheritance(strategy = InheritanceType.JOINED)
|
||||
public class Animal {
|
||||
|
||||
@Id
|
||||
private long animalId;
|
||||
|
||||
private String species;
|
||||
|
||||
public Animal() {}
|
||||
|
||||
public Animal(long animalId, String species) {
|
||||
this.animalId = animalId;
|
||||
this.species = species;
|
||||
}
|
||||
|
||||
public long getAnimalId() {
|
||||
return animalId;
|
||||
}
|
||||
|
||||
public void setAnimalId(long animalId) {
|
||||
this.animalId = animalId;
|
||||
}
|
||||
|
||||
public String getSpecies() {
|
||||
return species;
|
||||
}
|
||||
|
||||
public void setSpecies(String species) {
|
||||
this.species = species;
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.hibernate.pojo.inheritance;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import org.hibernate.annotations.Polymorphism;
|
||||
import org.hibernate.annotations.PolymorphismType;
|
||||
|
||||
@Entity
|
||||
@Polymorphism(type = PolymorphismType.EXPLICIT)
|
||||
public class Bag implements Item {
|
||||
|
||||
@Id
|
||||
private long bagId;
|
||||
|
||||
private String type;
|
||||
|
||||
public Bag(long bagId, String type) {
|
||||
this.bagId = bagId;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public long getBagId() {
|
||||
return bagId;
|
||||
}
|
||||
|
||||
public void setBagId(long bagId) {
|
||||
this.bagId = bagId;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.hibernate.pojo.inheritance;
|
||||
|
||||
import javax.persistence.DiscriminatorValue;
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
@DiscriminatorValue("1")
|
||||
public class Book extends MyProduct {
|
||||
private String author;
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(long productId, String name, String author) {
|
||||
super(productId, name);
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.hibernate.pojo.inheritance;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
public class Car extends Vehicle {
|
||||
private String engine;
|
||||
|
||||
public Car() {
|
||||
}
|
||||
|
||||
public Car(long vehicleId, String manufacturer, String engine) {
|
||||
super(vehicleId, manufacturer);
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
public String getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
public void setEngine(String engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.hibernate.pojo.inheritance;
|
||||
|
||||
public interface Item {
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user