Fix throw exception when more than one row with the given identifier was found and re-enabled additiona tests

This commit is contained in:
Andrea Boriero 2021-06-01 15:48:28 +02:00
parent babefc8b9d
commit 39d5d344fb
46 changed files with 1327 additions and 1221 deletions

View File

@ -68,7 +68,7 @@ public T load(Object key, LockOptions lockOptions, Boolean readOnly, SharedSessi
session.getFactory() session.getFactory()
); );
return loadPlan.load( key, lockOptions, readOnly, session ); return loadPlan.load( key, lockOptions, null, readOnly,true, session );
} }
@Override @Override
@ -93,7 +93,7 @@ public T load(
else { else {
lockOptionsToUse = lockOptions; lockOptionsToUse = lockOptions;
} }
return loadPlan.load( key, lockOptionsToUse, entityInstance, readOnly, session ); return loadPlan.load( key, lockOptionsToUse, entityInstance, readOnly, false, session );
} }
@Internal @Internal

View File

@ -75,14 +75,14 @@ T load(
LockOptions lockOptions, LockOptions lockOptions,
Boolean readOnly, Boolean readOnly,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return load( restrictedValue, lockOptions, null, readOnly, session ); return load( restrictedValue, lockOptions, null, readOnly,false, session );
} }
T load( T load(
Object restrictedValue, Object restrictedValue,
LockOptions lockOptions, LockOptions lockOptions,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return load( restrictedValue, lockOptions, null, null, session ); return load( restrictedValue, lockOptions, null, null,false, session );
} }
T load( T load(
@ -90,6 +90,7 @@ T load(
LockOptions lockOptions, LockOptions lockOptions,
Object entityInstance, Object entityInstance,
Boolean readOnly, Boolean readOnly,
Boolean singleResultExpected,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
final SessionFactoryImplementor sessionFactory = session.getFactory(); final SessionFactoryImplementor sessionFactory = session.getFactory();
final JdbcServices jdbcServices = sessionFactory.getJdbcServices(); final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
@ -153,7 +154,8 @@ public Callback getCallback() {
} }
}, },
RowTransformerPassThruImpl.instance(), RowTransformerPassThruImpl.instance(),
true true,
singleResultExpected
); );
if ( list.isEmpty() ) { if ( list.isEmpty() ) {

View File

@ -80,7 +80,29 @@ public <R> List<R> list(
.getJdbcCoordinator() .getJdbcCoordinator()
.getStatementPreparer() .getStatementPreparer()
.prepareStatement( sql ), .prepareStatement( sql ),
ListResultsConsumer.instance( uniqueFilter ) ListResultsConsumer.instance( uniqueFilter, false )
);
}
@Override
public <R> List<R> list(
JdbcSelect jdbcSelect,
JdbcParameterBindings jdbcParameterBindings,
ExecutionContext executionContext,
RowTransformer<R> rowTransformer,
boolean uniqueFilter,
boolean singleResultExpected) {
// Only do auto flushing for top level queries
return executeQuery(
jdbcSelect,
jdbcParameterBindings,
executionContext,
rowTransformer,
(sql) -> executionContext.getSession()
.getJdbcCoordinator()
.getStatementPreparer()
.prepareStatement( sql ),
ListResultsConsumer.instance( uniqueFilter, singleResultExpected )
); );
} }

View File

@ -30,6 +30,14 @@ <R> List<R> list(
RowTransformer<R> rowTransformer, RowTransformer<R> rowTransformer,
boolean uniqueFilter); boolean uniqueFilter);
<R> List<R> list(
JdbcSelect jdbcSelect,
JdbcParameterBindings jdbcParameterBindings,
ExecutionContext executionContext,
RowTransformer<R> rowTransformer,
boolean uniqueFilter,
boolean onlyOne);
<R> ScrollableResultsImplementor<R> scroll( <R> ScrollableResultsImplementor<R> scroll(
JdbcSelect jdbcSelect, JdbcSelect jdbcSelect,
ScrollMode scrollMode, ScrollMode scrollMode,

View File

@ -16,6 +16,7 @@
import org.hibernate.sql.exec.spi.Callback; import org.hibernate.sql.exec.spi.Callback;
import org.hibernate.sql.exec.spi.ExecutionContext; import org.hibernate.sql.exec.spi.ExecutionContext;
import org.hibernate.sql.results.graph.Initializer; import org.hibernate.sql.results.graph.Initializer;
import org.hibernate.sql.results.graph.collection.CollectionInitializer;
import org.hibernate.sql.results.graph.entity.EntityFetch; import org.hibernate.sql.results.graph.entity.EntityFetch;
import org.hibernate.sql.results.jdbc.internal.JdbcValuesSourceProcessingStateStandardImpl; import org.hibernate.sql.results.jdbc.internal.JdbcValuesSourceProcessingStateStandardImpl;
import org.hibernate.sql.results.jdbc.spi.JdbcValues; import org.hibernate.sql.results.jdbc.spi.JdbcValues;
@ -36,6 +37,7 @@ public class RowProcessingStateStandardImpl implements RowProcessingState {
private final RowReader<?> rowReader; private final RowReader<?> rowReader;
private final JdbcValues jdbcValues; private final JdbcValues jdbcValues;
private final ExecutionContext executionContext; private final ExecutionContext executionContext;
public final boolean hasCollectionInitializers;
public RowProcessingStateStandardImpl( public RowProcessingStateStandardImpl(
JdbcValuesSourceProcessingStateStandardImpl resultSetProcessingState, JdbcValuesSourceProcessingStateStandardImpl resultSetProcessingState,
@ -50,13 +52,28 @@ public RowProcessingStateStandardImpl(
final List<Initializer> initializers = rowReader.getInitializers(); final List<Initializer> initializers = rowReader.getInitializers();
if ( initializers == null || initializers.isEmpty() ) { if ( initializers == null || initializers.isEmpty() ) {
this.initializers = NO_INITIALIZERS; this.initializers = NO_INITIALIZERS;
hasCollectionInitializers = false;
} }
else { else {
//noinspection ToArrayCallWithZeroLengthArrayArgument //noinspection ToArrayCallWithZeroLengthArrayArgument
this.initializers = initializers.toArray( new Initializer[initializers.size()] ); this.initializers = initializers.toArray( new Initializer[initializers.size()] );
hasCollectionInitializers = hasCollectionInitializers(this.initializers);
} }
} }
private static boolean hasCollectionInitializers(Initializer[] initializers) {
for ( int i = 0; i < initializers.length; i++ ) {
if ( initializers[i] instanceof CollectionInitializer ) {
return true;
}
}
return false;
}
public boolean hasCollectionInitializers(){
return this.hasCollectionInitializers;
}
@Override @Override
public JdbcValuesSourceProcessingState getJdbcValuesSourceProcessingState() { public JdbcValuesSourceProcessingState getJdbcValuesSourceProcessingState() {
return resultSetProcessingState; return resultSetProcessingState;

View File

@ -6,10 +6,10 @@
*/ */
package org.hibernate.sql.results.spi; package org.hibernate.sql.results.spi;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.sql.results.jdbc.spi.JdbcValues; import org.hibernate.sql.results.jdbc.spi.JdbcValues;
@ -17,6 +17,7 @@
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.sql.results.jdbc.internal.JdbcValuesSourceProcessingStateStandardImpl; import org.hibernate.sql.results.jdbc.internal.JdbcValuesSourceProcessingStateStandardImpl;
import org.hibernate.sql.results.internal.RowProcessingStateStandardImpl; import org.hibernate.sql.results.internal.RowProcessingStateStandardImpl;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
@ -25,18 +26,28 @@ public class ListResultsConsumer<R> implements ResultsConsumer<List<R>, R> {
/** /**
* Singleton access * Singleton access
*/ */
private static final ListResultsConsumer UNIQUE_FILTER_INSTANCE = new ListResultsConsumer(true); private static final ListResultsConsumer UNIQUE_FILTER_INSTANCE = new ListResultsConsumer( UniqueSemantic.FILTER );
private static final ListResultsConsumer NORMAL_INSTANCE = new ListResultsConsumer(false); private static final ListResultsConsumer NORMAL_INSTANCE = new ListResultsConsumer( UniqueSemantic.NONE );
private static final ListResultsConsumer UNIQUE_INSTANCE = new ListResultsConsumer( UniqueSemantic.ASSERT );
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <R> ListResultsConsumer<R> instance(boolean uniqueFilter) { public static <R> ListResultsConsumer<R> instance(boolean uniqueFilter, boolean singleResultExpected) {
if ( singleResultExpected ) {
return UNIQUE_INSTANCE;
}
return uniqueFilter ? UNIQUE_FILTER_INSTANCE : NORMAL_INSTANCE; return uniqueFilter ? UNIQUE_FILTER_INSTANCE : NORMAL_INSTANCE;
} }
private final boolean uniqueFilter; public enum UniqueSemantic {
NONE,
FILTER,
ASSERT;
}
public ListResultsConsumer(boolean uniqueFilter) { private final UniqueSemantic uniqueSemantic;
this.uniqueFilter = uniqueFilter;
public ListResultsConsumer(UniqueSemantic uniqueSemantic) {
this.uniqueSemantic = uniqueSemantic;
} }
@Override @Override
@ -51,35 +62,49 @@ public List<R> consume(
final PersistenceContext persistenceContext = session.getPersistenceContext(); final PersistenceContext persistenceContext = session.getPersistenceContext();
persistenceContext.getLoadContexts().register( jdbcValuesSourceProcessingState ); persistenceContext.getLoadContexts().register( jdbcValuesSourceProcessingState );
boolean uniqueRows = false;
final Class<R> resultJavaType = rowReader.getResultJavaType();
if ( uniqueFilter && resultJavaType != null && ! resultJavaType.isArray() ) {
final EntityPersister entityDescriptor = session.getFactory().getMetamodel().findEntityDescriptor( resultJavaType );
if ( entityDescriptor != null ) {
uniqueRows = true;
}
}
final List<R> results = new ArrayList<>(); final List<R> results = new ArrayList<>();
while ( rowProcessingState.next() ) { if ( uniqueSemantic == UniqueSemantic.NONE ) {
final R row = rowReader.readRow( rowProcessingState, processingOptions ); while ( rowProcessingState.next() ) {
results.add( rowReader.readRow( rowProcessingState, processingOptions ) );
boolean add = true; rowProcessingState.finishRowProcessing();
if ( uniqueRows ) { }
if ( results.contains( row ) ) { }
add = false; else {
boolean uniqueRows = false;
final Class<R> resultJavaType = rowReader.getResultJavaType();
if ( resultJavaType != null && !resultJavaType.isArray() ) {
final EntityPersister entityDescriptor = session.getFactory().getMetamodel().findEntityDescriptor(
resultJavaType );
if ( entityDescriptor != null ) {
uniqueRows = true;
} }
} }
while ( rowProcessingState.next() ) {
if ( add ) { final R row = rowReader.readRow( rowProcessingState, processingOptions );
results.add( row ); boolean add = true;
if ( uniqueRows ) {
if ( results.contains( row ) ) {
if ( uniqueSemantic == UniqueSemantic.ASSERT && !rowProcessingState.hasCollectionInitializers() ) {
throw new HibernateException(
"More than one row with the given identifier was found: " +
jdbcValuesSourceProcessingState.getExecutionContext()
.getEntityId() +
", for class: " +
resultJavaType.getName()
);
}
add = false;
}
}
if ( add ) {
results.add( row );
}
rowProcessingState.finishRowProcessing();
} }
rowProcessingState.finishRowProcessing();
} }
persistenceContext.initializeNonLazyCollections(); persistenceContext.initializeNonLazyCollections();
jdbcValuesSourceProcessingState.finishUp( ); jdbcValuesSourceProcessingState.finishUp();
return results; return results;
} }
finally { finally {

View File

@ -16,7 +16,7 @@
--> -->
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Car"> <class name="Car">

View File

@ -6,7 +6,7 @@
*/ */
//$Id: Car.java 5686 2005-02-12 07:27:32Z steveebersole $ //$Id: Car.java 5686 2005-02-12 07:27:32Z steveebersole $
package org.hibernate.test.id; package org.hibernate.orm.test.id;
/** /**

View File

@ -1,44 +1,40 @@
package org.hibernate.test.id; package org.hibernate.orm.test.id;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.MapsId; import javax.persistence.MapsId;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import org.hibernate.Transaction;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Test; import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
/** /**
* @author Nathan Xu * @author Nathan Xu
*/ */
public class ForeignGeneratorTest extends BaseCoreFunctionalTestCase { @DomainModel(
annotatedClasses = {
@Override ForeignGeneratorTest.Product.class,
protected Class<?>[] getAnnotatedClasses() { ForeignGeneratorTest.ProductDetails.class
return new Class<?>[] { }
Product.class, )
ProductDetails.class @SessionFactory
}; public class ForeignGeneratorTest {
}
@Test @Test
@TestForIssue( jiraKey = "HHH-13456") @TestForIssue(jiraKey = "HHH-13456")
public void testForeignGeneratorInStatelessSession() { public void testForeignGeneratorInStatelessSession(SessionFactoryScope scope) {
scope.inStatelessTransaction( statelessSession -> {
inStatelessSession(statelessSession -> {
Transaction tx = statelessSession.beginTransaction();
Product product = new Product(); Product product = new Product();
ProductDetails productDetails = new ProductDetails( product ); ProductDetails productDetails = new ProductDetails( product );
statelessSession.insert( productDetails ); statelessSession.insert( productDetails );
} );
tx.commit();
});
} }
@Entity(name = "Product") @Entity(name = "Product")
@ -63,7 +59,7 @@ public static class ProductDetails {
public ProductDetails() { public ProductDetails() {
} }
public ProductDetails( Product product ) { public ProductDetails(Product product) {
this.product = product; this.product = product;
} }
} }

View File

@ -0,0 +1,81 @@
/*
* 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.orm.test.id;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Emmanuel Bernard
*/
@DomainModel(
xmlMappings = {
"org/hibernate/orm/test/id/Car.hbm.xml",
"org/hibernate/orm/test/id/Plane.hbm.xml",
"org/hibernate/orm/test/id/Radio.hbm.xml"
}
)
@SessionFactory
public class MultipleHiLoPerTableGeneratorTest {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "delete from Car" ).executeUpdate();
session.createQuery( "delete from Plane" ).executeUpdate();
session.createQuery( "delete from Radio" ).executeUpdate();
}
);
}
@Test
public void testDistinctId(SessionFactoryScope scope) {
int testLength = 8;
Car[] cars = new Car[testLength];
scope.inTransaction(
session -> {
Plane[] planes = new Plane[testLength];
for ( int i = 0; i < testLength; i++ ) {
cars[i] = new Car();
cars[i].setColor( "Color" + i );
planes[i] = new Plane();
planes[i].setNbrOfSeats( i );
session.persist( cars[i] );
//s.persist(planes[i]);
}
}
);
for ( int i = 0; i < testLength; i++ ) {
assertEquals( i + 1, cars[i].getId().intValue() );
//assertEquals(i+1, planes[i].getId().intValue());
}
}
@Test
public void testAllParams(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Radio radio = new Radio();
radio.setFrequency( "32 MHz" );
session.persist( radio );
assertEquals( new Integer( 1 ), radio.getId() );
radio = new Radio();
radio.setFrequency( "32 MHz" );
session.persist( radio );
assertEquals( new Integer( 2 ), radio.getId() );
}
);
}
}

View File

@ -0,0 +1,73 @@
/*
* 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.orm.test.id;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Emmanuel Bernard
*/
@DomainModel(
xmlMappings = {
"org/hibernate/orm/test/id/Car.hbm.xml"
}
)
@SessionFactory
public class MultipleHiLoPerTableGeneratorWithRollbackTest {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "delete from Car" ).executeUpdate();
}
);
}
@Test
public void testRollingBack(SessionFactoryScope scope) {
int testLength = 3;
Long lastId = scope.fromSession(
session -> {
session.getTransaction().begin();
try {
Long id = null;
for ( int i = 0; i < testLength; i++ ) {
Car car = new Car();
car.setColor( "color " + i );
session.save( car );
id = car.getId();
}
return id;
}
finally {
session.getTransaction().rollback();
}
}
);
Car car = new Car();
scope.inTransaction(
session -> {
car.setColor( "blue" );
session.save( car );
session.flush();
}
);
assertEquals( lastId.longValue() + 1, car.getId().longValue(), "id generation was rolled back" );
}
}

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id; package org.hibernate.orm.test.id;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
@ -13,37 +13,37 @@
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Before; import org.hibernate.testing.orm.junit.SessionFactory;
import org.junit.Test; import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.Assert.fail;
/** /**
* @author Gail Badner * @author Gail Badner
*/ */
public class NonUniqueIdTest extends BaseNonConfigCoreFunctionalTestCase { @DomainModel(
annotatedClasses = NonUniqueIdTest.Category.class
)
@SessionFactory
public class NonUniqueIdTest {
@Override @BeforeAll
protected Class[] getAnnotatedClasses() { public void setup(SessionFactoryScope scope) {
return new Class[] { Category.class };
}
@Before
public void setup() {
// Drop and recreate table so it has no primary key. The drop is done in a separate transaction because // Drop and recreate table so it has no primary key. The drop is done in a separate transaction because
// some databases do not support dropping and recreating in the same transaction. // some databases do not support dropping and recreating in the same transaction.
doInHibernate( scope.inTransaction(
this::sessionFactory,
session -> { session -> {
session.createNativeQuery( session.createNativeQuery(
"DROP TABLE CATEGORY" "DROP TABLE CATEGORY"
).executeUpdate(); ).executeUpdate();
} }
); );
doInHibernate(
this::sessionFactory, scope.inTransaction(
session -> { session -> {
session.createNativeQuery( session.createNativeQuery(
"create table CATEGORY( id integer not null, name varchar(255) )" "create table CATEGORY( id integer not null, name varchar(255) )"
@ -58,24 +58,32 @@ public void setup() {
); );
} }
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from Category" ).executeUpdate()
);
}
@Test @Test
@TestForIssue( jiraKey = "HHH-12802" ) @TestForIssue(jiraKey = "HHH-12802")
public void testLoadEntityWithNonUniqueId() { public void testLoadEntityWithNonUniqueId(SessionFactoryScope scope) {
try { try {
doInHibernate( scope.inTransaction(
this::sessionFactory,
session -> { session -> {
session.get( Category.class, 1 ); session.get( Category.class, 1 );
fail( "should have failed because there are 2 entities with id == 1" ); fail( "should have failed because there are 2 entities with id == 1" );
} }
); );
} }
catch ( HibernateException ex) { catch (HibernateException ex) {
// expected // expected
} }
} }
@Entity @Entity(name = "Category")
@Table(name = "CATEGORY") @Table(name = "CATEGORY")
public static class Category { public static class Category {
@Id @Id

View File

@ -9,7 +9,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Person"> <class name="Person">
<id name="id" column="id"> <id name="id" column="id">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id; package org.hibernate.orm.test.id;
public class Person { public class Person {

View File

@ -16,7 +16,7 @@
--> -->
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Plane"> <class name="Plane">

View File

@ -6,7 +6,7 @@
*/ */
//$Id: Plane.java 5686 2005-02-12 07:27:32Z steveebersole $ //$Id: Plane.java 5686 2005-02-12 07:27:32Z steveebersole $
package org.hibernate.test.id; package org.hibernate.orm.test.id;
/** /**

View File

@ -21,95 +21,84 @@
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.test.id; package org.hibernate.orm.test.id;
import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Properties;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Test; import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger; import static org.hibernate.cfg.AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
/** /**
* @author Andrea Boriero * @author Andrea Boriero
*/ */
@TestForIssue(jiraKey = "HHH-9287") @TestForIssue(jiraKey = "HHH-9287")
public class PooledHiLoSequenceIdentifierTest extends BaseCoreFunctionalTestCase { @DomainModel(
annotatedClasses = PooledHiLoSequenceIdentifierTest.SequenceIdentifier.class
)
@SessionFactory
@ServiceRegistry(settings = @Setting(name = USE_NEW_ID_GENERATOR_MAPPINGS, value = "true"))
public class PooledHiLoSequenceIdentifierTest {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from sequenceIdentifier" ).executeUpdate()
);
}
@Test @Test
public void testSequenceIdentifierGenerator() { public void testSequenceIdentifierGenerator(SessionFactoryScope scope) {
Session s = null; scope.inTransaction(
Transaction tx = null; session -> {
try { for ( int i = 0; i < 5; i++ ) {
s = openSession(); session.persist( new SequenceIdentifier() );
tx = s.beginTransaction(); }
session.flush();
for ( int i = 0; i < 5; i++ ) { assertEquals( 5, countInsertedRows( session ) );
s.persist( new SequenceIdentifier() );
}
s.flush();
assertEquals( 5, countInsertedRows( s ) ); insertNewRow( session );
insertNewRow( session );
insertNewRow( s ); assertEquals( 7, countInsertedRows( session ) );
insertNewRow( s );
assertEquals( 7, countInsertedRows( s ) ); List<Number> ids = session.createQuery( "SELECT id FROM sequenceIdentifier" ).list();
List<Number> ids = s.createQuery( "SELECT id FROM sequenceIdentifier" ).list(); assertEquals( 7, ids.size() );
for ( Number id : ids ) {
log.debug( "Found id: " + id );
}
for ( int i = 0; i < 3; i++ ) { for ( int i = 0; i < 3; i++ ) {
s.persist( new SequenceIdentifier() ); session.persist( new SequenceIdentifier() );
} }
s.flush(); session.flush();
assertEquals( 10, countInsertedRows( s ) ); assertEquals( 10, countInsertedRows( session ) );
} }
finally { );
if ( tx != null ) {
tx.rollback();
}
s.close();
}
} }
private int countInsertedRows(Session s) { private int countInsertedRows(Session s) {
return ((Number) s.createNativeQuery( "SELECT COUNT(*) FROM sequenceIdentifier" ) return ( (Number) s.createNativeQuery( "SELECT COUNT(*) FROM sequenceIdentifier" )
.uniqueResult()).intValue(); .uniqueResult() ).intValue();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {SequenceIdentifier.class};
}
@Override
protected void configure(Configuration configuration) {
Properties properties = configuration.getProperties();
properties.put( "hibernate.id.new_generator_mappings", "true" );
} }
@Entity(name = "sequenceIdentifier") @Entity(name = "sequenceIdentifier")
@ -125,6 +114,8 @@ public static class SequenceIdentifier {
) )
@GeneratedValue(strategy = GenerationType.TABLE, generator = "sampleGenerator") @GeneratedValue(strategy = GenerationType.TABLE, generator = "sampleGenerator")
private Long id; private Long id;
private String name;
} }
private void insertNewRow(Session session) { private void insertNewRow(Session session) {
@ -132,19 +123,21 @@ private void insertNewRow(Session session) {
final SessionFactoryImplementor sfi = si.getFactory(); final SessionFactoryImplementor sfi = si.getFactory();
session.doWork( session.doWork(
new Work() { connection -> {
@Override PreparedStatement statement = null;
public void execute(Connection connection) throws SQLException { try {
PreparedStatement statement = null; statement = connection.prepareStatement( "INSERT INTO sequenceIdentifier VALUES (?,?)" );
try { statement.setObject(
statement = connection.prepareStatement( "INSERT INTO sequenceIdentifier VALUES (?)" ); 1,
statement.setObject( 1, sfi.getIdentifierGenerator( SequenceIdentifier.class.getName() ).generate( si, null ) ); sfi.getIdentifierGenerator( SequenceIdentifier.class.getName() )
statement.executeUpdate(); .generate( si, null )
} );
finally { statement.setString( 2,"name" );
if ( statement != null ) { statement.executeUpdate();
statement.close(); }
} finally {
if ( statement != null ) {
statement.close();
} }
} }
} }

View File

@ -14,7 +14,7 @@
--> -->
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Product" table="t_product"> <class name="Product" table="t_product">
<id name="name"> <id name="name">

View File

@ -6,7 +6,7 @@
*/ */
//$Id: $ //$Id: $
package org.hibernate.test.id; package org.hibernate.orm.test.id;
/** /**

View File

@ -17,7 +17,7 @@
--> -->
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Radio"> <class name="Radio">

View File

@ -6,7 +6,7 @@
*/ */
//$Id: Radio.java 5686 2005-02-12 07:27:32Z steveebersole $ //$Id: Radio.java 5686 2005-02-12 07:27:32Z steveebersole $
package org.hibernate.test.id; package org.hibernate.orm.test.id;
/** /**

View File

@ -9,7 +9,7 @@
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.id"> <hibernate-mapping package="org.hibernate.orm.test.id">
<class name="Person"> <class name="Person">
<id name="id" column="id"> <id name="id" column="id">

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id; package org.hibernate.orm.test.id;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -12,23 +12,31 @@
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.SequenceGenerator; import javax.persistence.SequenceGenerator;
import org.hibernate.Session; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.Transaction;
import org.hibernate.dialect.SQLServer2012Dialect;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Test; import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue;
public class SQLServer2012SequenceGeneratorAnnotationTest extends BaseCoreFunctionalTestCase {
@DomainModel(
@Override annotatedClasses = SQLServer2012SequenceGeneratorAnnotationTest.Person.class
protected Class<?>[] getAnnotatedClasses() { )
return new Class[] { Person.class }; @SessionFactory
public class SQLServer2012SequenceGeneratorAnnotationTest {
@AfterEach
public void tearDown(SessionFactoryScope scope){
scope.inTransaction(
session ->
session.createQuery( "delete from Person" ).executeUpdate()
);
} }
/** /**
@ -38,20 +46,15 @@ protected Class<?>[] getAnnotatedClasses() {
*/ */
@Test @Test
@TestForIssue(jiraKey = "HHH-8814") @TestForIssue(jiraKey = "HHH-8814")
@RequiresDialect(value=SQLServer2012Dialect.class) @RequiresDialect(value = SQLServerDialect.class, version = 2012)
public void testStartOfSequence() { public void testStartOfSequence(SessionFactoryScope scope) {
final Person person = doInHibernate( this::sessionFactory, session -> { final Person person = scope.fromTransaction( session -> {
final Person _person = new Person(); final Person _person = new Person();
session.persist(_person); session.persist(_person);
return _person; return _person;
} ); } );
assertTrue(person.getId() == 10); assertEquals(10, person.getId());
}
@Override
protected boolean isCleanupTestDataRequired() {
return true;
} }
@Entity(name = "Person") @Entity(name = "Person")

View File

@ -0,0 +1,52 @@
/*
* 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.orm.test.id;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DomainModel(
xmlMappings = "org/hibernate/orm/test/id/SQLServer2012Person.hbm.xml"
)
@SessionFactory
public class SQLServer2012SequenceGeneratorTest {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from Person" ).executeUpdate()
);
}
/**
* SQL server requires that sequence be initialized to something other than the minimum value for the type
* (e.g., Long.MIN_VALUE). For generator = "sequence", the initial value must be provided as a parameter.
* For this test, the sequence is initialized to 10.
*/
@Test
@TestForIssue(jiraKey = "HHH-8814")
@RequiresDialect(value = SQLServerDialect.class, version = 2012)
public void testStartOfSequence(SessionFactoryScope scope) {
final Person person = scope.fromTransaction( session -> {
final Person _person = new Person();
session.persist( _person );
return _person;
} );
assertEquals( 10, person.getId() );
}
}

View File

@ -0,0 +1,65 @@
/*
* 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.orm.test.id;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.jdbc.SQLStatementInspector;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DomainModel(
xmlMappings = "org/hibernate/orm/test/id/Person.hbm.xml"
)
@SessionFactory(statementInspectorClass = SQLStatementInspector.class)
@ServiceRegistry(
settings = @Setting(name = Environment.USE_NEW_ID_GENERATOR_MAPPINGS, value = "false")
)
public class SequenceGeneratorTest {
/**
* This seems a little trivial, but we need to guarantee that all Dialects start their sequences on a non-0 value.
*/
@Test
@TestForIssue(jiraKey = "HHH-8814")
@RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class)
@SkipForDialect(
dialectClass = SQLServerDialect.class,
version = 2012,
reason = "SQLServer2012Dialect initializes sequence to minimum value (e.g., Long.MIN_VALUE; Hibernate assumes it is uninitialized.",
matchSubTypes = true
)
public void testStartOfSequence(SessionFactoryScope scope) {
final Person person = new Person();
scope.inTransaction(
session -> {
session.persist( person );
}
);
assertTrue( person.getId() > 0 );
final SQLStatementInspector statementInspector = (SQLStatementInspector) scope.getStatementInspector();
assertTrue( statementInspector.getSqlQueries()
.stream()
.filter( sql -> sql.contains( "product_sequence" ) )
.findFirst()
.isPresent() );
}
}

View File

@ -0,0 +1,53 @@
/*
* 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.orm.test.id;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author Emmanuel Bernard
*/
@DomainModel(
xmlMappings = "org/hibernate/orm/test/id/Product.hbm.xml"
)
@ServiceRegistry(settings = @Setting(name = Environment.USE_IDENTIFIER_ROLLBACK, value = "true"))
@SessionFactory
public class UseIdentifierRollbackTest {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from Product" ).executeUpdate()
);
}
@Test
public void testSimpleRollback(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Product prod = new Product();
assertNull( prod.getName() );
session.persist( prod );
session.flush();
assertNotNull( prod.getName() );
}
);
}
}

View File

@ -0,0 +1,133 @@
/*
* 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.orm.test.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@SkipForDialect(dialectClass = MySQLDialect.class, version = 5, matchSubTypes = true, reason = "BLOB/TEXT column 'id' used in key specification without a key length")
@SkipForDialect(dialectClass = OracleDialect.class, version = 9, matchSubTypes = true, reason = "ORA-02329: column of datatype LOB cannot be unique or a primary key")
@DomainModel(
annotatedClasses = ByteArrayIdTest.DemoEntity.class
)
@SessionFactory
public class ByteArrayIdTest {
@BeforeEach
public void prepare(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new Byte[] {
(byte) ( i + 1 ),
(byte) ( i + 2 ),
(byte) ( i + 3 ),
(byte) ( i + 4 )
};
entity.name = "Simple name " + i;
session.persist( entity );
}
}
);
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from ByteArrayIdTest$DemoEntity" ).executeUpdate()
);
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
List results = query.list();
session.delete( results.get( 0 ) );
session.delete( results.get( 1 ) );
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
}
);
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates(SessionFactoryScope scope) {
final String lastResultName = scope.fromTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
return results.get( 0 ).name;
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>();
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
}
);
}
@Entity
@Table(name = "DemoEntity")
public static class DemoEntity {
@Id
public Byte[] id;
public String name;
}
}

View File

@ -0,0 +1,127 @@
/*
* 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.orm.test.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@DomainModel(
annotatedClasses = CharacterArrayIdTest.DemoEntity.class
)
@SessionFactory
public class CharacterArrayIdTest {
@BeforeEach
public void prepare(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new Character[] {
(char) ( i + 'a' ),
(char) ( i + 'b' ),
(char) ( i + 'c' ),
(char) ( i + 'd' )
};
entity.name = "Simple name " + i;
session.persist( entity );
}
}
);
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from CharacterArrayIdTest$DemoEntity" ).executeUpdate()
);
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
List results = query.list();
session.delete( results.get( 0 ) );
session.delete( results.get( 1 ) );
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
}
);
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates(SessionFactoryScope scope) {
final String lastResultName = scope.fromTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
return results.get( 0 ).name;
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>();
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
}
);
}
@Entity
@Table(name = "DemoEntity")
public static class DemoEntity {
@Id
public Character[] id;
public String name;
}
}

View File

@ -0,0 +1,132 @@
/*
* 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.orm.test.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@SkipForDialect(dialectClass = MySQLDialect.class, version = 5, reason = "BLOB/TEXT column 'id' used in key specification without a key length")
@SkipForDialect(dialectClass = OracleDialect.class, version = 9, matchSubTypes = true, reason = "ORA-02329: column of datatype LOB cannot be unique or a primary key")
@DomainModel(
annotatedClasses = PrimitiveByteArrayIdTest.DemoEntity.class
)
@SessionFactory
public class PrimitiveByteArrayIdTest {
@BeforeEach
public void prepare(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new byte[] {
(byte) ( i + 1 ),
(byte) ( i + 2 ),
(byte) ( i + 3 ),
(byte) ( i + 4 )
};
entity.name = "Simple name " + i;
session.persist( entity );
}
}
);
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from PrimitiveByteArrayIdTest$DemoEntity" ).executeUpdate()
);
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
List results = query.list();
session.delete( results.get( 0 ) );
session.delete( results.get( 1 ) );
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
}
);
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates(SessionFactoryScope scope) {
final String lastResultName = scope.fromTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
return results.get( 0 ).name;
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>();
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
}
);
}
@Entity
@Table(name = "DemoEntity")
public static class DemoEntity {
@Id
public byte[] id;
public String name;
}
}

View File

@ -0,0 +1,127 @@
/*
* 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.orm.test.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@DomainModel(
annotatedClasses = PrimitiveCharacterArrayIdTest.DemoEntity.class
)
@SessionFactory
public class PrimitiveCharacterArrayIdTest {
@BeforeEach
public void prepare(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new char[] {
(char) ( i + 'a' ),
(char) ( i + 'b' ),
(char) ( i + 'c' ),
(char) ( i + 'd' )
};
entity.name = "Simple name " + i;
session.persist( entity );
}
}
);
}
@AfterEach
public void cleanup(SessionFactoryScope scope) {
scope.inTransaction(
session ->
session.createQuery( "delete from PrimitiveCharacterArrayIdTest$DemoEntity" ).executeUpdate()
);
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
List results = query.list();
session.delete( results.get( 0 ) );
session.delete( results.get( 1 ) );
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
}
);
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates(SessionFactoryScope scope) {
final String lastResultName = scope.fromTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
return results.get( 0 ).name;
}
);
scope.inTransaction(
session -> {
Query query = session.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>();
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
}
);
}
@Entity
@Table(name = "DemoEntity")
public static class DemoEntity {
@Id
public char[] id;
public String name;
}
}

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.sequence; package org.hibernate.orm.test.id.sequence;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -14,7 +14,6 @@
import javax.persistence.Table; import javax.persistence.Table;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.relational.AuxiliaryDatabaseObject;
import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.Sequence; import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
@ -23,33 +22,34 @@
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class LegacySequenceExportTest extends BaseUnitTestCase { @BaseUnitTest
public class LegacySequenceExportTest {
private StandardServiceRegistry ssr; private StandardServiceRegistry ssr;
@Before @BeforeEach
public void prepare() { public void prepare() {
ssr = new StandardServiceRegistryBuilder() ssr = new StandardServiceRegistryBuilder()
.applySetting( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false" ) .applySetting( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "false" )
.build(); .build();
} }
@After @AfterEach
public void destroy() { public void destroy() {
StandardServiceRegistryBuilder.destroy( ssr ); StandardServiceRegistryBuilder.destroy( ssr );
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9936" ) @TestForIssue(jiraKey = "HHH-9936")
public void testMultipleUsesOfDefaultSequenceName() { public void testMultipleUsesOfDefaultSequenceName() {
final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr )
.addAnnotatedClass( Entity1.class ) .addAnnotatedClass( Entity1.class )
@ -70,7 +70,7 @@ public void testMultipleUsesOfDefaultSequenceName() {
} }
@Test @Test
@TestForIssue( jiraKey = "HHH-9936" ) @TestForIssue(jiraKey = "HHH-9936")
public void testMultipleUsesOfExplicitSequenceName() { public void testMultipleUsesOfExplicitSequenceName() {
final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr ) final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources( ssr )
.addAnnotatedClass( Entity3.class ) .addAnnotatedClass( Entity3.class )
@ -90,37 +90,37 @@ public void testMultipleUsesOfExplicitSequenceName() {
assertEquals( 1, count ); assertEquals( 1, count );
} }
@Entity( name = "Entity1" ) @Entity(name = "Entity1")
@Table( name = "Entity1" ) @Table(name = "Entity1")
public static class Entity1 { public static class Entity1 {
@Id @Id
@GeneratedValue( strategy = GenerationType.SEQUENCE ) @GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer id; public Integer id;
} }
@Entity( name = "Entity2" ) @Entity(name = "Entity2")
@Table( name = "Entity2" ) @Table(name = "Entity2")
public static class Entity2 { public static class Entity2 {
@Id @Id
@GeneratedValue( strategy = GenerationType.SEQUENCE ) @GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer id; public Integer id;
} }
@Entity( name = "Entity3" ) @Entity(name = "Entity3")
@Table( name = "Entity3" ) @Table(name = "Entity3")
public static class Entity3 { public static class Entity3 {
@Id @Id
@GeneratedValue( strategy = GenerationType.SEQUENCE ) @GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator( name = "my_sequence" ) @SequenceGenerator(name = "my_sequence")
public Integer id; public Integer id;
} }
@Entity( name = "Entity4" ) @Entity(name = "Entity4")
@Table( name = "Entity4" ) @Table(name = "Entity4")
public static class Entity4 { public static class Entity4 {
@Id @Id
@GeneratedValue( strategy = GenerationType.SEQUENCE ) @GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator( name = "my_sequence" ) @SequenceGenerator(name = "my_sequence")
public Integer id; public Integer id;
} }
} }

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.sequence; package org.hibernate.orm.test.id.sequence;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -30,12 +30,13 @@
import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable; import org.hibernate.testing.logger.Triggerable;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* @author Gail Badner * @author Gail Badner

View File

@ -0,0 +1,71 @@
/*
* 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.orm.test.id.sequence;
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.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
/**
* @author Steve Ebersole
*/
@DomainModel(
annotatedClasses = OptimizerTest.TheEntity.class
)
@SessionFactory
public class OptimizerTest {
@Test
@TestForIssue(jiraKey = "HHH-10166")
public void testGenerationPastBound(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
for ( int i = 0; i < 100; i++ ) {
TheEntity entity = new TheEntity( Integer.toString( i ) );
session.save( entity );
}
}
);
scope.inTransaction(
session -> {
TheEntity number100 = session.get( TheEntity.class, 100 );
assertThat( number100, notNullValue() );
session.createQuery( "delete TheEntity" ).executeUpdate();
}
);
}
@Entity(name = "TheEntity")
@Table(name = "TheEntity")
public static class TheEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq1")
@SequenceGenerator(name = "seq1", sequenceName = "the_sequence")
public Integer id;
public String someString;
public TheEntity() {
}
public TheEntity(String someString) {
this.someString = someString;
}
}
}

View File

@ -4,68 +4,66 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.sequence; package org.hibernate.orm.test.id.sequence;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.RequiresDialect;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.SequenceGenerator; import javax.persistence.SequenceGenerator;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import org.hibernate.cfg.Environment;
import static org.junit.Assert.fail; import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* @author Vlad Mhalcea * @author Vlad Mhalcea
*/ */
@RequiresDialect(jiraKey = "HHH-13106", value = PostgreSQLDialect.class) @TestForIssue(jiraKey = "HHH-13106")
public class PostgreSQLIdentitySequenceTest extends BaseEntityManagerFunctionalTestCase { @RequiresDialect(value = PostgreSQLDialect.class, version = 10)
@Jpa(
@Override annotatedClasses = PostgreSQLIdentitySequenceTest.Role.class
protected Class[] getAnnotatedClasses() { )
return new Class[] { Role.class }; public class PostgreSQLIdentitySequenceTest {
}
private DriverManagerConnectionProviderImpl connectionProvider; private DriverManagerConnectionProviderImpl connectionProvider;
@Override @BeforeAll
public void buildEntityManagerFactory() { public void produceEntityManagerFactory() throws SQLException {
connectionProvider = new DriverManagerConnectionProviderImpl(); connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure( Environment.getProperties() ); connectionProvider.configure( Environment.getProperties() );
try(Connection connection = connectionProvider.getConnection(); try (Connection connection = connectionProvider.getConnection();
Statement statement = connection.createStatement()) { Statement statement = connection.createStatement()) {
statement.execute( "DROP TABLE IF EXISTS roles CASCADE" ); statement.execute( "DROP TABLE IF EXISTS roles CASCADE" );
statement.execute( "CREATE TABLE roles ( id BIGINT NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY )" ); statement.execute( "CREATE TABLE roles ( id BIGINT NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY )" );
} }
catch (SQLException e) {
fail(e.getMessage());
}
super.buildEntityManagerFactory();
} }
@Override @AfterAll
public void releaseResources() { public void releaseResources() {
super.releaseResources();
try(Connection connection = connectionProvider.getConnection(); try (Connection connection = connectionProvider.getConnection();
Statement statement = connection.createStatement()) { Statement statement = connection.createStatement()) {
statement.execute( "DROP TABLE IF EXISTS roles CASCADE" ); statement.execute( "DROP TABLE IF EXISTS roles CASCADE" );
} }
catch (SQLException e) { catch (SQLException e) {
fail(e.getMessage()); fail( e.getMessage() );
} }
if ( connectionProvider != null ) { if ( connectionProvider != null ) {
@ -74,8 +72,8 @@ public void releaseResources() {
} }
@Test @Test
public void test() { public void test(EntityManagerFactoryScope scope) {
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
Role role = new Role(); Role role = new Role();
entityManager.persist( role ); entityManager.persist( role );
} ); } );

View File

@ -4,35 +4,37 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.sequence; package org.hibernate.orm.test.id.sequence;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.RequiresDialect;
import org.junit.Test;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import org.hibernate.dialect.PostgreSQLDialect;
import static org.junit.Assert.assertNotNull;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* @author Vlad Mhalcea * @author Vlad Mhalcea
*/ */
@RequiresDialect(jiraKey = "HHH-13202", value = PostgreSQLDialect.class) @TestForIssue(jiraKey = "HHH-13202")
public class PostgreSQLIdentitySupportTest extends BaseEntityManagerFunctionalTestCase { @RequiresDialect(value = PostgreSQLDialect.class)
@Jpa(
@Override annotatedClasses = PostgreSQLIdentitySupportTest.Role.class
protected Class[] getAnnotatedClasses() { )
return new Class[] { Role.class }; public class PostgreSQLIdentitySupportTest {
}
@Test @Test
public void test() { public void test(EntityManagerFactoryScope scope) {
Role _role = doInJPA( this::entityManagerFactory, entityManager -> { Role _role = scope.fromTransaction( entityManager -> {
Role role = new Role(); Role role = new Role();
entityManager.persist( role ); entityManager.persist( role );
@ -40,9 +42,9 @@ public void test() {
return role; return role;
} ); } );
doInJPA( this::entityManagerFactory, entityManager -> { scope.inTransaction( entityManager -> {
Role role = entityManager.find( Role.class, _role.getId() ); Role role = entityManager.find( Role.class, _role.getId() );
assertNotNull(role); assertNotNull( role );
} ); } );
} }

View File

@ -4,68 +4,65 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.usertype; package org.hibernate.orm.test.id.usertype;
import java.io.Serializable; import java.io.Serializable;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Comparator; import java.util.Comparator;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
import org.junit.Test;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.annotations.Type; import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDef;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.type.LongType; import org.hibernate.type.LongType;
import org.hibernate.usertype.UserType; import org.hibernate.usertype.UserType;
public class UserTypeComparableIdTest extends BaseCoreFunctionalTestCase { import org.hibernate.testing.TestForIssue;
@Override import org.hibernate.testing.orm.junit.DomainModel;
protected void configure(Configuration configuration) { import org.hibernate.testing.orm.junit.ServiceRegistry;
configuration.setProperty( AvailableSettings.ORDER_UPDATES, "true" ); import org.hibernate.testing.orm.junit.SessionFactory;
} import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.Test;
@DomainModel(
annotatedClasses = UserTypeComparableIdTest.SomeEntity.class
)
@SessionFactory
@ServiceRegistry(
settings = @Setting(name = AvailableSettings.ORDER_UPDATES, value = "true")
)
public class UserTypeComparableIdTest {
@Test @Test
@TestForIssue(jiraKey = "HHH-8999") @TestForIssue(jiraKey = "HHH-8999")
public void testUserTypeId() { public void testUserTypeId(SessionFactoryScope scope) {
Session s = openSession();
s.beginTransaction();
SomeEntity e1 = new SomeEntity(); SomeEntity e1 = new SomeEntity();
CustomId e1Id = new CustomId( 1L );
e1.setCustomId( e1Id );
SomeEntity e2 = new SomeEntity(); SomeEntity e2 = new SomeEntity();
CustomId e2Id = new CustomId( 2L ); scope.inTransaction(
e2.setCustomId( e2Id ); session -> {
s.persist( e1 ); CustomId e1Id = new CustomId( 1L );
s.persist( e2 ); e1.setCustomId( e1Id );
s.getTransaction().commit(); CustomId e2Id = new CustomId( 2L );
s.close(); e2.setCustomId( e2Id );
session.persist( e1 );
session.persist( e2 );
}
);
s = openSession(); scope.inTransaction(
s.beginTransaction(); session -> {
e1 = s.get( SomeEntity.class, e1Id ); session.delete( session.get( SomeEntity.class, e1.getCustomId() ) );
e2 = s.get( SomeEntity.class, e2Id ); session.delete( session.get( SomeEntity.class, e2.getCustomId() ) );
s.delete( e1 ); }
s.delete( e2 ); );
s.getTransaction().commit();
s.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { SomeEntity.class };
} }
@ -139,7 +136,8 @@ public int[] sqlTypes() {
} }
@Override @Override
public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner)
throws SQLException {
Long value = rs.getLong( position ); Long value = rs.getLong( position );
return new CustomId( value ); return new CustomId( value );

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * 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>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.test.id.usertype; package org.hibernate.orm.test.id.usertype;
import java.io.Serializable; import java.io.Serializable;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -16,7 +16,6 @@
import javax.persistence.Table; import javax.persistence.Table;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.annotations.Type; import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDef;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -24,43 +23,41 @@
import org.hibernate.usertype.UserType; import org.hibernate.usertype.UserType;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.orm.junit.DomainModel;
import org.junit.Test; import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
public class UserTypeNonComparableIdTest extends BaseCoreFunctionalTestCase { @DomainModel(
annotatedClasses = UserTypeNonComparableIdTest.SomeEntity.class
)
@SessionFactory
public class UserTypeNonComparableIdTest {
@Test @Test
@TestForIssue(jiraKey = "HHH-8999") @TestForIssue(jiraKey = "HHH-8999")
public void testUserTypeId() { public void testUserTypeId(SessionFactoryScope scope) {
Session s = openSession();
s.beginTransaction();
SomeEntity e1 = new SomeEntity(); SomeEntity e1 = new SomeEntity();
CustomId e1Id = new CustomId( 1L );
e1.setCustomId( e1Id );
SomeEntity e2 = new SomeEntity(); SomeEntity e2 = new SomeEntity();
CustomId e2Id = new CustomId( 2L ); scope.inTransaction(
e2.setCustomId( e2Id ); session -> {
s.persist( e1 ); CustomId e1Id = new CustomId( 1L );
s.persist( e2 ); e1.setCustomId( e1Id );
s.getTransaction().commit(); CustomId e2Id = new CustomId( 2L );
s.close(); e2.setCustomId( e2Id );
session.persist( e1 );
session.persist( e2 );
}
);
s = openSession(); scope.inTransaction(
s.beginTransaction(); session -> {
e1 = s.get( SomeEntity.class, e1Id ); session.delete( session.get( SomeEntity.class, e1.getCustomId() ) );
e2 = s.get( SomeEntity.class, e2Id ); session.delete( session.get( SomeEntity.class, e2.getCustomId() ) );
s.delete( e1 ); }
s.delete( e2 ); );
s.getTransaction().commit();
s.close();
} }
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { SomeEntity.class };
}
@TypeDef( @TypeDef(
name = "customId", name = "customId",
typeClass = CustomIdType.class typeClass = CustomIdType.class
@ -126,7 +123,8 @@ public int[] sqlTypes() {
} }
@Override @Override
public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { public Object nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner)
throws SQLException {
Long value = rs.getLong( position ); Long value = rs.getLong( position );
return new CustomId( value ); return new CustomId( value );

View File

@ -1,108 +0,0 @@
/*
* 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.id;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
/**
* @author Emmanuel Bernard
*/
public class MultipleHiLoPerTableGeneratorTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[]{ "id/Car.hbm.xml", "id/Plane.hbm.xml", "id/Radio.hbm.xml" };
}
@Test
public void testDistinctId() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
int testLength = 8;
Car[] cars = new Car[testLength];
Plane[] planes = new Plane[testLength];
for (int i = 0; i < testLength ; i++) {
cars[i] = new Car();
cars[i].setColor("Color" + i);
planes[i] = new Plane();
planes[i].setNbrOfSeats(i);
s.persist(cars[i]);
//s.persist(planes[i]);
}
tx.commit();
s.close();
for (int i = 0; i < testLength ; i++) {
assertEquals(i+1, cars[i].getId().intValue());
//assertEquals(i+1, planes[i].getId().intValue());
}
s = openSession();
tx = s.beginTransaction();
s.createQuery( "delete from Car" ).executeUpdate();
tx.commit();
s.close();
}
@Test
public void testRollingBack() throws Throwable {
Session s = openSession();
Transaction tx = s.beginTransaction();
int testLength = 3;
Long lastId = null;
for (int i = 0; i < testLength ; i++) {
Car car = new Car();
car.setColor( "color " + i );
s.save( car );
lastId = car.getId();
}
tx.rollback();
s.close();
s = openSession();
tx = s.beginTransaction();
Car car = new Car();
car.setColor( "blue" );
s.save( car );
s.flush();
tx.commit();
s.close();
assertEquals( "id generation was rolled back", lastId.longValue() + 1, car.getId().longValue() );
s = openSession();
tx = s.beginTransaction();
s.createQuery( "delete Car" ).executeUpdate();
tx.commit();
s.close();
}
@Test
public void testAllParams() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Radio radio = new Radio();
radio.setFrequency("32 MHz");
s.persist(radio);
assertEquals( new Integer(1), radio.getId() );
radio = new Radio();
radio.setFrequency("32 MHz");
s.persist(radio);
assertEquals( new Integer(2), radio.getId() );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
s.createQuery( "delete from Radio" ).executeUpdate();
tx.commit();
s.close();
}
}

View File

@ -1,55 +0,0 @@
/*
* 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.id;
import java.util.List;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.SQLServer2012Dialect;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
public class SQLServer2012SequenceGeneratorTest extends BaseCoreFunctionalTestCase {
@Override
public String[] getMappings() {
return new String[] { "id/SQLServer2012Person.hbm.xml" };
}
/**
* SQL server requires that sequence be initialized to something other than the minimum value for the type
* (e.g., Long.MIN_VALUE). For generator = "sequence", the initial value must be provided as a parameter.
* For this test, the sequence is initialized to 10.
*/
@Test
@TestForIssue(jiraKey = "HHH-8814")
@RequiresDialect(value=SQLServer2012Dialect.class)
public void testStartOfSequence() {
final Person person = doInHibernate( this::sessionFactory, session -> {
final Person _person = new Person();
session.persist(_person);
return _person;
} );
assertTrue(person.getId() == 10);
}
@Override
protected boolean isCleanupTestDataRequired() {
return true;
}
}

View File

@ -1,72 +0,0 @@
/*
* 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.id;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.SQLServer2012Dialect;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.hibernate.testing.jdbc.SQLStatementInterceptor;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SequenceGeneratorTest extends BaseNonConfigCoreFunctionalTestCase {
private SQLStatementInterceptor sqlStatementInterceptor;
@Override
protected void configureSessionFactoryBuilder(SessionFactoryBuilder sfb) {
sqlStatementInterceptor = new SQLStatementInterceptor( sfb );
}
@Override
public String[] getMappings() {
return new String[] { "id/Person.hbm.xml" };
}
@Override
protected void addSettings(Map settings) {
settings.put( Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "false" );
}
/**
* This seems a little trivial, but we need to guarantee that all Dialects start their sequences on a non-0 value.
*/
@Test
@TestForIssue(jiraKey = "HHH-8814")
@RequiresDialectFeature(DialectChecks.SupportsSequences.class)
@SkipForDialect(
value = SQLServer2012Dialect.class,
comment = "SQLServer2012Dialect initializes sequence to minimum value (e.g., Long.MIN_VALUE; Hibernate assumes it is uninitialized."
)
public void testStartOfSequence() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
final Person person = new Person();
s.persist( person );
tx.commit();
s.close();
assertTrue( person.getId() > 0 );
assertTrue( sqlStatementInterceptor.getSqlQueries()
.stream()
.filter( sql -> sql.contains( "product_sequence" ) )
.findFirst()
.isPresent() );
}
}

View File

@ -1,46 +0,0 @@
/*
* 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.id;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* @author Emmanuel Bernard
*/
public class UseIdentifierRollbackTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[] { "id/Product.hbm.xml" };
}
public void configure(Configuration cfg) {
cfg.setProperty( Environment.USE_IDENTIFIER_ROLLBACK, "true");
super.configure( cfg );
}
@Test
public void testSimpleRollback() {
Session session = openSession();
Transaction t = session.beginTransaction();
Product prod = new Product();
assertNull( prod.getName() );
session.persist(prod);
session.flush();
assertNotNull( prod.getName() );
t.rollback();
session.close();
}
}

View File

@ -1,134 +0,0 @@
/*
* 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.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.Oracle9iDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@SkipForDialect(value = MySQL5Dialect.class, comment = "BLOB/TEXT column 'id' used in key specification without a key length")
@SkipForDialect(value = Oracle9iDialect.class, comment = "ORA-02329: column of datatype LOB cannot be unique or a primary key")
public class ByteArrayIdTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { DemoEntity.class };
}
@Before
public void prepare() {
Session s = openSession();
s.getTransaction().begin();
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new Byte[] {
(byte) ( i + 1 ),
(byte) ( i + 2 ),
(byte) ( i + 3 ),
(byte) ( i + 4 )
};
entity.name = "Simple name " + i;
s.persist( entity );
}
s.getTransaction().commit();
s.close();
}
@After
public void cleanup() {
Session s = openSession();
s.getTransaction().begin();
s.createQuery( "delete from ByteArrayIdTest$DemoEntity" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
List results = query.list();
s.delete( results.get( 0 ) );
s.delete( results.get( 1 ) );
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
s.getTransaction().commit();
s.close();
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
final String lastResultName = results.get( 0 ).name;
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM ByteArrayIdTest$DemoEntity s" );
results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>( );
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
s.getTransaction().commit();
s.close();
}
@Entity
@Table(name="DemoEntity")
public static class DemoEntity {
@Id
public Byte[] id;
public String name;
}
}

View File

@ -1,129 +0,0 @@
/*
* 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.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
public class CharacterArrayIdTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { DemoEntity.class };
}
@Before
public void prepare() {
Session s = openSession();
s.getTransaction().begin();
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new Character[] {
(char) ( i + 'a' ),
(char) ( i + 'b' ),
(char) ( i + 'c' ),
(char) ( i + 'd' )
};
entity.name = "Simple name " + i;
s.persist( entity );
}
s.getTransaction().commit();
s.close();
}
@After
public void cleanup() {
Session s = openSession();
s.getTransaction().begin();
s.createQuery( "delete from CharacterArrayIdTest$DemoEntity" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
List results = query.list();
s.delete( results.get( 0 ) );
s.delete( results.get( 1 ) );
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
s.getTransaction().commit();
s.close();
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
final String lastResultName = results.get( 0 ).name;
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM CharacterArrayIdTest$DemoEntity s" );
results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>( );
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
s.getTransaction().commit();
s.close();
}
@Entity
@Table(name="DemoEntity")
public static class DemoEntity {
@Id
public Character[] id;
public String name;
}
}

View File

@ -1,135 +0,0 @@
/*
* 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.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.Oracle9iDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
@SkipForDialect(value = MySQL5Dialect.class, comment = "BLOB/TEXT column 'id' used in key specification without a key length")
@SkipForDialect(value = Oracle9iDialect.class, comment = "ORA-02329: column of datatype LOB cannot be unique or a primary key")
public class PrimitiveByteArrayIdTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { DemoEntity.class };
}
@Before
public void prepare() {
Session s = openSession();
s.getTransaction().begin();
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new byte[] {
(byte) ( i + 1 ),
(byte) ( i + 2 ),
(byte) ( i + 3 ),
(byte) ( i + 4 )
};
entity.name = "Simple name " + i;
s.persist( entity );
}
s.getTransaction().commit();
s.close();
}
@After
public void cleanup() {
Session s = openSession();
s.getTransaction().begin();
s.createQuery( "delete from PrimitiveByteArrayIdTest$DemoEntity" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
List results = query.list();
s.delete( results.get( 0 ) );
s.delete( results.get( 1 ) );
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
s.getTransaction().commit();
s.close();
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
final String lastResultName = results.get( 0 ).name;
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM PrimitiveByteArrayIdTest$DemoEntity s" );
results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>( );
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
s.getTransaction().commit();
s.close();
}
@Entity
@Table(name="DemoEntity")
public static class DemoEntity {
@Id
public byte[] id;
public String name;
}
}

View File

@ -1,129 +0,0 @@
/*
* 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.id.array;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:p.krauzowicz@visiona.pl">Piotr Krauzowicz</a>
* @author Gail Badner
*/
public class PrimitiveCharacterArrayIdTest extends BaseCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { DemoEntity.class };
}
@Before
public void prepare() {
Session s = openSession();
s.getTransaction().begin();
for ( int i = 0; i < 3; i++ ) {
DemoEntity entity = new DemoEntity();
entity.id = new char[] {
(char) ( i + 'a' ),
(char) ( i + 'b' ),
(char) ( i + 'c' ),
(char) ( i + 'd' )
};
entity.name = "Simple name " + i;
s.persist( entity );
}
s.getTransaction().commit();
s.close();
}
@After
public void cleanup() {
Session s = openSession();
s.getTransaction().begin();
s.createQuery( "delete from PrimitiveCharacterArrayIdTest$DemoEntity" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
/**
* Removes two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleDeletions() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
List results = query.list();
s.delete( results.get( 0 ) );
s.delete( results.get( 1 ) );
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
assertEquals( 1, query.list().size() );
s.getTransaction().commit();
s.close();
}
/**
* Updates two records from database.
*/
@Test
@TestForIssue(jiraKey = "HHH-8999")
public void testMultipleUpdates() {
Session s = openSession();
s.getTransaction().begin();
Query query = s.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
List<DemoEntity> results = (List<DemoEntity>) query.list();
results.get( 0 ).name = "Different 0";
results.get( 1 ).name = "Different 1";
final String lastResultName = results.get( 0 ).name;
s.getTransaction().commit();
s.close();
s = openSession();
s.getTransaction().begin();
query = s.createQuery( "SELECT s FROM PrimitiveCharacterArrayIdTest$DemoEntity s" );
results = (List<DemoEntity>) query.list();
final Set<String> names = new HashSet<String>( );
for ( DemoEntity entity : results ) {
names.add( entity.name );
}
assertTrue( names.contains( "Different 0" ) );
assertTrue( names.contains( "Different 1" ) );
assertTrue( names.contains( lastResultName ) );
s.getTransaction().commit();
s.close();
}
@Entity
@Table(name="DemoEntity")
public static class DemoEntity {
@Id
public char[] id;
public String name;
}
}

View File

@ -1,71 +0,0 @@
/*
* 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.id.sequence;
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.Session;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Steve Ebersole
*/
public class OptimizerTest extends BaseNonConfigCoreFunctionalTestCase {
@Test
@TestForIssue( jiraKey = "HHH-10166" )
public void testGenerationPastBound() {
Session session = openSession();
session.getTransaction().begin();
for (int i = 0; i < 100; i++) {
TheEntity entity = new TheEntity( Integer.toString( i ) );
session.save( entity );
}
session.getTransaction().commit();
session.close();
session = openSession();
session.getTransaction().begin();
TheEntity number100 = session.get( TheEntity.class, 100 );
assertThat( number100, notNullValue() );
session.createQuery( "delete TheEntity" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { TheEntity.class };
}
@Entity( name = "TheEntity" )
@Table( name = "TheEntity" )
public static class TheEntity {
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "seq1" )
@SequenceGenerator( name = "seq1", sequenceName = "the_sequence" )
public Integer id;
public String someString;
public TheEntity() {
}
public TheEntity(String someString) {
this.someString = someString;
}
}
}