Merge remote-tracking branch 'upstream/wip/6.0' into wip/6.0

This commit is contained in:
Christian Beikov 2021-02-10 11:31:53 +01:00
commit 3eee006002
35 changed files with 826 additions and 742 deletions

View File

@ -270,89 +270,117 @@ public abstract class Dialect implements ConversionContext {
* These required functions include the functions defined by the JPA
* query language specification:
*
* * avg(arg) - aggregate function
* * count([distinct ]arg) - aggregate function
* * max(arg) - aggregate function
* * min(arg) - aggregate function
* * sum(arg) - aggregate function
* <ul>
* <li> avg(arg) - aggregate function
* <li> count([distinct ]arg) - aggregate function
* <li> max(arg) - aggregate function
* <li> min(arg) - aggregate function
* <li> sum(arg) - aggregate function
* </ul>
*
* * coalesce(arg0, arg1, ...)
* * nullif(arg0, arg1)
* <ul>
* <li> coalesce(arg0, arg1, ...)
* <li> nullif(arg0, arg1)
* </ul>
*
* * lower(arg)
* * upper(arg)
* * length(arg)
* * concat(arg0, arg1, ...)
* * locate(pattern, string[, start])
* * substring(string, start[, length])
* * trim([[spec ][character ]from] string)
* <ul>
* <li> lower(arg)
* <li> upper(arg)
* <li> length(arg)
* <li> concat(arg0, arg1, ...)
* <li> locate(pattern, string[, start])
* <li> substring(string, start[, length])
* <li> trim([[spec ][character ]from] string)
* </ul>
*
* * abs(arg)
* * mod(arg0, arg1)
* * sqrt(arg)
* <ul>
* <li> abs(arg)
* <li> mod(arg0, arg1)
* <li> sqrt(arg)
* </ul>
*
* * current date
* * current time
* * current timestamp
* <ul>
* <li> current date
* <li> current time
* <li> current timestamp
* </ul>
*
* Along with an additional set of functions defined by ANSI SQL:
*
* * any(arg) - aggregate function
* * every(arg) - aggregate function
* <ul>
* <li> any(arg) - aggregate function
* <li> every(arg) - aggregate function
* </ul>
*
* * cast(arg as Type)
* * extract(field from arg)
* <ul>
* <li> cast(arg as Type)
* <li> extract(field from arg)
* </ul>
*
* * ln(arg)
* * exp(arg)
* * power(arg0, arg1)
* * floor(arg)
* * ceiling(arg)
* <ul>
* <li> ln(arg)
* <li> exp(arg)
* <li> power(arg0, arg1)
* <li> floor(arg)
* <li> ceiling(arg)
* </ul>
*
* * position(pattern in string)
* * substring(string from start[ for length])
* * overlay(string placing replacement from start[ for length])
* <ul>
* <li> position(pattern in string)
* <li> substring(string from start[ for length])
* <li> overlay(string placing replacement from start[ for length])
* </ul>
*
* And the following functions for working with java.time types:
*
* * local date
* * local time
* * local datetime
* * offset datetime
* * instant
* <ul>
* <li> local date
* <li> local time
* <li> local datetime
* <li> offset datetime
* <li> instant
* </ul>
*
* And a number of additional "standard" functions:
*
* * left(string, length)
* * right(string, length)
* * replace(string, pattern, replacement)
* * pad(string with length spec[ character])
* <ul>
* <li> left(string, length)
* <li> right(string, length)
* <li> replace(string, pattern, replacement)
* <li> pad(string with length spec[ character])
* </ul>
*
* * sign(arg)
* * sin(arg)
* * cos(arg)
* * tan(arg)
* * asin(arg)
* * acos(arg)
* * atan(arg)
* * atan2(arg0, arg1)
* * round(arg0, arg1)
* * least(arg0, arg1, ...)
* * greatest(arg0, arg1, ...)
* <ul>
* <li> sign(arg)
* <li> sin(arg)
* <li> cos(arg)
* <li> tan(arg)
* <li> asin(arg)
* <li> acos(arg)
* <li> atan(arg)
* <li> atan2(arg0, arg1)
* <li> round(arg0, arg1)
* <li> least(arg0, arg1, ...)
* <li> greatest(arg0, arg1, ...)
* </ul>
*
* * format(datetime as pattern)
* * str(arg) - synonym of cast(a as String)
* * ifnull(arg0, arg1) - synonym of coalesce(a, b)
* <ul>
* <li> format(datetime as pattern)
* <li> str(arg) - synonym of cast(a as String)
* <li> ifnull(arg0, arg1) - synonym of coalesce(a, b)
* </ul>
*
* Finally, the following functions are defined as abbreviations
* for extract(), and desugared by the parser:
*
* * second(arg) - synonym of extract(second from a)
* * minute(arg) - synonym of extract(minute from a)
* * hour(arg) - synonym of extract(hour from a)
* * day(arg) - synonym of extract(day from a)
* * month(arg) - synonym of extract(month from a)
* * year(arg) - synonym of extract(year from a)
* <ul>
* <li> second(arg) - synonym of extract(second from a)
* <li> minute(arg) - synonym of extract(minute from a)
* <li> hour(arg) - synonym of extract(hour from a)
* <li> day(arg) - synonym of extract(day from a)
* <li> month(arg) - synonym of extract(month from a)
* <li> year(arg) - synonym of extract(year from a)
* </ul>
*
*/
public void initializeFunctionRegistry(QueryEngine queryEngine) {
@ -497,26 +525,76 @@ public abstract class Dialect implements ConversionContext {
queryEngine.getSqmFunctionRegistry().registerAlternateKey( "current_instant", "instant" ); //deprecated legacy!
}
/**
* Translation of the HQL/JPQL {@code current_date} function, which
* maps to the Java type {@code java.sql.Date}, and of the HQL
* {@code local_date} function which maps to the Java type
* {@code java.sql.LocalDate}.
*/
public String currentDate() {
return "current_date";
}
/**
* Translation of the HQL/JPQL {@code current_time} function, which
* maps to the Java type {@code java.sql.Time} which is a time with
* no time zone. This contradicts ANSI SQL where {@code current_time}
* has the type {@code TIME WITH TIME ZONE}.
* <p>
* It is recommended to override this in dialects for databases which
* support {@code localtime} or {@code time at local}.
*/
public String currentTime() {
return "current_time";
}
/**
* Translation of the HQL/JPQL {@code current_timestamp} function,
* which maps to the Java type {@code java.sql.Timestamp} which is
* a datetime with no time zone. This contradicts ANSI SQL where
* {@code current_timestamp} has the type
* {@code TIMESTAMP WITH TIME ZONE}.
* <p>
* It is recommended to override this in dialects for databases which
* support {@code localtimestamp} or {@code timestamp at local}.
*/
public String currentTimestamp() {
return "current_timestamp";
}
/**
* Translation of the HQL {@code local_time} function, which maps to
* the Java type {@code java.time.LocalTime} which is a time with no
* time zone. It should usually be the same SQL function as for
* {@link #currentTime()}.
* <p>
* It is recommended to override this in dialects for databases which
* support {@code localtime} or {@code current_time at local}.
*/
public String currentLocalTime() {
return currentTime();
}
/**
* Translation of the HQL {@code local_datetime} function, which maps
* to the Java type {@code java.time.LocalDateTime} which is a datetime
* with no time zone. It should usually be the same SQL function as for
* {@link #currentTimestamp()}.
* <p>
* It is recommended to override this in dialects for databases which
* support {@code localtimestamp} or {@code current_timestamp at local}.
*/
public String currentLocalTimestamp() {
return currentTimestamp();
}
/**
* Translation of the HQL {@code offset_datetime} function, which maps
* to the Java type {@code java.time.OffsetDateTime} which is a datetime
* with a time zone. This in principle correctly maps to the ANSI SQL
* {@code current_timestamp} which has the type
* {@code TIMESTAMP WITH TIME ZONE}.
*/
public String currentTimestampWithTimeZone() {
return currentTimestamp();
}

View File

@ -67,6 +67,7 @@ public class H2Dialect extends Dialect {
private final LimitHandler limitHandler;
private final boolean cascadeConstraints;
private final boolean useLocalTime;
private final int version;
@ -101,6 +102,8 @@ public class H2Dialect extends Dialect {
supportsTuplesInSubqueries = version >= 104198;
// Prior to 1.4.200 the 'cascade' in 'drop table' was implicit
cascadeConstraints = version >= 104200;
// 1.4.200 introduced changes in current_time and current_timestamp
useLocalTime = version >= 140199;
getDefaultProperties().setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
// http://code.google.com/p/h2database/issues/detail?id=235
@ -117,6 +120,12 @@ public class H2Dialect extends Dialect {
this.sequenceInformationExtractor = SequenceInformationExtractorNoOpImpl.INSTANCE;
this.querySequenceString = null;
}
if ( version < 200 ) {
// prior to version 2.0, H2 reported NUMERIC columns as DECIMAL,
// which caused problems for schema update tool
registerColumnType( Types.NUMERIC, "decimal($p,$s)" );
}
}
private static int parseBuildId(DialectResolutionInfo info) {
@ -185,6 +194,21 @@ public class H2Dialect extends Dialect {
CommonFunctionFactory.rownum( queryEngine );
}
@Override
public String currentTime() {
return useLocalTime ? "localtime" : super.currentTime();
}
@Override
public String currentTimestamp() {
return useLocalTime ? "localtimestamp" : super.currentTimestamp();
}
@Override
public String currentTimestampWithTimeZone() {
return "current_timestamp";
}
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {

View File

@ -212,6 +212,21 @@ public class HSQLDialect extends Dialect {
}
}
@Override
public String currentTime() {
return "localtime";
}
@Override
public String currentTimestamp() {
return "localtimestamp";
}
@Override
public String currentTimestampWithTimeZone() {
return "current_timestamp";
}
@Override
public SqlAstTranslatorFactory getSqlAstTranslatorFactory() {
return new StandardSqlAstTranslatorFactory() {

View File

@ -122,6 +122,21 @@ public class PostgreSQLDialect extends Dialect {
return version;
}
@Override
public String currentTime() {
return "localtime";
}
@Override
public String currentTimestamp() {
return "localtimestamp";
}
@Override
public String currentTimestampWithTimeZone() {
return "current_timestamp";
}
/**
* The {@code extract()} function returns {@link TemporalUnit#DAY_OF_WEEK}
* numbered from 0 to 6. This isn't consistent with what most other

View File

@ -8,6 +8,7 @@ package org.hibernate.type;
import java.util.UUID;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.descriptor.java.UUIDTypeDescriptor;
import org.hibernate.type.descriptor.sql.BinaryTypeDescriptor;
@ -20,7 +21,12 @@ public class UUIDBinaryType extends AbstractSingleColumnStandardBasicType<UUID>
public static final UUIDBinaryType INSTANCE = new UUIDBinaryType();
public UUIDBinaryType() {
super( BinaryTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE );
super( BinaryTypeDescriptor.INSTANCE, new UUIDTypeDescriptor() {
@Override
public long getDefaultSqlLength(Dialect dialect) {
return 16;
}
} );
}
public String getName() {

View File

@ -21,7 +21,12 @@ public class UUIDCharType extends AbstractSingleColumnStandardBasicType<UUID> im
public static final UUIDCharType INSTANCE = new UUIDCharType();
public UUIDCharType() {
super( VarcharTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE );
super( VarcharTypeDescriptor.INSTANCE, new UUIDTypeDescriptor() {
@Override
public long getDefaultSqlLength(Dialect dialect) {
return 36;
}
} );
}
public String getName() {

View File

@ -1,117 +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>.
*/
//$Id$
package org.hibernate.jpa.test.connection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.hibernate.cfg.Environment;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.test.Distributor;
import org.hibernate.jpa.test.Item;
import org.hibernate.jpa.test.xml.Light;
import org.hibernate.jpa.test.xml.Lighter;
/**
* @author Emmanuel Bernard
*/
public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
private Properties properties = new Properties();
private List<String> mappingFiles;
private URL puRoot;
public PersistenceUnitInfoImpl(URL puRoot, String[] mappingFiles) {
this.mappingFiles = new ArrayList<>( mappingFiles.length );
this.mappingFiles.addAll( Arrays.asList( mappingFiles ) );
this.puRoot = puRoot;
}
public String getPersistenceUnitName() {
return "persistenceinfo";
}
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
public DataSource getJtaDataSource() {
return new FakeDataSource();
}
public DataSource getNonJtaDataSource() {
return null;
}
public List<String> getMappingFileNames() {
return mappingFiles;
}
public List<URL> getJarFileUrls() {
return new ArrayList<URL>();
}
public List<String> getManagedClassNames() {
List<String> classes = new ArrayList<String>();
classes.add( Item.class.getName() );
classes.add( Distributor.class.getName() );
classes.add( Light.class.getName() );
classes.add( Lighter.class.getName() );
return classes;
}
public Properties getProperties() {
properties.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
return properties;
}
public String getPersistenceXMLSchemaVersion() {
return null;
}
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
public URL getPersistenceUnitRootUrl() {
return puRoot;
}
public boolean excludeUnlistedClasses() {
return true;
}
public SharedCacheMode getSharedCacheMode() {
return null;
}
public ValidationMode getValidationMode() {
return null;
}
public void addTransformer(ClassTransformer transformer) {
}
public ClassLoader getNewTempClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}

View File

@ -1,104 +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.jpa.test.connection;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.PersistenceException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.TestForIssue;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Andrea Boriero
*/
@TestForIssue(jiraKey = "HHH-11257")
public class TestConnectionPool
extends BaseEntityManagerFunctionalTestCase {
private final static int CONNECTION_POOL_SIZE = 2;
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { TestEntity.class };
}
@Override
protected boolean createSchema() {
return false;
}
@Override
protected void addConfigOptions(Map options) {
options.put(
AvailableSettings.POOL_SIZE,
Integer.valueOf( CONNECTION_POOL_SIZE )
);
options.put( "hibernate.connection.customProperty", "x" );
options.put( AvailableSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT, "true" );
}
@Test
@TestForIssue(jiraKey = "HHH-13700")
public void testConnectionPoolPropertyFiltering() {
ConnectionProvider cp = serviceRegistry().getService( ConnectionProvider.class );
DriverManagerConnectionProviderImpl dmcp = (DriverManagerConnectionProviderImpl) cp;
Properties connectionProperties = dmcp.getConnectionProperties();
Assert.assertEquals( "x", connectionProperties.getProperty( "customProperty" ) );
Assert.assertNull( connectionProperties.getProperty( "pool_size" ) );
Assert.assertNull( connectionProperties.getProperty( "provider_disables_autocommit" ) );
}
@Test
public void testConnectionPoolDoesNotConsumeAllConnections() {
for ( int i = 0; i < CONNECTION_POOL_SIZE + 1; ++i ) {
EntityManager entityManager = getOrCreateEntityManager();
try {
for ( int j = 0; j < 2; j++ ) {
try {
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<TestEntity> criteriaQuery = builder.createQuery(
TestEntity.class );
criteriaQuery.select( criteriaQuery.from( TestEntity.class ) );
entityManager.createQuery( criteriaQuery ).getResultList();
}
catch ( PersistenceException e ) {
if ( e.getCause() instanceof SQLGrammarException ) {
//expected, the schema was not created
}
else {
throw e;
}
}
}
}
finally {
entityManager.close();
}
}
}
@Entity(name = "Test_Entity")
public static class TestEntity {
@Id
public long id;
}
}

View File

@ -1,44 +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.jpa.test.criteria;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CollectionJoin;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.jpa.test.metamodel.LineItem;
import org.hibernate.jpa.test.metamodel.LineItem_;
import org.hibernate.jpa.test.metamodel.Order;
import org.hibernate.jpa.test.metamodel.Order_;
import org.junit.Test;
/**
* Similar to {@link org.hibernate.orm.test.query.hql.OnKeywordTest}, but here testing from JPA criteria queries.
*
* @author Steve Ebersole
*/
public class OnKeywordTest extends AbstractMetamodelSpecificTest {
@Test
public void basicTest() {
EntityManager em = getOrCreateEntityManager();
CriteriaQuery<Order> criteria = em.getCriteriaBuilder().createQuery( Order.class );
Root<Order> root = criteria.from( Order.class );
criteria.select( root );
CollectionJoin<Order,LineItem> lineItemsJoin = root.join( Order_.lineItems );
lineItemsJoin.on(
em.getCriteriaBuilder().gt(
lineItemsJoin.get( LineItem_.quantity ),
em.getCriteriaBuilder().literal( 20 )
)
);
em.createQuery( criteria ).getResultList();
em.close();
}
}

View File

@ -1,65 +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.jpa.test.criteria.basic;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.jpa.test.metamodel.Product;
import org.hibernate.jpa.test.metamodel.Product_;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.junit.Assert;
import org.junit.Test;
public class CastTest extends AbstractMetamodelSpecificTest {
private static final int QUANTITY = 2;
@Test
@SkipForDialect(value = DerbyDialect.class,comment = "Derby does not support cast from INTEGER to VARCHAR")
@TestForIssue( jiraKey = "HHH-5755" )
public void testCastToString() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Product product = new Product();
product.setId( "product1" );
product.setPrice( 1.23d );
product.setQuantity( QUANTITY );
product.setPartNumber( ((long)Integer.MAX_VALUE) + 1 );
product.setRating( 1.999f );
product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) );
product.setSomeBigDecimal( BigDecimal.valueOf( 987654.321 ) );
em.persist( product );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> root = criteria.from( Product.class );
criteria.where( builder.equal(root.get(Product_.quantity).as( String.class ), builder.literal(String.valueOf(QUANTITY))) );
List<Product> result = em.createQuery( criteria ).getResultList();
Assert.assertEquals( 1, result.size() );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.createQuery( "delete Product" ).executeUpdate();
em.getTransaction().commit();
em.close();
}
}

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.jpa.test.ejb3configuration;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.HibernateEntityManager;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.Cat;
import org.hibernate.jpa.test.Distributor;
import org.hibernate.jpa.test.Item;
import org.hibernate.jpa.test.Kitten;
import org.hibernate.jpa.test.Wallet;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class EntityManagerFactorySerializationTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testSerialization() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( entityManagerFactory() );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
EntityManagerFactory serializedFactory = (EntityManagerFactory) in.readObject();
in.close();
byteIn.close();
EntityManager em = serializedFactory.createEntityManager();
//em.getTransaction().begin();
//em.setFlushMode( FlushModeType.NEVER );
Cat cat = new Cat();
cat.setAge( 3 );
cat.setDateOfBirth( new Date() );
cat.setLength( 22 );
cat.setName( "Kitty" );
em.persist( cat );
Item item = new Item();
item.setName( "Train Ticket" );
item.setDescr( "Paris-London" );
em.persist( item );
//em.getTransaction().commit();
//em.getTransaction().begin();
item.setDescr( "Paris-Bruxelles" );
//em.getTransaction().commit();
//fake the in container work
em.unwrap( Session.class ).disconnect();
stream = new ByteArrayOutputStream();
out = new ObjectOutputStream( stream );
out.writeObject( em );
out.close();
serialized = stream.toByteArray();
stream.close();
byteIn = new ByteArrayInputStream( serialized );
in = new ObjectInputStream( byteIn );
em = (EntityManager) in.readObject();
in.close();
byteIn.close();
//fake the in container work
em.getTransaction().begin();
item = em.find( Item.class, item.getName() );
item.setDescr( item.getDescr() + "-Amsterdam" );
cat = (Cat) em.createQuery( "select c from " + Cat.class.getName() + " c" ).getSingleResult();
cat.setLength( 34 );
em.flush();
em.remove( item );
em.remove( cat );
em.flush();
em.getTransaction().commit();
em.close();
}
@Test
public void testEntityManagerFactorySerialization() throws Exception {
EntityManagerFactory entityManagerFactory = entityManagerFactory();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( entityManagerFactory );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
EntityManagerFactory entityManagerFactory2 = (EntityManagerFactory) in.readObject();
in.close();
byteIn.close();
assertTrue("deserialized EntityManagerFactory should be the same original EntityManagerFactory instance",
entityManagerFactory2 == entityManagerFactory);
}
@Test
public void testEntityManagerFactoryProperties() {
EntityManagerFactory entityManagerFactory = entityManagerFactory();
assertTrue( entityManagerFactory.getProperties().containsKey( AvailableSettings.USER ) );
if ( entityManagerFactory.getProperties().containsKey( AvailableSettings.PASS ) ) {
assertEquals( "****", entityManagerFactory.getProperties().get( AvailableSettings.PASS ) );
}
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Item.class,
Distributor.class,
Wallet.class,
Cat.class,
Kitten.class
};
}
}

View File

@ -6,7 +6,7 @@
*/
//$Id$
package org.hibernate.jpa.test.connection;
package org.hibernate.orm.test.jpa.connection;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

View File

@ -0,0 +1,68 @@
/*
* 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.jpa.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl;
import static org.mockito.Mockito.spy;
public class ConnectionProviderDecorator extends UserSuppliedConnectionProviderImpl {
private final DataSource dataSource;
private int connectionCount;
public Connection connection;
public ConnectionProviderDecorator(){
String url = Environment.getProperties().getProperty( Environment.URL );
Properties connectionProps = new Properties();
connectionProps.put( "user", Environment.getProperties().getProperty( Environment.USER ) );
connectionProps.put( "password", Environment.getProperties().getProperty( Environment.PASS ) );
dataSource = new BaseDataSource() {
@Override
public Connection getConnection() throws SQLException {
return DriverManager.getConnection( url, connectionProps );
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return DriverManager.getConnection( url, connectionProps );
}
};
}
@Override
public Connection getConnection() throws SQLException {
connectionCount++;
connection = spy( dataSource.getConnection() );
return connection;
}
@Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
public int getConnectionCount() {
return this.connectionCount;
}
public void clear() {
connectionCount = 0;
}
}

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.jpa.connection;
import java.sql.SQLException;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
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.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12197")
@RequiresDialect(H2Dialect.class)
@Jpa(
annotatedClasses = { ConnectionsReleaseAutoCommitTest.Thing.class },
integrationSettings = @Setting(name = AvailableSettings.CONNECTION_PROVIDER, value = "org.hibernate.orm.test.jpa.connection.ConnectionProviderDecorator")
)
public class ConnectionsReleaseAutoCommitTest {
@Test
public void testConnectionAcquisitionCount(EntityManagerFactoryScope scope) throws SQLException {
ConnectionProviderDecorator connectionProvider = getConnectionProvider( scope );
connectionProvider.clear();
scope.inTransaction( entityManager -> {
assertEquals( 1, connectionProvider.getConnectionCount() );
Thing thing = new Thing();
thing.setId( 1 );
entityManager.persist( thing );
assertEquals( 1, connectionProvider.getConnectionCount() );
} );
assertEquals( 1, connectionProvider.getConnectionCount() );
verify( connectionProvider.connection, times( 1 ) ).close();
Mockito.reset( connectionProvider.connection );
}
private ConnectionProviderDecorator getConnectionProvider(EntityManagerFactoryScope scope) {
return (ConnectionProviderDecorator) ( (SessionFactoryImplementor) ( scope
.getEntityManagerFactory() ) ).getServiceRegistry().getService( ConnectionProvider.class );
}
@Entity(name = "Thing")
@Table(name = "Thing")
public static class Thing {
@Id
public Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
}

View File

@ -7,7 +7,7 @@
//$Id$
package org.hibernate.jpa.test.connection;
package org.hibernate.orm.test.jpa.connection;
import java.net.URL;
import java.nio.file.Files;
@ -31,8 +31,8 @@ import org.hibernate.jpa.test.xml.Light;
import org.hibernate.jpa.test.xml.Lighter;
import org.hibernate.testing.util.jpa.PersistenceUnitInfoAdapter;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author Emmanuel Bernard
@ -58,7 +58,7 @@ public class DataSourceInjectionTest {
try ( final SessionImplementor session = sf.openSession().unwrap( SessionImplementor.class ) ) {
session.createQuery( "select i from Item i" ).list();
Assert.fail( "Expecting FakeDataSourceException" );
Assertions.fail( "Expecting FakeDataSourceException" );
}
catch (PersistenceException pe) {
try {

View File

@ -6,7 +6,7 @@
*/
//$Id$
package org.hibernate.jpa.test.connection;
package org.hibernate.orm.test.jpa.connection;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

View File

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

View File

@ -0,0 +1,55 @@
/*
* 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.jpa.criteria;
import org.hibernate.jpa.test.metamodel.Address;
import org.hibernate.jpa.test.metamodel.Alias;
import org.hibernate.jpa.test.metamodel.Country;
import org.hibernate.jpa.test.metamodel.CreditCard;
import org.hibernate.jpa.test.metamodel.Customer;
import org.hibernate.jpa.test.metamodel.Entity1;
import org.hibernate.jpa.test.metamodel.Entity2;
import org.hibernate.jpa.test.metamodel.Entity3;
import org.hibernate.jpa.test.metamodel.Info;
import org.hibernate.jpa.test.metamodel.LineItem;
import org.hibernate.jpa.test.metamodel.Order;
import org.hibernate.jpa.test.metamodel.Phone;
import org.hibernate.jpa.test.metamodel.Product;
import org.hibernate.jpa.test.metamodel.ShelfLife;
import org.hibernate.jpa.test.metamodel.Spouse;
import org.hibernate.jpa.test.metamodel.Thing;
import org.hibernate.jpa.test.metamodel.ThingWithQuantity;
import org.hibernate.jpa.test.metamodel.VersionedEntity;
import org.hibernate.testing.orm.junit.Jpa;
/**
* @author Jan Schatteman
*/
@Jpa(annotatedClasses = {
Address.class,
Alias.class,
Country.class,
CreditCard.class,
Customer.class,
Entity1.class,
Entity2.class,
Entity3.class,
Info.class,
LineItem.class,
Order.class,
Phone.class,
Product.class,
ShelfLife.class,
Spouse.class,
Thing.class,
ThingWithQuantity.class,
VersionedEntity.class
})
public abstract class AbstractCriteriaTest {
}

View File

@ -0,0 +1,46 @@
/*
* 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.jpa.criteria;
import javax.persistence.criteria.CollectionJoin;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.jpa.test.metamodel.LineItem;
import org.hibernate.jpa.test.metamodel.LineItem_;
import org.hibernate.jpa.test.metamodel.Order;
import org.hibernate.jpa.test.metamodel.Order_;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.junit.jupiter.api.Test;
/**
* Similar to {@link org.hibernate.orm.test.query.hql.OnKeywordTest}, but here testing from JPA criteria queries.
*
* @author Steve Ebersole
*/
public class OnKeywordTest extends AbstractCriteriaTest {
@Test
public void basicTest(EntityManagerFactoryScope scope) {
scope.inEntityManager(
entityManager -> {
CriteriaQuery<Order> criteria = entityManager.getCriteriaBuilder().createQuery( Order.class );
Root<Order> root = criteria.from( Order.class );
criteria.select( root );
CollectionJoin<Order, LineItem> lineItemsJoin = root.join( Order_.lineItems );
lineItemsJoin.on(
entityManager.getCriteriaBuilder().gt(
lineItemsJoin.get( LineItem_.quantity ),
entityManager.getCriteriaBuilder().literal( 20 )
)
);
entityManager.createQuery( criteria ).getResultList();
}
);
}
}

View File

@ -0,0 +1,72 @@
/*
* 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.jpa.criteria.basic;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.metamodel.Product;
import org.hibernate.jpa.test.metamodel.Product_;
import org.hibernate.orm.test.jpa.criteria.AbstractCriteriaTest;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class CastTest extends AbstractCriteriaTest {
private static final int QUANTITY = 2;
@AfterEach
public void tearDown(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
entityManager.createQuery( "delete from Product" ).executeUpdate();
}
);
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby does not support cast from INTEGER to VARCHAR")
@TestForIssue(jiraKey = "HHH-5755")
public void testCastToString(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Product product = new Product();
product.setId( "product1" );
product.setPrice( 1.23d );
product.setQuantity( QUANTITY );
product.setPartNumber( ( (long) Integer.MAX_VALUE ) + 1 );
product.setRating( 1.999f );
product.setSomeBigInteger( BigInteger.valueOf( 987654321 ) );
product.setSomeBigDecimal( BigDecimal.valueOf( 987654.321 ) );
entityManager.persist( product );
}
);
scope.inTransaction(
entityManager -> {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> criteria = builder.createQuery( Product.class );
Root<Product> root = criteria.from( Product.class );
criteria.where( builder.equal(
root.get( Product_.quantity ).as( String.class ),
builder.literal( String.valueOf( QUANTITY ) )
) );
List<Product> result = entityManager.createQuery( criteria ).getResultList();
Assertions.assertEquals( 1, result.size() );
}
);
}
}

View File

@ -4,30 +4,31 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.util.Collections;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import org.hibernate.HibernateException;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Test passing along various config settings that take objects other than strings as values.
*
* @author Steve Ebersole
*/
public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
@BaseUnitTest
public class ConfigurationObjectSettingTest {
@Test
public void testContainerBootstrapSharedCacheMode() {
// first, via the integration vars
@ -36,17 +37,17 @@ public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
// as object
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
empty,
Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
Collections.singletonMap( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
);
assertEquals( SharedCacheMode.DISABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.SHARED_CACHE_MODE ) );
assertEquals( SharedCacheMode.DISABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.JPA_SHARED_CACHE_MODE ) );
}
{
// as string
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
empty,
Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() )
Collections.singletonMap( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() )
);
assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), builder.getConfigurationValues().get( AvailableSettings.SHARED_CACHE_MODE ) );
assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), builder.getConfigurationValues().get( AvailableSettings.JPA_SHARED_CACHE_MODE ) );
}
// next, via the PUI
@ -61,16 +62,16 @@ public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
adapter,
null
);
assertEquals( SharedCacheMode.ENABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.SHARED_CACHE_MODE ) );
assertEquals( SharedCacheMode.ENABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.JPA_SHARED_CACHE_MODE ) );
}
// via both, integration vars should take precedence
{
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
adapter,
Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
Collections.singletonMap( AvailableSettings.JPA_SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
);
assertEquals( SharedCacheMode.DISABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.SHARED_CACHE_MODE ) );
assertEquals( SharedCacheMode.DISABLE_SELECTIVE, builder.getConfigurationValues().get( AvailableSettings.JPA_SHARED_CACHE_MODE ) );
}
}
@ -82,17 +83,17 @@ public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
// as object
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
empty,
Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK )
Collections.singletonMap( AvailableSettings.JPA_VALIDATION_MODE, ValidationMode.CALLBACK )
);
assertEquals( ValidationMode.CALLBACK, builder.getConfigurationValues().get( AvailableSettings.VALIDATION_MODE ) );
assertEquals( ValidationMode.CALLBACK, builder.getConfigurationValues().get( AvailableSettings.JPA_VALIDATION_MODE ) );
}
{
// as string
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
empty,
Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name() )
Collections.singletonMap( AvailableSettings.JPA_VALIDATION_MODE, ValidationMode.CALLBACK.name() )
);
assertEquals( ValidationMode.CALLBACK.name(), builder.getConfigurationValues().get( AvailableSettings.VALIDATION_MODE ) );
assertEquals( ValidationMode.CALLBACK.name(), builder.getConfigurationValues().get( AvailableSettings.JPA_VALIDATION_MODE ) );
}
// next, via the PUI
@ -107,16 +108,16 @@ public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
adapter,
null
);
assertEquals( ValidationMode.CALLBACK, builder.getConfigurationValues().get( AvailableSettings.VALIDATION_MODE ) );
assertEquals( ValidationMode.CALLBACK, builder.getConfigurationValues().get( AvailableSettings.JPA_VALIDATION_MODE ) );
}
// via both, integration vars should take precedence
{
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
adapter,
Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.NONE )
Collections.singletonMap( AvailableSettings.JPA_VALIDATION_MODE, ValidationMode.NONE )
);
assertEquals( ValidationMode.NONE, builder.getConfigurationValues().get( AvailableSettings.VALIDATION_MODE ) );
assertEquals( ValidationMode.NONE, builder.getConfigurationValues().get( AvailableSettings.JPA_VALIDATION_MODE ) );
}
}
@ -127,7 +128,7 @@ public class ConfigurationObjectSettingTest extends BaseUnitTestCase {
try {
Bootstrap.getEntityManagerFactoryBuilder(
adapter,
Collections.singletonMap( AvailableSettings.VALIDATION_FACTORY, token )
Collections.singletonMap( AvailableSettings.JPA_VALIDATION_FACTORY, token )
);
fail( "Was expecting error as token did not implement ValidatorFactory" );
}

View File

@ -0,0 +1,145 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.test.Cat;
import org.hibernate.jpa.test.Distributor;
import org.hibernate.jpa.test.Item;
import org.hibernate.jpa.test.Kitten;
import org.hibernate.jpa.test.Wallet;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Emmanuel Bernard
*/
@Jpa(annotatedClasses = {
Item.class,
Distributor.class,
Wallet.class,
Cat.class,
Kitten.class
})
public class EntityManagerFactorySerializationTest {
@Test
public void testSerialization(EntityManagerFactoryScope scope) throws Exception {
EntityManagerFactory emf = scope.getEntityManagerFactory();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( emf );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
EntityManagerFactory serializedFactory = (EntityManagerFactory) in.readObject();
in.close();
byteIn.close();
EntityManager em = serializedFactory.createEntityManager();
try {
//em.getTransaction().begin();
//em.setFlushMode( FlushModeType.NEVER );
Cat cat = new Cat();
cat.setAge( 3 );
cat.setDateOfBirth( new Date() );
cat.setLength( 22 );
cat.setName( "Kitty" );
em.persist( cat );
Item item = new Item();
item.setName( "Train Ticket" );
item.setDescr( "Paris-London" );
em.persist( item );
//em.getTransaction().commit();
//em.getTransaction().begin();
item.setDescr( "Paris-Bruxelles" );
//em.getTransaction().commit();
//fake the in container work
em.unwrap( Session.class ).disconnect();
stream = new ByteArrayOutputStream();
out = new ObjectOutputStream( stream );
out.writeObject( em );
out.close();
serialized = stream.toByteArray();
stream.close();
byteIn = new ByteArrayInputStream( serialized );
in = new ObjectInputStream( byteIn );
em = (EntityManager) in.readObject();
in.close();
byteIn.close();
//fake the in container work
em.getTransaction().begin();
item = em.find( Item.class, item.getName() );
item.setDescr( item.getDescr() + "-Amsterdam" );
cat = (Cat) em.createQuery( "select c from " + Cat.class.getName() + " c" ).getSingleResult();
cat.setLength( 34 );
em.flush();
em.remove( item );
em.remove( cat );
em.flush();
em.getTransaction().commit();
}
catch (Exception e) {
if ( em.getTransaction().isActive() ) {
em.getTransaction().rollback();
}
throw e;
}
finally {
em.close();
}
}
@Test
public void testEntityManagerFactorySerialization(EntityManagerFactoryScope scope) throws Exception {
EntityManagerFactory entityManagerFactory = scope.getEntityManagerFactory();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( entityManagerFactory );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
EntityManagerFactory entityManagerFactory2 = (EntityManagerFactory) in.readObject();
in.close();
byteIn.close();
assertTrue(
entityManagerFactory2 == entityManagerFactory,
"deserialized EntityManagerFactory should be the same original EntityManagerFactory instance"
);
}
@Test
public void testEntityManagerFactoryProperties(EntityManagerFactoryScope scope) {
EntityManagerFactory entityManagerFactory = scope.getEntityManagerFactory();
assertTrue( entityManagerFactory.getProperties().containsKey( AvailableSettings.USER ) );
if ( entityManagerFactory.getProperties().containsKey( AvailableSettings.PASS ) ) {
assertEquals( "****", entityManagerFactory.getProperties().get( AvailableSettings.PASS ) );
}
}
}

View File

@ -6,7 +6,7 @@
*/
//$Id$
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.io.Serializable;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.util.Arrays;
import java.util.Map;
@ -16,8 +16,6 @@ import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.Environment;
@ -29,13 +27,13 @@ import org.hibernate.jpa.test.Item;
import org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter;
import org.hibernate.jpa.test.SettingsGenerator;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterEach;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Emmanuel Bernard
@ -51,7 +49,7 @@ public class InterceptorTest {
private EntityManagerFactory entityManagerFactory;
@After
@AfterEach
public void releaseResources() {
if ( entityManagerFactory != null ) {
entityManagerFactory.close();

View File

@ -6,7 +6,7 @@
*/
//$
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.io.Serializable;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import javax.persistence.EntityManagerFactory;
import java.util.Collections;
@ -15,17 +15,18 @@ import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.test.MyNamingStrategy;
import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals;
import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Gail Badner
*/
public class NamingStrategyConfigurationTest extends BaseUnitTestCase {
@BaseUnitTest
public class NamingStrategyConfigurationTest {
@Test
public void testNamingStrategyFromProperty() {
@ -35,7 +36,10 @@ public class NamingStrategyConfigurationTest extends BaseUnitTestCase {
PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter();
EntityManagerFactoryBuilderImpl builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
adapter,
Collections.singletonMap( AvailableSettings.PHYSICAL_NAMING_STRATEGY, MyNamingStrategy.class.getName() )
Collections.singletonMap(
AvailableSettings.PHYSICAL_NAMING_STRATEGY,
MyNamingStrategy.class.getName()
)
);
final EntityManagerFactory emf = builder.build();
try {
@ -48,8 +52,9 @@ public class NamingStrategyConfigurationTest extends BaseUnitTestCase {
MyNamingStrategy.class,
builder.getMetadata().getMetadataBuildingOptions().getPhysicalNamingStrategy()
);
}finally {
if(emf != null){
}
finally {
if ( emf != null ) {
emf.close();
}
}

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import java.io.Serializable;
import java.util.Arrays;
@ -39,6 +39,7 @@ import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter;
import org.hibernate.jpa.test.SettingsGenerator;
import org.hibernate.jpa.test.ejb3configuration.Bell;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.metadata.ClassMetadata;
@ -67,8 +68,8 @@ import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author <a href="mailto:emmanuel@hibernate.org">Emmanuel Bernard</a>
@ -89,9 +90,9 @@ public class PersisterClassProviderTest {
entityManagerFactory.close();
}
catch ( PersistenceException e ) {
Assert.assertNotNull( e.getCause() );
Assert.assertNotNull( e.getCause().getCause() );
Assert.assertEquals( GoofyException.class, e.getCause().getCause().getClass() );
Assertions.assertNotNull( e.getCause() );
Assertions.assertNotNull( e.getCause().getCause() );
Assertions.assertEquals( GoofyException.class, e.getCause().getCause().getClass() );
}
}

View File

@ -4,14 +4,14 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration;
package org.hibernate.orm.test.jpa.ejb3configuration;
import javax.persistence.EntityManagerFactory;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
@ -38,7 +38,7 @@ public class SessionFactoryObserverTest {
try {
final EntityManagerFactory entityManagerFactory = builder.build();
entityManagerFactory.close();
Assert.fail( "GoofyException should have been thrown" );
Assertions.fail( "GoofyException should have been thrown" );
}
catch ( GoofyException e ) {
//success

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration.id;
package org.hibernate.orm.test.jpa.ejb3configuration.id;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration.id;
package org.hibernate.orm.test.jpa.ejb3configuration.id;
/**
* @author <a href="mailto:emmanuel@hibernate.org">Emmanuel Bernard</a>

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration.id;
package org.hibernate.orm.test.jpa.ejb3configuration.id;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration.id;
package org.hibernate.orm.test.jpa.ejb3configuration.id;
import java.util.HashMap;
import java.util.Map;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.ejb3configuration.id;
package org.hibernate.orm.test.jpa.ejb3configuration.id;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
@ -17,8 +17,8 @@ import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author <a href="mailto:emmanuel@hibernate.org">Emmanuel Bernard</a>
@ -43,7 +43,7 @@ public class IdentifierGeneratorStrategyProviderTest {
try {
entityManager.persist( new Cable() );
entityManager.flush();
Assert.fail( "FunkyException should have been thrown when the id is generated" );
Assertions.fail( "FunkyException should have been thrown when the id is generated" );
}
catch ( FunkyException e ) {
entityManager.close();

View File

@ -1,148 +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.connections;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.sql.DataSource;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.connection.BaseDataSource;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12197")
@RequiresDialect(H2Dialect.class)
public class ConnectionsReleaseAutoCommitTest extends BaseEntityManagerFunctionalTestCase {
private ConnectionProviderDecorator connectionProvider;
private Connection connection;
@Override
protected Map getConfig() {
Map config = super.getConfig();
String url = Environment.getProperties().getProperty( Environment.URL );
Properties connectionProps = new Properties();
connectionProps.put("user", Environment.getProperties().getProperty( Environment.USER ));
connectionProps.put("password", Environment.getProperties().getProperty( Environment.PASS ));
BaseDataSource dataSource = new BaseDataSource() {
@Override
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, connectionProps);
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return DriverManager.getConnection(url, connectionProps);
}
};
connectionProvider = new ConnectionProviderDecorator( dataSource );
config.put( AvailableSettings.CONNECTION_PROVIDER, connectionProvider );
return config;
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Thing.class,
};
}
@Test
public void testConnectionAcquisitionCount() throws SQLException {
connectionProvider.clear();
doInJPA( this::entityManagerFactory, entityManager -> {
assertEquals( 1, connectionProvider.getConnectionCount() );
Thing thing = new Thing();
thing.setId( 1 );
entityManager.persist( thing );
assertEquals( 1, connectionProvider.getConnectionCount() );
} );
assertEquals( 1, connectionProvider.getConnectionCount() );
verify( connectionProvider.connection, times( 1 ) ).close();
Mockito.reset( connectionProvider.connection );
}
@Entity(name = "Thing")
@Table(name = "Thing")
public static class Thing {
@Id
public Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
public static class ConnectionProviderDecorator extends UserSuppliedConnectionProviderImpl {
private final DataSource dataSource;
private int connectionCount;
private Connection connection;
public ConnectionProviderDecorator(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Connection getConnection() throws SQLException {
connectionCount++;
connection = spy(dataSource.getConnection());
return connection;
}
@Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
public int getConnectionCount() {
return this.connectionCount;
}
public void clear() {
connectionCount = 0;
}
}
}

View File

@ -0,0 +1,82 @@
/*
* 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.testing.orm.junit;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Steve Ebersole
*/
public final class ExtraAssertions {
private ExtraAssertions() {
}
public static void assertClassAssignability(Class expected, Class actual) {
if ( !expected.isAssignableFrom( actual ) ) {
fail( "Expected class [" + expected.getName() + "] was not assignable from actual [" + actual.getName() + "]" );
}
}
@SuppressWarnings("unchecked")
public static <T> T assertTyping(Class<T> expectedType, Object value) {
if ( !expectedType.isInstance( value ) ) {
fail(
String.format(
"Expecting value of type [%s], but found [%s]",
expectedType.getName(),
value == null ? "<null>" : value
)
);
}
return (T) value;
}
public static void assertJdbcTypeCode(int expected, int actual) {
if ( expected != actual ) {
final String message = String.format(
"JDBC type codes did not match...\n" +
"Expected: %s (%s)\n" +
"Actual : %s (%s)",
jdbcTypeCodeMap().get( expected ),
expected,
jdbcTypeCodeMap().get( actual ),
actual
);
fail( message );
}
}
private static Map<Integer, String> jdbcTypeCodeMap;
private static synchronized Map<Integer, String> jdbcTypeCodeMap() {
if ( jdbcTypeCodeMap == null ) {
jdbcTypeCodeMap = generateJdbcTypeCache();
}
return jdbcTypeCodeMap;
}
private static Map generateJdbcTypeCache() {
final Field[] fields = Types.class.getFields();
Map cache = new HashMap( (int) ( fields.length * .75 ) + 1 );
for ( Field field : fields ) {
if ( Modifier.isStatic( field.getModifiers() ) ) {
try {
cache.put( field.get( null ), field.getName() );
}
catch (Throwable ignore) {
}
}
}
return cache;
}
}