HHH-12148 - Add test for issue

This commit is contained in:
Andrea Boriero 2017-11-22 11:51:56 +00:00 committed by Steve Ebersole
parent 6818275376
commit 2b7c2c883c
7 changed files with 526 additions and 9 deletions

View File

@ -0,0 +1,124 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.indetifier;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.core.Is.is;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author Andrea Boriero
*/
public class AssignedInitialValueTableGeneratorConfiguredTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Product.class
};
}
@Test
public void testTheFirstGeneratedIdIsEqualToTableGeneratorInitialValuePlusOne() {
doInJPA( this::entityManagerFactory, entityManager -> {
Product product = new Product();
product.setName( "Hibernate" );
entityManager.persist( product );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
Product product = entityManager.find( Product.class, 3L );
assertThat( product, notNullValue() );
} );
}
@Test
public void testTheGeneratedIdValuesAreCorrect() {
doInJPA( this::entityManagerFactory, entityManager -> {
for ( long i = 0; i < 3; i++ ) {
Product product = new Product();
product.setName( "Hibernate " + i );
entityManager.persist( product );
}
} );
Session session = getOrCreateEntityManager().unwrap( Session.class );
session.doWork( new Work() {
@Override
public void execute(Connection connection) throws SQLException {
ResultSet resultSet = connection.createStatement().executeQuery(
"select product_id from table_identifier" );
resultSet.next();
int productIdValue = resultSet.getInt( 1 );
assertThat( productIdValue, is(12) );
}
} );
doInJPA( this::entityManagerFactory, entityManager -> {
List<Product> products = entityManager.createQuery( "from Product p order by id " ).getResultList();
assertThat( products.size(), is( 3 ) );
assertThat( products.get( 0 ).getId(), is( 3L ) );
assertThat( products.get( 1 ).getId(), is( 4L ) );
assertThat( products.get( 2 ).getId(), is( 5L ) );
} );
}
@Entity(name = "Product")
public static class Product {
@Id
@GeneratedValue(
strategy = GenerationType.TABLE,
generator = "table-generator"
)
@TableGenerator(
name = "table-generator",
table = "table_identifier",
pkColumnName = "table_name",
valueColumnName = "product_id",
allocationSize = 5,
initialValue = 2
)
private Long id;
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;
}
}
}

View File

@ -0,0 +1,124 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.indetifier;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.core.Is.is;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertThat;
/**
* @author Andrea Boriero
*/
public class DefaultInitialValueTableGeneratorConfiguredTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Product.class
};
}
@Test
public void testTheFirstGeneratedIdIsEqualToTableGeneratorInitialValuePlusOne() {
doInJPA( this::entityManagerFactory, entityManager -> {
Product product = new Product();
product.setName( "Hibernate" );
entityManager.persist( product );
} );
doInJPA( this::entityManagerFactory, entityManager -> {
Product product = entityManager.find(
Product.class,
1L
);
assertThat( product, notNullValue() );
} );
}
@Test
public void testTheGeneratedIdValuesAreCorrect() {
doInJPA( this::entityManagerFactory, entityManager -> {
for ( long i = 0; i < 3; i++ ) {
Product product = new Product();
product.setName( "Hibernate " + i );
entityManager.persist( product );
}
} );
Session session = getOrCreateEntityManager().unwrap( Session.class );
session.doWork( new Work() {
@Override
public void execute(Connection connection) throws SQLException {
ResultSet resultSet = connection.createStatement().executeQuery(
"select product_id from table_identifier" );
resultSet.next();
int productIdValue = resultSet.getInt( 1 );
assertThat( productIdValue, is(10) );
}
} );
doInJPA( this::entityManagerFactory, entityManager -> {
List<Product> products = entityManager.createQuery(
"from Product p order by id " ).getResultList();
assertThat( products.size(), is( 3 ) );
assertThat( products.get( 0 ).getId(), is( 1L ) );
assertThat( products.get( 1 ).getId(), is( 2L ) );
assertThat( products.get( 2 ).getId(), is( 3L ) );
} );
}
@Entity(name = "Product")
public static class Product {
@Id
@GeneratedValue(
strategy = GenerationType.TABLE,
generator = "table-generator"
)
@TableGenerator(
name = "table-generator",
table = "table_identifier",
pkColumnName = "table_name",
valueColumnName = "product_id",
allocationSize = 5
)
private Long id;
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;
}
}
}

View File

@ -200,9 +200,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); assertThat( tableGenerator.getTableName(), is( "my_id_table" ) );
// all the JPA defaults since they were not defined // all the JPA defaults since they were not defined
// - note : currently initialValue=1 in mapping is shows up here assertThat( tableGenerator.getInitialValue(), is( 1 ) );
// as 2
// assertThat( tableGenerator.getInitialValue(), is( 1 ) );
assertThat( tableGenerator.getIncrementSize(), is( 50 ) ); assertThat( tableGenerator.getIncrementSize(), is( 50 ) );
} }
@ -226,7 +224,7 @@ public class GeneratedValueTests extends BaseUnitTestCase {
assertThat( tableGenerator.getTableName(), is( "my_id_table" ) ); assertThat( tableGenerator.getTableName(), is( "my_id_table" ) );
// - note : currently initialValue=1 in mapping is shows up here as 2 // - note : currently initialValue=1 in mapping is shows up here as 2
// assertThat( tableGenerator.getInitialValue(), is( 1 ) ); assertThat( tableGenerator.getInitialValue(), is( 1 ) );
assertThat( tableGenerator.getIncrementSize(), is( 25 ) ); assertThat( tableGenerator.getIncrementSize(), is( 25 ) );
} }

View File

@ -0,0 +1,120 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.schemaupdate.idgenerator;
import java.io.File;
import java.nio.file.Files;
import java.util.EnumSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.RequiresDialect;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author Andrea Boriero
*/
@RequiresDialect(H2Dialect.class)
public class SequenceGenerationTest {
private StandardServiceRegistry ssr;
private File output;
private MetadataImplementor metadata;
@Before
public void setUp() throws Exception {
ssr = new StandardServiceRegistryBuilder()
.applySetting( Environment.HBM2DDL_AUTO, "none" )
.build();
output = File.createTempFile( "update_script", ".sql" );
output.deleteOnExit();
metadata = (MetadataImplementor) new MetadataSources( ssr )
.addAnnotatedClass( TestEntity.class )
.buildMetadata();
metadata.validate();
}
@Test
public void testSequenceIsGenerated() throws Exception {
new SchemaExport()
.setOutputFile( output.getAbsolutePath() )
.create( EnumSet.of( TargetType.SCRIPT, TargetType.DATABASE ), metadata );
List<String> commands = Files.readAllLines( output.toPath() );
assertThat(
isCommandGenerated( commands, "create table test_entity \\(id .*, primary key \\(id\\)\\)" ),
is( true )
);
assertThat(
isCommandGenerated( commands, "create sequence sequence_generator start with 5 increment by 3" ),
is( true )
);
}
@After
public void tearDown() {
try {
new SchemaExport()
.drop( EnumSet.of( TargetType.DATABASE ), metadata );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
private boolean isCommandGenerated(List<String> commands, String expectedCommnad) {
final Pattern pattern = Pattern.compile( expectedCommnad.toLowerCase() );
for ( String command : commands ) {
Matcher matcher = pattern.matcher( command.toLowerCase() );
if ( matcher.matches() ) {
return true;
}
}
return false;
}
@Entity(name = "TestEntity")
@Table(name = "TEST_ENTITY")
public static class TestEntity {
Long id;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCEGENERATOR")
@SequenceGenerator(name = "SEQUENCEGENERATOR", allocationSize = 3, initialValue = 5, sequenceName = "SEQUENCE_GENERATOR")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
}

View File

@ -25,9 +25,11 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.RequiresDialect;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -38,6 +40,7 @@ import static org.junit.Assert.assertThat;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@RequiresDialect(H2Dialect.class)
public class SequenceGeneratorsTest { public class SequenceGeneratorsTest {
private StandardServiceRegistry ssr; private StandardServiceRegistry ssr;
private File output; private File output;
@ -65,12 +68,12 @@ public class SequenceGeneratorsTest {
List<String> commands = Files.readAllLines( output.toPath() ); List<String> commands = Files.readAllLines( output.toPath() );
assertThat( assertThat(
isCommandGenerated( commands, "create table test_entity \\(id .*, primary key \\(id\\)\\)" ), isCommandGenerated( commands, "CREATE TABLE TEST_ENTITY \\(ID .*, PRIMARY KEY \\(ID\\)\\)" ),
is( true ) is( true )
); );
assertThat( assertThat(
isCommandGenerated( commands, "create sequence sequence_generator start with 5 increment by 3" ), isCommandGenerated( commands, "CREATE SEQUENCE SEQUENCE_GENERATOR START WITH 5 INCREMENT BY 3" ),
is( true ) is( true )
); );
} }

View File

@ -0,0 +1,145 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.schemaupdate.idgenerator;
import java.io.File;
import java.nio.file.Files;
import java.util.EnumSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.RequiresDialect;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* @author Andrea Boriero
*/
@RequiresDialect(H2Dialect.class)
public class TableGeneratorTest {
private StandardServiceRegistry ssr;
private File output;
private MetadataImplementor metadata;
private static final int INITIAL_VALUE = 5;
private static final int EXPECTED_DB_INSERTED_VALUE = INITIAL_VALUE;
@Before
public void setUp() throws Exception {
ssr = new StandardServiceRegistryBuilder()
.applySetting( Environment.HBM2DDL_AUTO, "none" )
.build();
output = File.createTempFile( "update_script", ".sql" );
output.deleteOnExit();
metadata = (MetadataImplementor) new MetadataSources( ssr )
.addAnnotatedClass( TestEntity.class )
.buildMetadata();
metadata.validate();
}
@Test
public void testTableGeneratorIsGenerated() throws Exception {
new SchemaExport()
.setOutputFile( output.getAbsolutePath() )
.create( EnumSet.of( TargetType.SCRIPT, TargetType.DATABASE ), metadata );
final List<String> commands = Files.readAllLines( output.toPath() );
final String expectedTestEntityTableCreationCommand = "CREATE TABLE TEST_ENTITY \\(ID .*, PRIMARY KEY \\(ID\\)\\)";
assertTrue(
"The command '" + expectedTestEntityTableCreationCommand + "' has not been correctly generated",
isCommandGenerated( commands, expectedTestEntityTableCreationCommand )
);
final String expectedIdTableGeneratorCreationCommand = "CREATE TABLE ID_TABLE_GENERATOR \\(PK .*, VALUE .*, PRIMARY KEY \\(PK\\)\\)";
assertTrue(
"The command '" + expectedIdTableGeneratorCreationCommand + "' has not been correctly generated",
isCommandGenerated(
commands,
expectedIdTableGeneratorCreationCommand
)
);
final String expectedInsertIntoTableGeneratorCommand = "INSERT INTO ID_TABLE_GENERATOR\\(PK, VALUE\\) VALUES \\('TEST_ENTITY_ID'," + EXPECTED_DB_INSERTED_VALUE + "\\)";
assertTrue(
"The command '" + expectedInsertIntoTableGeneratorCommand + "' has not been correctly generated",
isCommandGenerated(
commands,
expectedInsertIntoTableGeneratorCommand
)
);
}
@After
public void tearDown() {
try {
new SchemaExport().drop( EnumSet.of( TargetType.DATABASE ), metadata );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
@Entity(name = "TestEntity")
@Table(name = "TEST_ENTITY")
@TableGenerator(name = "tableGenerator",
table = "ID_TABLE_GENERATOR",
pkColumnName = "PK",
pkColumnValue = "TEST_ENTITY_ID",
valueColumnName = "VALUE",
allocationSize = 3,
initialValue = INITIAL_VALUE)
public static class TestEntity {
Long id;
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "tableGenerator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
private boolean isCommandGenerated(List<String> commands, String expectedCommnad) {
final Pattern pattern = Pattern.compile( expectedCommnad.toLowerCase() );
for ( String command : commands ) {
Matcher matcher = pattern.matcher( command.toLowerCase() );
if ( matcher.matches() ) {
return true;
}
}
return false;
}
}

View File

@ -25,9 +25,11 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType; import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.RequiresDialect;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -37,6 +39,7 @@ import static org.junit.Assert.assertTrue;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@RequiresDialect(H2Dialect.class)
public class TableGeneratorsTest { public class TableGeneratorsTest {
private StandardServiceRegistry ssr; private StandardServiceRegistry ssr;
@ -68,13 +71,13 @@ public class TableGeneratorsTest {
final List<String> commands = Files.readAllLines( output.toPath() ); final List<String> commands = Files.readAllLines( output.toPath() );
final String expectedTestEntityTableCreationCommand = "create table test_entity \\(id .*, primary key \\(id\\)\\)"; final String expectedTestEntityTableCreationCommand = "CREATE TABLE TEST_ENTITY \\(ID .*, PRIMARY KEY \\(ID\\)\\)";
assertTrue( assertTrue(
"The command '" + expectedTestEntityTableCreationCommand + "' has not been correctly generated", "The command '" + expectedTestEntityTableCreationCommand + "' has not been correctly generated",
isCommandGenerated( commands, expectedTestEntityTableCreationCommand ) isCommandGenerated( commands, expectedTestEntityTableCreationCommand )
); );
final String expectedIdTableGeneratorCreationCommand = "create table ID_TABLE_GENERATOR \\(PK .*, VALUE .*, primary key \\(PK\\)\\)"; final String expectedIdTableGeneratorCreationCommand = "CREATE TABLE ID_TABLE_GENERATOR \\(PK .*, VALUE .*, PRIMARY KEY \\(PK\\)\\)";
assertTrue( assertTrue(
"The command '" + expectedIdTableGeneratorCreationCommand + "' has not been correctly generated", "The command '" + expectedIdTableGeneratorCreationCommand + "' has not been correctly generated",
@ -85,7 +88,7 @@ public class TableGeneratorsTest {
) )
); );
final String expectedInsertIntoTableGeneratorCommand = "INSERT INTO ID_TABLE_GENERATOR\\(PK, VALUE\\) values \\('TEST_ENTITY_ID'," + EXPECTED_DB_INSERTED_VALUE + "\\)"; final String expectedInsertIntoTableGeneratorCommand = "INSERT INTO ID_TABLE_GENERATOR\\(PK, VALUE\\) VALUES \\('TEST_ENTITY_ID'," + EXPECTED_DB_INSERTED_VALUE + "\\)";
assertTrue( assertTrue(
"The command '" + expectedInsertIntoTableGeneratorCommand + "' has not been correctly generated", "The command '" + expectedInsertIntoTableGeneratorCommand + "' has not been correctly generated",