HHH-9996 - Finish Derby database profile

This commit is contained in:
Andrea Boriero 2015-09-08 14:01:49 +01:00
parent ac16e825f8
commit 8d3b2e723b
49 changed files with 750 additions and 217 deletions

View File

@ -5,7 +5,7 @@
* 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>.
*/ */
//databaseProfile { //databaseProfile {
jdbcDependency 'org.apache.derby:derby:10.10.2.0' jdbcDependency 'org.apache.derby:derby:10.11.1.1'
// testing { // testing {
// beforeSuite { // beforeSuite {

View File

@ -21,6 +21,5 @@ hibernate.max_fetch_depth 5
hibernate.cache.region_prefix hibernate.test hibernate.cache.region_prefix hibernate.test
hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory
javax.persistence.validation.mode=NONE
hibernate.service.allow_crawling=false hibernate.service.allow_crawling=false
hibernate.session.events.log=true hibernate.session.events.log=true

View File

@ -14,6 +14,7 @@ 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.Table;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.internal.SessionImpl; import org.hibernate.internal.SessionImpl;
@ -68,6 +69,7 @@ public class ExtraStateTest extends BaseCoreFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "ChineseTakeawayRestaurant")
public class ChineseTakeawayRestaurant { public class ChineseTakeawayRestaurant {
private long id; private long id;

View File

@ -6,42 +6,32 @@
*/ */
package org.hibernate.id; package org.hibernate.id;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Properties; import java.util.Properties;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ObjectNameNormalizer; import org.hibernate.boot.model.naming.ObjectNameNormalizer;
import org.hibernate.boot.model.relational.SimpleAuxiliaryDatabaseObject;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.spi.JdbcServices;
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.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.internal.SessionImpl; import org.hibernate.internal.SessionImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.env.TestingDatabaseInfo;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.BasicTestingJdbcServiceImpl;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
@ -50,25 +40,21 @@ import static org.junit.Assert.assertEquals;
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@SuppressWarnings({ "deprecation" }) @SuppressWarnings({"deprecation"})
@RequiresDialectFeature( DialectChecks.SupportsSequences.class ) @RequiresDialectFeature(DialectChecks.SupportsSequences.class)
public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase { public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase {
private static final String TEST_SEQUENCE = "test_sequence"; private static final String TEST_SEQUENCE = "test_sequence";
private StandardServiceRegistry serviceRegistry; private StandardServiceRegistry serviceRegistry;
private SessionFactoryImplementor sessionFactory; private SessionFactoryImplementor sessionFactory;
private SequenceStyleGenerator generator; private SequenceStyleGenerator generator;
private SessionImplementor session; private SessionImplementor sessionImpl;
private SequenceValueExtractor sequenceValueExtractor;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
BasicTestingJdbcServiceImpl jdbcServices = new BasicTestingJdbcServiceImpl();
jdbcServices.prepare( false );
serviceRegistry = new StandardServiceRegistryBuilder() serviceRegistry = new StandardServiceRegistryBuilder()
.enableAutoClose() .enableAutoClose()
.addService( JdbcEnvironment.class, jdbcServices.getJdbcEnvironment() )
.addService( JdbcServices.class, jdbcServices )
.applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" ) .applySetting( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
.build(); .build();
@ -94,13 +80,14 @@ public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase {
generator.registerExportables( metadata.getDatabase() ); generator.registerExportables( metadata.getDatabase() );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory(); sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
sequenceValueExtractor = new SequenceValueExtractor( sessionFactory.getDialect(), TEST_SEQUENCE );
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
if(session != null && !session.isClosed()) { if ( sessionImpl != null && !sessionImpl.isClosed() ) {
((Session)session).close(); ((Session) sessionImpl).close();
} }
if ( sessionFactory != null ) { if ( sessionFactory != null ) {
sessionFactory.close(); sessionFactory.close();
} }
@ -111,58 +98,49 @@ public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase {
@Test @Test
public void testHiLoAlgorithm() { public void testHiLoAlgorithm() {
session = (SessionImpl) sessionFactory.openSession(); sessionImpl = (SessionImpl) sessionFactory.openSession();
((Session)session).beginTransaction();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// initially sequence should be uninitialized // initially sequence should be uninitialized
assertEquals( 0L, extractSequenceValue( (session) ) ); assertEquals( 0L, extractSequenceValue( (sessionImpl) ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// historically the hilo generators skipped the initial block of values; // historically the hilo generators skipped the initial block of values;
// so the first generated id value is maxlo + 1, here be 4 // so the first generated id value is maxlo + 1, here be 4
Long generatedValue = (Long) generator.generate( session, null ); assertEquals( 1L, generateValue() );
assertEquals( 1L, generatedValue.longValue() );
// which should also perform the first read on the sequence which should set it to its "start with" value (1) // which should also perform the first read on the sequence which should set it to its "start with" value (1)
assertEquals( 1L, extractSequenceValue( (session) ) ); assertEquals( 1L, extractSequenceValue( (sessionImpl) ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 2L, generateValue() );
assertEquals( 2L, generatedValue.longValue() ); assertEquals( 2L, extractSequenceValue( (sessionImpl) ) );
assertEquals( 2L, extractSequenceValue( (session) ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 3L, generateValue() );
assertEquals( 3L, generatedValue.longValue() ); assertEquals( 3L, extractSequenceValue( (sessionImpl) ) );
assertEquals( 3L, extractSequenceValue( (session) ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 4L, generateValue() );
assertEquals( 4L, generatedValue.longValue() ); assertEquals( 4L, extractSequenceValue( (sessionImpl) ) );
assertEquals( 4L, extractSequenceValue( (session) ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 5L, generateValue() );
assertEquals( 5L, generatedValue.longValue() ); assertEquals( 5L, extractSequenceValue( (sessionImpl) ) );
assertEquals( 5L, extractSequenceValue( (session) ) );
((Session)session).getTransaction().commit(); ((Session) sessionImpl).close();
((Session)session).close();
} }
private long extractSequenceValue(final SessionImplementor session) { private long extractSequenceValue(SessionImplementor sessionImpl) {
class WorkImpl implements Work { return sequenceValueExtractor.extractSequenceValue( sessionImpl );
private long value; }
public void execute(Connection connection) throws SQLException {
private long generateValue() {
PreparedStatement query = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( "select currval('" + TEST_SEQUENCE + "');" ); Long generatedValue;
ResultSet resultSet = session.getJdbcCoordinator().getResultSetReturn().extract( query ); Transaction transaction = ((Session) sessionImpl).beginTransaction();
resultSet.next(); generatedValue = (Long) generator.generate( sessionImpl, null );
value = resultSet.getLong( 1 ); transaction.commit();
} return generatedValue.longValue();
}
WorkImpl work = new WorkImpl();
( (Session) session ).doWork( work );
return work.value;
} }
} }

View File

@ -6,13 +6,10 @@
*/ */
package org.hibernate.id; package org.hibernate.id;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata; import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistry;
@ -22,33 +19,35 @@ import org.hibernate.cfg.AvailableSettings;
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.internal.SessionImpl; import org.hibernate.internal.SessionImpl;
import org.hibernate.jdbc.Work;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
/** /**
* I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this * I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this
* unit test so that we can make sure the value keep being generated in the expected manner * unit test so that we can make sure the value keep being generated in the expected manner
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@SuppressWarnings({ "deprecation" }) @SuppressWarnings({"deprecation"})
@RequiresDialectFeature( DialectChecks.SupportsSequences.class ) @RequiresDialectFeature(DialectChecks.SupportsSequences.class)
public class SequenceHiLoGeneratorTest extends BaseUnitTestCase { public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
private static final String TEST_SEQUENCE = "test_sequence"; private static final String TEST_SEQUENCE = "test_sequence";
private StandardServiceRegistry serviceRegistry; private StandardServiceRegistry serviceRegistry;
private SessionFactoryImplementor sessionFactory; private SessionFactoryImplementor sessionFactory;
private SequenceHiLoGenerator generator; private SequenceHiLoGenerator generator;
private SessionImplementor sessionImpl;
private SequenceValueExtractor sequenceValueExtractor;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
@ -62,7 +61,10 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
Properties properties = new Properties(); Properties properties = new Properties();
properties.setProperty( SequenceGenerator.SEQUENCE, TEST_SEQUENCE ); properties.setProperty( SequenceGenerator.SEQUENCE, TEST_SEQUENCE );
properties.setProperty( SequenceHiLoGenerator.MAX_LO, "3" ); properties.setProperty( SequenceHiLoGenerator.MAX_LO, "3" );
properties.put( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer() ); properties.put(
PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
buildingContext.getObjectNameNormalizer()
);
generator = new SequenceHiLoGenerator(); generator = new SequenceHiLoGenerator();
generator.configure( StandardBasicTypes.LONG, properties, serviceRegistry ); generator.configure( StandardBasicTypes.LONG, properties, serviceRegistry );
@ -71,6 +73,7 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
generator.registerExportables( metadata.getDatabase() ); generator.registerExportables( metadata.getDatabase() );
sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory(); sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
sequenceValueExtractor = new SequenceValueExtractor( sessionFactory.getDialect(), TEST_SEQUENCE );
} }
@After @After
@ -85,61 +88,50 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
@Test @Test
public void testHiLoAlgorithm() { public void testHiLoAlgorithm() {
SessionImpl session = (SessionImpl) sessionFactory.openSession(); sessionImpl = (SessionImpl) sessionFactory.openSession();
session.beginTransaction();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// initially sequence should be uninitialized // initially sequence should be uninitialized
assertEquals( 0L, extractSequenceValue( session ) ); assertEquals( 0L, extractSequenceValue( sessionImpl ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// historically the hilo generators skipped the initial block of values; // historically the hilo generators skipped the initial block of values;
// so the first generated id value is maxlo + 1, here be 4 // so the first generated id value is maxlo + 1, here be 4
Long generatedValue = (Long) generator.generate( session, null ); assertEquals( 4L, generateValue() );
assertEquals( 4L, generatedValue.longValue() );
// which should also perform the first read on the sequence which should set it to its "start with" value (1) // which should also perform the first read on the sequence which should set it to its "start with" value (1)
assertEquals( 1L, extractSequenceValue( session ) ); assertEquals( 1L, extractSequenceValue( sessionImpl ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 5L, generateValue() );
assertEquals( 5L, generatedValue.longValue() ); assertEquals( 1L, extractSequenceValue( sessionImpl ) );
assertEquals( 1L, extractSequenceValue( session ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 6L, generateValue() );
assertEquals( 6L, generatedValue.longValue() ); assertEquals( 1L, extractSequenceValue( sessionImpl ) );
assertEquals( 1L, extractSequenceValue( session ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 7L, generateValue() );
assertEquals( 7L, generatedValue.longValue() );
// unlike the newer strategies, the db value will not get update here. It gets updated on the next invocation // unlike the newer strategies, the db value will not get update here. It gets updated on the next invocation
// after a clock over // after a clock over
assertEquals( 1L, extractSequenceValue( session ) ); assertEquals( 1L, extractSequenceValue( sessionImpl ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generatedValue = (Long) generator.generate( session, null ); assertEquals( 8L, generateValue() );
assertEquals( 8L, generatedValue.longValue() );
// this should force an increment in the sequence value // this should force an increment in the sequence value
assertEquals( 2L, extractSequenceValue( session ) ); assertEquals( 2L, extractSequenceValue( sessionImpl ) );
session.getTransaction().commit(); ((Session) sessionImpl).close();
session.close();
} }
private long extractSequenceValue(final SessionImplementor session) { private long extractSequenceValue(SessionImplementor sessionImpl) {
class WorkImpl implements Work { return sequenceValueExtractor.extractSequenceValue( sessionImpl );
private long value; }
public void execute(Connection connection) throws SQLException { private long generateValue() {
PreparedStatement query = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( "select currval('" + TEST_SEQUENCE + "');" ); Long generatedValue;
ResultSet resultSet = session.getJdbcCoordinator().getResultSetReturn().extract( query ); Transaction transaction = ((Session) sessionImpl).beginTransaction();
resultSet.next(); generatedValue = (Long) generator.generate( sessionImpl, null );
value = resultSet.getLong( 1 ); transaction.commit();
} return generatedValue.longValue();
}
WorkImpl work = new WorkImpl();
( (Session) session ).doWork( work );
return work.value;
} }
} }

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.id;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
/**
* @author Andrea Boriero
*/
public class SequenceValueExtractor {
private final Dialect dialect;
private final String queryString;
public SequenceValueExtractor(Dialect dialect, String sequenceName) {
this.dialect = dialect;
if ( dialect instanceof DerbyDialect ) {
queryString = "VALUES SYSCS_UTIL.SYSCS_PEEK_AT_SEQUENCE('HIBERNATE_ORM_TEST', '" + sequenceName.toUpperCase() + "')";
}
else {
queryString = "select currval('" + sequenceName + "');";
}
}
public long extractSequenceValue(final SessionImplementor sessionImpl) {
class WorkImpl implements Work {
private long value;
public void execute(Connection connection) throws SQLException {
Session session = (Session) sessionImpl;
Transaction transaction = session.beginTransaction();
final PreparedStatement query = sessionImpl.getJdbcCoordinator()
.getStatementPreparer()
.prepareStatement( queryString );
ResultSet resultSet = sessionImpl.getJdbcCoordinator().getResultSetReturn().extract( query );
resultSet.next();
value = resultSet.getLong( 1 );
resultSet.close();
transaction.commit();
if ( dialect instanceof DerbyDialect ) {
value--;
}
}
}
WorkImpl work = new WorkImpl();
((Session) sessionImpl).doWork( work );
return work.value;
}
}

View File

@ -12,7 +12,7 @@ import java.util.Date;
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public class CarModel extends Model { public class CarModel extends Model {
@Column(name="`year`") @Column(name="model_year")
private Date year; private Date year;
public Date getYear() { public Date getYear() {

View File

@ -14,6 +14,7 @@ import org.junit.Test;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.PostgreSQL81Dialect; import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.TeradataDialect; import org.hibernate.dialect.TeradataDialect;
@ -30,13 +31,13 @@ import static org.junit.Assert.assertNotNull;
*/ */
public class Ejb3XmlTest extends BaseCoreFunctionalTestCase { public class Ejb3XmlTest extends BaseCoreFunctionalTestCase {
@Test @Test
@SkipForDialects ( { @SkipForDialects({
@SkipForDialect(value = { PostgreSQL81Dialect.class, PostgreSQLDialect.class }, @SkipForDialect(value = {PostgreSQL81Dialect.class, PostgreSQLDialect.class},
comment = "postgresql jdbc driver does not implement the setQueryTimeout method"), comment = "postgresql jdbc driver does not implement the setQueryTimeout method"),
@SkipForDialect(value = TeradataDialect.class , @SkipForDialect(value = TeradataDialect.class,
jiraKey = "HHH-8190", jiraKey = "HHH-8190",
comment = "uses Teradata reserved word - year") comment = "uses Teradata reserved word - year")
} ) })
public void testEjb3Xml() throws Exception { public void testEjb3Xml() throws Exception {
Session s = openSession(); Session s = openSession();
Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction();

View File

@ -24,6 +24,7 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.MapKeyColumn; import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.Query; import org.hibernate.Query;
import org.hibernate.Session; import org.hibernate.Session;
@ -197,6 +198,7 @@ public class PersistentMapTest extends BaseCoreFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "MyUser")
private static class User implements Serializable { private static class User implements Serializable {
@Id @GeneratedValue @Id @GeneratedValue
private Integer id; private Integer id;
@ -207,6 +209,7 @@ public class PersistentMapTest extends BaseCoreFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "UserData")
private static class UserData { private static class UserData {
@Id @GeneratedValue @Id @GeneratedValue
private Integer id; private Integer id;

View File

@ -33,6 +33,7 @@ public class Component {
Set<Stuff> stuffs = new HashSet<Stuff>(); Set<Stuff> stuffs = new HashSet<Stuff>();
@Entity @Entity
@Table(name = "stuff")
public static class Stuff { public static class Stuff {
@Id @Id
private Long id; private Long id;

View File

@ -19,6 +19,7 @@ import org.hibernate.cfg.Environment;
import org.hibernate.dialect.AbstractHANADialect; import org.hibernate.dialect.AbstractHANADialect;
import org.hibernate.dialect.CUBRIDDialect; import org.hibernate.dialect.CUBRIDDialect;
import org.hibernate.dialect.DB2Dialect; import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.IngresDialect; import org.hibernate.dialect.IngresDialect;
@ -754,7 +755,12 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
"from Human where cast(? as string) is null" : "from Human where cast(? as string) is null" :
"from Human where ? is null" "from Human where ? is null"
; ;
s.createQuery( query ).setParameter( 0, null ).list(); if ( getDialect() instanceof DerbyDialect ) {
s.createQuery( query ).setParameter( 0, "null" ).list();
}
else {
s.createQuery( query ).setParameter( 0, null ).list();
}
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();
@ -1386,10 +1392,12 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
public void testSimpleSelectWithLimitAndOffset() throws Exception { public void testSimpleSelectWithLimitAndOffset() throws Exception {
// just checking correctness of param binding code... // just checking correctness of param binding code...
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
session.createQuery( "from Animal" ) session.createQuery( "from Animal" )
.setFirstResult( 2 ) .setFirstResult( 2 )
.setMaxResults( 1 ) .setMaxResults( 1 )
.list(); .list();
t.commit();
session.close(); session.close();
} }
@ -1567,6 +1575,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
// which in-and-of-itself is not necessarily bad. But somewhere later // which in-and-of-itself is not necessarily bad. But somewhere later
// the choices made there caused joins to be dropped. // the choices made there caused joins to be dropped.
Session s = openSession(); Session s = openSession();
Transaction t = s.beginTransaction();
String qryString = String qryString =
"select a.id, a.description" + "select a.id, a.description" +
" from Animal a" + " from Animal a" +
@ -1599,6 +1608,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
" where h = f1" + " where h = f1" +
")"; ")";
s.createQuery( qryString ).list(); s.createQuery( qryString ).list();
t.commit();
s.close(); s.close();
} }
@ -2604,8 +2614,8 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
an.setBodyWeight(123.45f); an.setBodyWeight(123.45f);
session.persist( an ); session.persist( an );
String str = (String) session.createQuery("select str(an.bodyWeight) from Animal an where str(an.bodyWeight) like '%1%'").uniqueResult(); String str = (String) session.createQuery("select str(an.bodyWeight) from Animal an where str(an.bodyWeight) like '%1%'").uniqueResult();
if ( getDialect() instanceof DB2Dialect || getDialect() instanceof TeradataDialect) { if ( (getDialect() instanceof DB2Dialect || getDialect() instanceof TeradataDialect) && !(getDialect() instanceof DerbyDialect) ) {
assertTrue( str.startsWith("1.234") ); assertTrue( str.startsWith( "1.234" ) );
} }
else //noinspection deprecation else //noinspection deprecation
if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect || getDialect() instanceof SQLServerDialect ) { if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect || getDialect() instanceof SQLServerDialect ) {
@ -2894,9 +2904,11 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
public void testFromOnly() throws Exception { public void testFromOnly() throws Exception {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "from Animal" ).list(); List results = session.createQuery( "from Animal" ).list();
assertEquals( "Incorrect result size", 2, results.size() ); assertEquals( "Incorrect result size", 2, results.size() );
assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal ); assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
} }
@ -2905,9 +2917,11 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
public void testSimpleSelect() throws Exception { public void testSimpleSelect() throws Exception {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "select a from Animal as a" ).list(); List results = session.createQuery( "select a from Animal as a" ).list();
assertEquals( "Incorrect result size", 2, results.size() ); assertEquals( "Incorrect result size", 2, results.size() );
assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal ); assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
} }
@ -2916,8 +2930,10 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
public void testEntityPropertySelect() throws Exception { public void testEntityPropertySelect() throws Exception {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "select a.mother from Animal as a" ).list(); List results = session.createQuery( "select a.mother from Animal as a" ).list();
assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal ); assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
} }
@ -2927,6 +2943,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "from Animal an where an.bodyWeight > 10" ).list(); List results = session.createQuery( "from Animal an where an.bodyWeight > 10" ).list();
assertEquals( "Incorrect result size", 1, results.size() ); assertEquals( "Incorrect result size", 1, results.size() );
@ -2945,6 +2962,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
results = session.createQuery( "from Animal an where (an.bodyWeight > 10 and an.bodyWeight < 100) or an.bodyWeight is null" ).list(); results = session.createQuery( "from Animal an where (an.bodyWeight > 10 and an.bodyWeight < 100) or an.bodyWeight is null" ).list();
assertEquals( "Incorrect result size", 1, results.size() ); assertEquals( "Incorrect result size", 1, results.size() );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -2955,6 +2973,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "from Animal an join fetch an.mother" ).list(); List results = session.createQuery( "from Animal an join fetch an.mother" ).list();
assertEquals( "Incorrect result size", 1, results.size() ); assertEquals( "Incorrect result size", 1, results.size() );
@ -2968,6 +2987,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
mother = ( ( Animal ) results.get( 0 ) ).getMother(); mother = ( ( Animal ) results.get( 0 ) ).getMother();
assertTrue( "fetch uninitialized", mother != null && Hibernate.isInitialized( mother ) ); assertTrue( "fetch uninitialized", mother != null && Hibernate.isInitialized( mother ) );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -2978,6 +2998,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "from Animal an join fetch an.offspring" ).list(); List results = session.createQuery( "from Animal an join fetch an.offspring" ).list();
assertEquals( "Incorrect result size", 1, results.size() ); assertEquals( "Incorrect result size", 1, results.size() );
assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal ); assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Animal );
@ -2990,6 +3011,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
os = ( ( Animal ) results.get( 0 ) ).getOffspring(); os = ( ( Animal ) results.get( 0 ) ).getOffspring();
assertTrue( "fetch uninitialized", os != null && Hibernate.isInitialized( os ) && os.size() == 1 ); assertTrue( "fetch uninitialized", os != null && Hibernate.isInitialized( os ) && os.size() == 1 );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -3010,6 +3032,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
session.save( mammal ); session.save( mammal );
session.save( zoo ); session.save( zoo );
txn.commit(); txn.commit();
session.close();
session = openSession(); session = openSession();
txn = session.beginTransaction(); txn = session.beginTransaction();
@ -3042,6 +3065,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
session.save( mammal ); session.save( mammal );
session.save( zoo ); session.save( zoo );
txn.commit(); txn.commit();
session.close();
session = openSession(); session = openSession();
txn = session.beginTransaction(); txn = session.beginTransaction();
@ -3074,6 +3098,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
session.save( mammal ); session.save( mammal );
session.save( zoo ); session.save( zoo );
txn.commit(); txn.commit();
session.close();
session = openSession(); session = openSession();
txn = session.beginTransaction(); txn = session.beginTransaction();
@ -3095,11 +3120,15 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
public void testProjectionQueries() throws Exception { public void testProjectionQueries() throws Exception {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "select an.mother.id, max(an.bodyWeight) from Animal an group by an.mother.id" ).list(); List results = session.createQuery( "select an.mother.id, max(an.bodyWeight) from Animal an group by an.mother.id" ).list();
// mysql returns nulls in this group by // mysql returns nulls in this group by
assertEquals( "Incorrect result size", 2, results.size() ); assertEquals( "Incorrect result size", 2, results.size() );
assertTrue( "Incorrect return type", results.get( 0 ) instanceof Object[] ); assertTrue( "Incorrect return type", results.get( 0 ) instanceof Object[] );
assertEquals( "Incorrect return dimensions", 2, ( ( Object[] ) results.get( 0 ) ).length ); assertEquals( "Incorrect return dimensions", 2, ((Object[]) results.get( 0 )).length );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
} }
@ -3132,6 +3161,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
createTestBaseData(); createTestBaseData();
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).list(); List results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).list();
assertEquals( "Incorrect result size", 2, results.size() ); assertEquals( "Incorrect result size", 2, results.size() );
@ -3210,6 +3240,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
assertEquals( "incorrect result size", 2, results.size() ); assertEquals( "incorrect result size", 2, results.size() );
assertClassAssignability( Animal.class, results.get( 0 ).getClass() ); assertClassAssignability( Animal.class, results.get( 0 ).getClass() );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -3431,7 +3462,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testIllegalMixedTransformerQueries() { public void testIllegalMixedTransformerQueries() {
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
try { try {
getSelectNewQuery( session ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); getSelectNewQuery( session ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
fail("'select new' together with a resulttransformer should result in error!"); fail("'select new' together with a resulttransformer should result in error!");
@ -3452,7 +3483,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
} catch(HibernateException he) { } catch(HibernateException he) {
assertTrue(he.getMessage().indexOf("ResultTransformer")==0); assertTrue(he.getMessage().indexOf("ResultTransformer")==0);
} }
t.commit();
session.close(); session.close();
} }
@ -3467,28 +3498,33 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
String query = "select an.description as description, an.bodyWeight as bodyWeight from Animal an order by bodyWeight desc"; String query = "select an.description as description, an.bodyWeight as bodyWeight from Animal an order by bodyWeight desc";
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( query ) List results = session.createQuery( query )
.setResultTransformer(Transformers.aliasToBean(Animal.class)).list(); .setResultTransformer(Transformers.aliasToBean(Animal.class)).list();
assertEquals( "Incorrect result size", results.size(), 2 ); assertEquals( "Incorrect result size", results.size(), 2 );
assertTrue( "Incorrect return type", results.get(0) instanceof Animal ); assertTrue( "Incorrect return type", results.get(0) instanceof Animal );
Animal firstAnimal = (Animal) results.get(0); Animal firstAnimal = (Animal) results.get(0);
Animal secondAnimal = (Animal) results.get(1); Animal secondAnimal = (Animal) results.get(1);
assertEquals("Mammal #1", firstAnimal.getDescription()); assertEquals("Mammal #1", firstAnimal.getDescription());
assertEquals("Mammal #2", secondAnimal.getDescription()); assertEquals( "Mammal #2", secondAnimal.getDescription() );
assertFalse(session.contains(firstAnimal)); assertFalse( session.contains( firstAnimal ) );
t.commit();
session.close(); session.close();
session = openSession(); session = openSession();
t = session.beginTransaction();
Iterator iter = session.createQuery( query ) Iterator iter = session.createQuery( query )
.setResultTransformer(Transformers.aliasToBean(Animal.class)).iterate(); .setResultTransformer(Transformers.aliasToBean(Animal.class)).iterate();
assertTrue( "Incorrect result size", iter.hasNext() ); assertTrue( "Incorrect result size", iter.hasNext() );
assertTrue( "Incorrect return type", iter.next() instanceof Animal ); assertTrue( "Incorrect return type", iter.next() instanceof Animal );
t.commit();
session.close(); session.close();
session = openSession(); session = openSession();
t = session.beginTransaction();
ScrollableResults sr = session.createQuery( query ) ScrollableResults sr = session.createQuery( query )
.setResultTransformer(Transformers.aliasToBean(Animal.class)).scroll(); .setResultTransformer(Transformers.aliasToBean(Animal.class)).scroll();
@ -3498,20 +3534,23 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
assertFalse( session.contains( sr.get( 0 ) ) ); assertFalse( session.contains( sr.get( 0 ) ) );
sr.close(); sr.close();
t.commit();
session.close(); session.close();
session = openSession(); session = openSession();
t = session.beginTransaction();
results = session.createQuery( "select a from Animal a, Animal b order by a.id" ) results = session.createQuery( "select a from Animal a, Animal b order by a.id" )
.setResultTransformer( DistinctRootEntityResultTransformer.INSTANCE ) .setResultTransformer( DistinctRootEntityResultTransformer.INSTANCE )
.list(); .list();
assertEquals( "Incorrect result size", 2, results.size()); assertEquals( "Incorrect result size", 2, results.size());
assertTrue( "Incorrect return type", results.get(0) instanceof Animal ); assertTrue( "Incorrect return type", results.get( 0 ) instanceof Animal );
firstAnimal = (Animal) results.get(0); firstAnimal = (Animal) results.get(0);
secondAnimal = (Animal) results.get(1); secondAnimal = (Animal) results.get(1);
assertEquals( "Mammal #1", firstAnimal.getDescription() ); assertEquals( "Mammal #1", firstAnimal.getDescription() );
assertEquals( "Mammal #2", secondAnimal.getDescription() ); assertEquals( "Mammal #2", secondAnimal.getDescription() );
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -3524,6 +3563,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
String query = "select an as an from Animal an order by bodyWeight desc"; String query = "select an as an from Animal an order by bodyWeight desc";
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
List results = session.createQuery( query ) List results = session.createQuery( query )
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
@ -3536,11 +3576,13 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
Animal secondAnimal = (Animal) map.get("an"); Animal secondAnimal = (Animal) map.get("an");
assertEquals( "Mammal #1", firstAnimal.getDescription() ); assertEquals( "Mammal #1", firstAnimal.getDescription() );
assertEquals("Mammal #2", secondAnimal.getDescription()); assertEquals("Mammal #2", secondAnimal.getDescription());
assertTrue(session.contains(firstAnimal)); assertTrue( session.contains( firstAnimal));
assertSame( firstAnimal, session.get( Animal.class, firstAnimal.getId() ) ); assertSame( firstAnimal, session.get( Animal.class, firstAnimal.getId() ) );
t.commit();
session.close(); session.close();
session = openSession(); session = openSession();
t = session.beginTransaction();
Iterator iter = session.createQuery( query ) Iterator iter = session.createQuery( query )
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).iterate(); .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).iterate();
@ -3550,9 +3592,11 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
assertEquals( "Mammal #1", firstAnimal.getDescription() ); assertEquals( "Mammal #1", firstAnimal.getDescription() );
assertTrue( "Incorrect result size", iter.hasNext() ); assertTrue( "Incorrect result size", iter.hasNext() );
t.commit();
session.close(); session.close();
session = openSession(); session = openSession();
t = session.beginTransaction();
ScrollableResults sr = session.createQuery( query ) ScrollableResults sr = session.createQuery( query )
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).scroll(); .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).scroll();
@ -3562,6 +3606,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
assertFalse( session.contains( sr.get( 0 ) ) ); assertFalse( session.contains( sr.get( 0 ) ) );
sr.close(); sr.close();
t.commit();
session.close(); session.close();
destroyTestBaseData(); destroyTestBaseData();
@ -3570,6 +3615,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testEJBQLFunctions() throws Exception { public void testEJBQLFunctions() throws Exception {
Session session = openSession(); Session session = openSession();
Transaction t = session.beginTransaction();
String hql = "from Animal a where a.description = concat('1', concat('2','3'), '4'||'5')||'0'"; String hql = "from Animal a where a.description = concat('1', concat('2','3'), '4'||'5')||'0'";
session.createQuery(hql).list(); session.createQuery(hql).list();
@ -3672,6 +3718,7 @@ public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
hql = "from Animal a where a.description like 'x%ax%' escape 'x'"; hql = "from Animal a where a.description like 'x%ax%' escape 'x'";
session.createQuery(hql).list(); session.createQuery(hql).list();
t.commit();
session.close(); session.close();
} }

View File

@ -10,6 +10,7 @@ import javax.persistence.Entity;
import javax.persistence.Id; import javax.persistence.Id;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test; import org.junit.Test;
@ -36,12 +37,25 @@ public class CastFunctionTest extends BaseCoreFunctionalTestCase {
Session s = openSession(); Session s = openSession();
s.beginTransaction(); s.beginTransaction();
// using the short name if ( getDialect() instanceof DerbyDialect ) {
s.createQuery( "select cast(e.theLostNumber as string) from MyEntity e" ).list(); // the conversion from DOUBLE to VARCHAR is not supported by Derby,
// using the java class name // using the short name
s.createQuery( "select cast(e.theLostNumber as java.lang.String) from MyEntity e" ).list(); s.createQuery( "select cast(char(e.theLostNumber) as string) from MyEntity e" ).list();
// using the fqn Hibernate Type name // using the java class name
s.createQuery( "select cast(e.theLostNumber as org.hibernate.type.StringType) from MyEntity e" ).list(); s.createQuery( "select cast(char(e.theLostNumber) as java.lang.String) from MyEntity e" ).list();
// using the fqn Hibernate Type name
s.createQuery( "select cast(char(e.theLostNumber) as org.hibernate.type.StringType) from MyEntity e" )
.list();
}
else {
// using the short name
s.createQuery( "select cast(e.theLostNumber as string) from MyEntity e" ).list();
// using the java class name
s.createQuery( "select cast(e.theLostNumber as java.lang.String) from MyEntity e" ).list();
// using the fqn Hibernate Type name
s.createQuery( "select cast(e.theLostNumber as org.hibernate.type.StringType) from MyEntity e" )
.list();
}
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();

View File

@ -9,7 +9,7 @@
<hibernate-mapping package="org.hibernate.test.legacy"> <hibernate-mapping package="org.hibernate.test.legacy">
<class name="CompositeIdId"> <class name="CompositeIdId">
<composite-id> <composite-id>
<key-property name="system"/> <key-property name="user"/>
<key-property name="id"/> <key-property name="id"/>
</composite-id> </composite-id>
<property name="name"/> <property name="name"/>
@ -23,7 +23,7 @@
<sql-query name="loadC"> <sql-query name="loadC">
<return alias="c" class="CompositeIdId"/> <return alias="c" class="CompositeIdId"/>
select "system" as {c.system}, id as {c.id}, name as {c.name}, foo as {c.composite.foo}, bar as {c.composite.bar} from CompositeIdId where "system"=? and id=? select "user" as {c.user}, id as {c.id}, name as {c.name}, foo as {c.composite.foo}, bar as {c.composite.bar} from CompositeIdId where "user"=? and id=?
</sql-query> </sql-query>
</hibernate-mapping> </hibernate-mapping>

View File

@ -18,7 +18,7 @@ import java.io.Serializable;
*/ */
public class CompositeIdId implements Serializable { public class CompositeIdId implements Serializable {
String system; String user;
String id; String id;
String name; String name;
CompositeElement composite; CompositeElement composite;
@ -30,11 +30,11 @@ public class CompositeIdId implements Serializable {
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public String getSystem() { public String getUser() {
return system; return user;
} }
public void setSystem(String system) { public void setUser(String user) {
this.system = system; this.user = user;
} }
public String getName() { public String getName() {
return name; return name;
@ -50,7 +50,7 @@ public class CompositeIdId implements Serializable {
// not totally NP or type safe equals, but enough for the unittests. // not totally NP or type safe equals, but enough for the unittests.
CompositeIdId o = (CompositeIdId) obj; CompositeIdId o = (CompositeIdId) obj;
if(o==null) return false; if(o==null) return false;
return o.getSystem().equals(getSystem()) && o.getId().equals(getId()); return o.getUser().equals( getUser()) && o.getId().equals(getId());
} }
public CompositeElement getComposite() { public CompositeElement getComposite() {
return composite; return composite;

View File

@ -3534,22 +3534,29 @@ public class FooBarTest extends LegacyTestCase {
Session s = openSession(); Session s = openSession();
Transaction txn = s.beginTransaction(); Transaction txn = s.beginTransaction();
Foo foo = new Foo(); Foo foo = new Foo();
s.save(foo); s.save( foo );
Foo foo1 = new Foo(); Foo foo1 = new Foo();
s.save(foo1); s.save(foo1);
foo.setFoo(foo1); foo.setFoo( foo1 );
List l = s.createQuery( "select parent, child from Foo parent, Foo child where parent.foo = child" ).list(); List l = s.createQuery( "select parent, child from Foo parent, Foo child where parent.foo = child" ).list();
assertTrue( "multi-column find", l.size()==1 ); assertTrue( "multi-column find", l.size()==1 );
Iterator rs = s.createQuery( Iterator rs = null;
"select count(distinct child.id), count(distinct parent.id) from Foo parent, Foo child where parent.foo = child" Object[] row = null;
).iterate(); //Derby does not support multiple DISTINCT aggregates
Object[] row = (Object[]) rs.next(); if ( !(getDialect() instanceof DerbyDialect) ) {
assertTrue( "multi-column count", ( (Long) row[0] ).intValue()==1 ); rs = s.createQuery(
assertTrue( "multi-column count", ( (Long) row[1] ).intValue()==1 ); "select count(distinct child.id), count(distinct parent.id) from Foo parent, Foo child where parent.foo = child"
assertTrue( !rs.hasNext() ); ).iterate();
rs = s.createQuery( "select child.id, parent.id, child.long from Foo parent, Foo child where parent.foo = child" ) row = (Object[]) rs.next();
assertTrue( "multi-column count", ((Long) row[0]).intValue() == 1 );
assertTrue( "multi-column count", ((Long) row[1]).intValue() == 1 );
assertTrue( !rs.hasNext() );
}
rs = s.createQuery(
"select child.id, parent.id, child.long from Foo parent, Foo child where parent.foo = child"
)
.iterate(); .iterate();
row = (Object[]) rs.next(); row = (Object[]) rs.next();
assertTrue( "multi-column id", row[0].equals( foo.getFoo().getKey() ) ); assertTrue( "multi-column id", row[0].equals( foo.getFoo().getKey() ) );

View File

@ -15,6 +15,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.TeradataDialect; import org.hibernate.dialect.TeradataDialect;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.junit.Test; import org.junit.Test;
@ -384,7 +385,7 @@ public class SQLFunctionsTest extends LegacyTestCase {
simple.setName("Simple 1"); simple.setName("Simple 1");
s.save( simple ); s.save( simple );
if ( getDialect() instanceof DB2Dialect) { if ( getDialect() instanceof DB2Dialect && !(getDialect() instanceof DerbyDialect) ) {
s.createQuery( "from Simple s where repeat('foo', 3) = 'foofoofoo'" ).list(); s.createQuery( "from Simple s where repeat('foo', 3) = 'foofoofoo'" ).list();
s.createQuery( "from Simple s where repeat(s.name, 3) = 'foofoofoo'" ).list(); s.createQuery( "from Simple s where repeat(s.name, 3) = 'foofoofoo'" ).list();
s.createQuery( "from Simple s where repeat( lower(s.name), 3 + (1-1) / 2) = 'foofoofoo'" ).list(); s.createQuery( "from Simple s where repeat( lower(s.name), 3 + (1-1) / 2) = 'foofoofoo'" ).list();

View File

@ -98,7 +98,7 @@ public class SQLLoaderTest extends LegacyTestCase {
Category s = new Category(); Category s = new Category();
s.setName(String.valueOf(nextLong++)); s.setName(String.valueOf(nextLong++));
session.save(s); session.save( s );
Simple simple = new Simple( Long.valueOf(nextLong++) ); Simple simple = new Simple( Long.valueOf(nextLong++) );
simple.init(); simple.init();
@ -108,7 +108,7 @@ public class SQLLoaderTest extends LegacyTestCase {
session.save(a); session.save(a);
B b = new B(); B b = new B();
session.save(b); session.save( b );
session.flush(); session.flush();
session.createSQLQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list(); session.createSQLQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list();
@ -128,17 +128,17 @@ public class SQLLoaderTest extends LegacyTestCase {
} }
Category s = new Category(); Category s = new Category();
s.setName(String.valueOf(nextLong++)); s.setName( String.valueOf( nextLong++ ) );
session.save(s); session.save( s );
s = new Category(); s = new Category();
s.setName("WannaBeFound"); s.setName( "WannaBeFound" );
session.flush(); session.flush();
Query query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name = :name" ) Query query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name = :name" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
query.setProperties(s); query.setProperties( s );
//query.setParameter("name", s.getName()); //query.setParameter("name", s.getName());
query.list(); query.list();
@ -146,7 +146,7 @@ public class SQLLoaderTest extends LegacyTestCase {
query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in (:names)" ) query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in (:names)" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
String[] str = new String[] { "WannaBeFound", "NotThere" }; String[] str = new String[] { "WannaBeFound", "NotThere" };
query.setParameterList("names", str); query.setParameterList( "names", str );
query.uniqueResult(); query.uniqueResult();
query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in :names" ) query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in :names" )
@ -157,12 +157,12 @@ public class SQLLoaderTest extends LegacyTestCase {
query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in (:names)" ) query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in (:names)" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
str = new String[] { "WannaBeFound" }; str = new String[] { "WannaBeFound" };
query.setParameterList("names", str); query.setParameterList( "names", str );
query.uniqueResult(); query.uniqueResult();
query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in :names" ) query = session.createSQLQuery( "select {category.*} from category {category} where {category}.name in :names" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
query.setParameterList("names", str); query.setParameterList( "names", str );
query.uniqueResult(); query.uniqueResult();
session.getTransaction().commit(); session.getTransaction().commit();
@ -402,10 +402,10 @@ public class SQLLoaderTest extends LegacyTestCase {
} }
A savedA = new A(); A savedA = new A();
savedA.setName("Max"); savedA.setName("Max");
session.save(savedA); session.save( savedA );
B savedB = new B(); B savedB = new B();
session.save(savedB); session.save( savedB );
session.flush(); session.flush();
int count = session.createQuery("from A").list().size(); int count = session.createQuery("from A").list().size();
@ -429,7 +429,7 @@ public class SQLLoaderTest extends LegacyTestCase {
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull(list);
assertEquals(1, list.size()); assertEquals( 1, list.size() );
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@ -443,10 +443,10 @@ public class SQLLoaderTest extends LegacyTestCase {
} }
A savedA = new A(); A savedA = new A();
savedA.setName("Max"); savedA.setName("Max");
session.save(savedA); session.save( savedA );
B savedB = new B(); B savedB = new B();
session.save(savedB); session.save( savedB );
session.flush(); session.flush();
int count = session.createQuery("from A").list().size(); int count = session.createQuery("from A").list().size();
@ -469,7 +469,7 @@ public class SQLLoaderTest extends LegacyTestCase {
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull(list);
assertEquals(2, list.size()); assertEquals( 2, list.size() );
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@ -556,12 +556,12 @@ public class SQLLoaderTest extends LegacyTestCase {
session.beginTransaction(); session.beginTransaction();
SQLQuery q = session.createSQLQuery( sql ).addEntity( "comp", Componentizable.class ); SQLQuery q = session.createSQLQuery( sql ).addEntity( "comp", Componentizable.class );
List list = q.list(); List list = q.list();
assertEquals(list.size(),1); assertEquals( list.size(), 1 );
Componentizable co = (Componentizable) list.get(0); Componentizable co = (Componentizable) list.get(0);
assertEquals(c.getNickName(), co.getNickName()); assertEquals( c.getNickName(), co.getNickName() );
assertEquals(c.getComponent().getName(), co.getComponent().getName()); assertEquals( c.getComponent().getName(), co.getComponent().getName() );
assertEquals(c.getComponent().getSubComponent().getSubName(), co.getComponent().getSubComponent().getSubName()); assertEquals( c.getComponent().getSubComponent().getSubName(), co.getComponent().getSubComponent().getSubName() );
session.delete( co ); session.delete( co );
session.getTransaction().commit(); session.getTransaction().commit();
@ -573,16 +573,16 @@ public class SQLLoaderTest extends LegacyTestCase {
session.beginTransaction(); session.beginTransaction();
Componentizable c = new Componentizable(); Componentizable c = new Componentizable();
c.setNickName("Flacky"); c.setNickName( "Flacky" );
Component component = new Component(); Component component = new Component();
component.setName("flakky comp"); component.setName("flakky comp");
SubComponent subComponent = new SubComponent(); SubComponent subComponent = new SubComponent();
subComponent.setSubName("subway"); subComponent.setSubName("subway");
component.setSubComponent(subComponent); component.setSubComponent( subComponent );
c.setComponent(component); c.setComponent( component );
session.save(c); session.save( c );
session.getTransaction().commit(); session.getTransaction().commit();
session.clear(); session.clear();
@ -603,8 +603,8 @@ public class SQLLoaderTest extends LegacyTestCase {
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull( list );
assertTrue(list.size() > 0); assertTrue( list.size() > 0 );
assertTrue(list.get(0) instanceof Category); assertTrue(list.get(0) instanceof Category);
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); session.close();
@ -632,9 +632,9 @@ public class SQLLoaderTest extends LegacyTestCase {
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull( list );
assertTrue(list.size() > 0); assertTrue( list.size() > 0 );
assertTrue(list.get(0) instanceof Category); assertTrue( list.get( 0 ) instanceof Category );
// How do we handle objects that does not have id property (such as Simple ?) // How do we handle objects that does not have id property (such as Simple ?)
// How do we handle objects with composite id's ? (such as Single) // How do we handle objects with composite id's ? (such as Single)
@ -667,7 +667,7 @@ public class SQLLoaderTest extends LegacyTestCase {
A a2 = (A) list.get(1); A a2 = (A) list.get(1);
assertTrue((a2 instanceof B) || (a1 instanceof B)); assertTrue((a2 instanceof B) || (a1 instanceof B));
assertFalse(a1 instanceof B && a2 instanceof B); assertFalse( a1 instanceof B && a2 instanceof B );
if (a1 instanceof B) { if (a1 instanceof B) {
assertSame(a1, savedB); assertSame(a1, savedB);
@ -730,7 +730,7 @@ public class SQLLoaderTest extends LegacyTestCase {
s.beginTransaction(); s.beginTransaction();
CompositeIdId id = new CompositeIdId(); CompositeIdId id = new CompositeIdId();
id.setName("Max"); id.setName("Max");
id.setSystem("c64"); id.setUser( "c64" );
id.setId("games"); id.setId("games");
s.save(id); s.save(id);
s.getTransaction().commit(); s.getTransaction().commit();
@ -741,13 +741,13 @@ public class SQLLoaderTest extends LegacyTestCase {
// having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it. // having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it.
// NOTE : SYSTEM is an ANSI SQL defined keyword, so it gets quoted; so it needs to get quoted here too // NOTE : SYSTEM is an ANSI SQL defined keyword, so it gets quoted; so it needs to get quoted here too
String sql = String.format( String sql = String.format(
"select %1$s as {c.system}, " + "select %1$s as {c.user}, " +
" id as {c.id}, name as {c.name}, " + " id as {c.id}, name as {c.name}, " +
" foo as {c.composite.foo}, " + " foo as {c.composite.foo}, " +
" bar as {c.composite.bar} " + " bar as {c.composite.bar} " +
"from CompositeIdId " + "from CompositeIdId " +
"where %1$s=? and id=?", "where %1$s=? and id=?",
getDialect().openQuote() + "system" + getDialect().closeQuote() getDialect().openQuote() + "user" + getDialect().closeQuote()
); );
SQLQuery query = s.createSQLQuery( sql ).addEntity( "c", CompositeIdId.class ); SQLQuery query = s.createSQLQuery( sql ).addEntity( "c", CompositeIdId.class );
@ -763,7 +763,7 @@ public class SQLLoaderTest extends LegacyTestCase {
s = openSession(); s = openSession();
s.beginTransaction(); s.beginTransaction();
CompositeIdId useForGet = new CompositeIdId(); CompositeIdId useForGet = new CompositeIdId();
useForGet.setSystem("c64"); useForGet.setUser( "c64" );
useForGet.setId("games"); useForGet.setId("games");
// this doesn't work since the verification does not take column span into respect! // this doesn't work since the verification does not take column span into respect!
CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet); CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet);
@ -776,7 +776,6 @@ public class SQLLoaderTest extends LegacyTestCase {
assertEquals(id,id2); assertEquals(id,id2);
assertEquals(id.getName(), id2.getName()); assertEquals(id.getName(), id2.getName());
assertEquals(id.getId(), id2.getId()); assertEquals(id.getId(), id2.getId());
assertEquals(id.getSystem(), id2.getSystem()); assertEquals(id.getUser(), id2.getUser());
} }
} }

View File

@ -31,7 +31,7 @@ public class BasicGetLoadAccessTest extends BaseNonConfigCoreFunctionalTestCase
} }
@Entity( name = "User" ) @Entity( name = "User" )
@Table( name = "user" ) @Table( name = "my_user" )
public static class User { public static class User {
private Integer id; private Integer id;
private String name; private String name;

View File

@ -38,7 +38,7 @@ public class ProxiedGetLoadAccessTest extends BaseNonConfigCoreFunctionalTestCas
} }
@Entity( name = "User" ) @Entity( name = "User" )
@Table( name = "user" ) @Table( name = "my_user" )
@Proxy( proxyClass = User.class ) @Proxy( proxyClass = User.class )
public static class UserImpl implements User { public static class UserImpl implements User {
private Integer id; private Integer id;

View File

@ -26,7 +26,7 @@
<property name="title"/> <property name="title"/>
<property name="author"/> <property name="author"/>
<component name="pubDate"> <component name="pubDate">
<property name="year" not-null="true"/> <property name="year" not-null="true" column="pubDate_year"/>
<property name="month"/> <property name="month"/>
</component> </component>
<property name="summary"/> <property name="summary"/>
@ -41,7 +41,7 @@
<property name="title"/> <property name="title"/>
<property name="author"/> <property name="author"/>
<component name="pubDate"> <component name="pubDate">
<property name="year" not-null="true"/> <property name="year" not-null="true" column="pubDate_year" />
<property name="month"/> <property name="month"/>
</component> </component>
<property name="summary"/> <property name="summary"/>

View File

@ -20,7 +20,10 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.hbm2ddl.Target; import org.hibernate.tool.hbm2ddl.Target;
import org.hibernate.testing.DialectCheck;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.FailureExpected; import org.hibernate.testing.FailureExpected;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase; import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test; import org.junit.Test;
@ -28,6 +31,7 @@ import org.junit.Test;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@RequiresDialectFeature( value = {DialectChecks.SupportSchemaCreation.class, DialectChecks.SupportCatalogCreation.class})
public class ForeignKeyMigrationTest extends BaseUnitTestCase { public class ForeignKeyMigrationTest extends BaseUnitTestCase {
@Test @Test
@TestForIssue( jiraKey = "HHH-9716" ) @TestForIssue( jiraKey = "HHH-9716" )

View File

@ -124,7 +124,7 @@ public abstract class SchemaExportTest extends BaseUnitTestCase {
assertEquals( 0, schemaExport.getExceptions().size() ); assertEquals( 0, schemaExport.getExceptions().size() );
} }
else { else {
assertEquals( 2, schemaExport.getExceptions().size() ); assertEquals( 1, schemaExport.getExceptions().size() );
} }
// call create again; it should drop tables before re-creating // call create again; it should drop tables before re-creating
schemaExport.create( true, true ); schemaExport.create( true, true );

View File

@ -11,6 +11,7 @@ import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
@ -67,6 +68,7 @@ public class TestFkUpdating {
@Entity( name = "User" ) @Entity( name = "User" )
@Table( name = "my_user")
public static class User { public static class User {
private Integer id; private Integer id;
private Set<Role> roles; private Set<Role> roles;

View File

@ -15,6 +15,7 @@ import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.FetchMode; import org.hibernate.FetchMode;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
@ -128,6 +129,7 @@ public class SortTest extends BaseCoreFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "Owner")
private static class Owner { private static class Owner {
@Id @Id
@ -140,6 +142,7 @@ public class SortTest extends BaseCoreFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "Cat")
private static class Cat implements Comparable<Cat> { private static class Cat implements Comparable<Cat> {
@Id @Id

View File

@ -6,6 +6,8 @@
*/ */
package org.hibernate.test.sql.hand.custom; package org.hibernate.test.sql.hand.custom;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
@ -15,6 +17,8 @@ import org.hibernate.HibernateException;
import org.hibernate.Query; import org.hibernate.Query;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.procedure.ProcedureCall;
import org.hibernate.test.sql.hand.Employment; import org.hibernate.test.sql.hand.Employment;
import org.hibernate.test.sql.hand.Organization; import org.hibernate.test.sql.hand.Organization;
import org.hibernate.test.sql.hand.Person; import org.hibernate.test.sql.hand.Person;
@ -88,6 +92,4 @@ public abstract class CustomStoredProcTestSupport extends CustomSQLTestSupport {
t.commit(); t.commit();
s.close(); s.close();
} }
} }

View File

@ -7,8 +7,11 @@
package org.hibernate.test.sql.hand.custom.db2; package org.hibernate.test.sql.hand.custom.db2;
import org.hibernate.dialect.DB2Dialect; import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport; import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.SkipForDialect;
/** /**
* Custom SQL tests for DB2 * Custom SQL tests for DB2
@ -16,6 +19,7 @@ import org.hibernate.testing.RequiresDialect;
* @author Max Rydahl Andersen * @author Max Rydahl Andersen
*/ */
@RequiresDialect( DB2Dialect.class ) @RequiresDialect( DB2Dialect.class )
@SkipForDialect( DerbyDialect.class )
public class DB2CustomSQLTest extends CustomStoredProcTestSupport { public class DB2CustomSQLTest extends CustomStoredProcTestSupport {
public String[] getMappings() { public String[] getMappings() {
return new String[] { "sql/hand/custom/db2/Mappings.hbm.xml" }; return new String[] { "sql/hand/custom/db2/Mappings.hbm.xml" };

View File

@ -0,0 +1,22 @@
/*
* 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.sql.hand.custom.derby;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
/**
* @author Andrea Boriero
*/
@RequiresDialect(DerbyDialect.class)
public class DerbyCustomSQLTest extends CustomStoredProcTestSupport {
public String[] getMappings() {
return new String[] {"sql/hand/custom/derby/Mappings.hbm.xml"};
}
}

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.test.sql.hand.custom.derby;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Andrea Boriero
*/
public class DerbyStoreProcedures {
public static void selectAllEmployments(ResultSet[] resultSets) throws SQLException {
Connection conn = DriverManager.getConnection( "jdbc:default:connection" );
PreparedStatement statement = conn.prepareStatement(
"select EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE," +
" REGIONCODE, EMPID, 'VALUE', CURRENCY" +
" FROM EMPLOYMENT"
);
resultSets[0] = statement.executeQuery();
conn.close();
}
public static void paramHandling(short j, short i, ResultSet[] resultSets) throws SQLException {
Connection conn = DriverManager.getConnection( "jdbc:default:connection" );
PreparedStatement statement = conn.prepareStatement( "SELECT " + j + " as value, " + i + " as value2 from sysibm.sysdummy1" );
resultSets[0] = statement.executeQuery();
conn.close();
}
public static void simpleScalar(short i, ResultSet[] resultSets) throws SQLException {
Connection conn = DriverManager.getConnection( "jdbc:default:connection" );
PreparedStatement statement = conn.prepareStatement(
"SELECT " + i + " as value, 'getAll' as name from sysibm.sysdummy1"
);
resultSets[0] = statement.executeQuery();
conn.close();
}
}

View File

@ -0,0 +1,275 @@
<?xml version="1.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>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
This mapping demonstrates the use of Hibernate with all-handwritten SQL!
NOTE : this version is for DB2 & variants
-->
<hibernate-mapping package="org.hibernate.test.sql.hand" default-access="field">
<class name="Organization" table="ORGANIZATION">
<id name="id" unsaved-value="0" column="ORGID">
<generator class="increment"/>
</id>
<property name="name" not-null="true" column="NAME"/>
<set name="employments"
inverse="true"
order-by="DUMMY">
<key column="EMPLOYER"/> <!-- only needed for DDL generation -->
<one-to-many class="Employment"/>
<loader query-ref="organizationEmployments"/>
</set>
<!-- query-list name="currentEmployments"
query-ref="organizationCurrentEmployments"-->
<loader query-ref="organization"/>
<sql-insert>INSERT INTO ORGANIZATION (NAME, ORGID) VALUES ( UPPER(? || ''), ? )</sql-insert>
<sql-update>UPDATE ORGANIZATION SET NAME=UPPER(? || '') WHERE ORGID=?</sql-update>
<sql-delete>DELETE FROM ORGANIZATION WHERE ORGID=?</sql-delete>
</class>
<class name="Person" table="PERSON">
<id name="id" unsaved-value="0" column="PERID">
<generator class="increment"/>
</id>
<property name="name" not-null="true" column="NAME"/>
<loader query-ref="person"/>
<sql-insert>INSERT INTO PERSON (NAME, PERID) VALUES ( UPPER(? || ''), ? )</sql-insert>
<sql-update>UPDATE PERSON SET NAME=UPPER(? || '') WHERE PERID=?</sql-update>
<sql-delete>DELETE FROM PERSON WHERE PERID=?</sql-delete>
</class>
<class name="Employment" table="EMPLOYMENT">
<id name="employmentId" unsaved-value="0" column="EMPID">
<generator class="increment"/>
</id>
<many-to-one name="employee" column="EMPLOYEE" not-null="true" update="false"/>
<many-to-one name="employer" column="EMPLOYER" not-null="true" update="false"/>
<property name="startDate" column="STARTDATE" not-null="true" update="false" insert="false"/>
<property name="endDate" column="ENDDATE" insert="false"/>
<property name="regionCode" column="REGIONCODE" update="false"/>
<property name="salary" type="org.hibernate.test.sql.hand.MonetaryAmountUserType">
<column name="`VALUE`" sql-type="float"/>
<column name="CURRENCY"/>
</property>
<loader query-ref="employment"/>
<sql-insert>
INSERT INTO EMPLOYMENT
(EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, VALUE, CURRENCY, EMPID)
<!-- inserting raw specific timestamp since using current date or current timestamp for some reason does not work with a timestamp column! -->
VALUES (?, ?, TIMESTAMP ('2006-02-28 11:39:00'), UPPER(? || ''), ?, ?, ?)
</sql-insert>
<sql-update>UPDATE EMPLOYMENT SET ENDDATE=?, VALUE=?, CURRENCY=? WHERE EMPID=?</sql-update>
<sql-delete>DELETE FROM EMPLOYMENT WHERE EMPID=?</sql-delete>
</class>
<class name="TextHolder">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="description" type="text" length="15000"/>
<loader query-ref="textholder"/>
<sql-insert>
INSERT INTO TEXTHOLDER
(DESCRIPTION, ID)
VALUES (?, ?)
</sql-insert>
<sql-update>UPDATE TEXTHOLDER SET DESCRIPTION=? WHERE ID=?</sql-update>
<sql-delete>DELETE FROM TEXTHOLDER WHERE ID=?</sql-delete>
</class>
<class name="ImageHolder">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="photo" type="image" length="15000"/>
<loader query-ref="imageholder"/>
<sql-insert>
INSERT INTO IMAGEHOLDER
(PHOTO, ID)
VALUES (?, ?)
</sql-insert>
<sql-update>UPDATE IMAGEHOLDER SET PHOTO=? WHERE ID=?</sql-update>
<sql-delete>DELETE FROM IMAGEHOLDER WHERE ID=?</sql-delete>
</class>
<resultset name="org-emp-regionCode">
<return-scalar column="regionCode" type="string"/>
<return alias="org" class="Organization"/>
<return-join alias="emp" property="org.employments"/>
</resultset>
<resultset name="org-emp-person">
<return alias="org" class="Organization"/>
<return-join alias="emp" property="org.employments"/>
<return-join alias="pers" property="emp.employee"/>
</resultset>
<sql-query name="person">
<return alias="p" class="Person" lock-mode="upgrade"/>
SELECT NAME AS {p.name}, PERID AS {p.id} FROM PERSON WHERE PERID=? /*FOR UPDATE*/
</sql-query>
<sql-query name="organization">
<return alias="org" class="Organization"/>
<return-join alias="emp" property="org.employments"/>
SELECT {org.*}, {emp.*}
FROM ORGANIZATION org
LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
WHERE org.ORGID=?
</sql-query>
<!--sql-query name="organization">
<return alias="org" class="Organization"/>
SELECT NAME AS {org.name}, ORGID AS {org.id} FROM ORGANIZATION
WHERE ORGID=?
</sql-query-->
<sql-query name="allOrganizationsWithEmployees" flush-mode="never">
<return alias="org" class="Organization"/>
SELECT DISTINCT org.NAME AS {org.name}, org.ORGID AS {org.id}
FROM ORGANIZATION org
INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ORGID
</sql-query>
<sql-query name="employment">
<return alias="emp" class="Employment"/>
SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}
FROM EMPLOYMENT
WHERE EMPID = ?
</sql-query>
<sql-query name="organizationEmployments">
<load-collection alias="empcol" role="Organization.employments"/>
SELECT {empcol.*}
FROM EMPLOYMENT empcol
WHERE EMPLOYER = :id
ORDER BY STARTDATE ASC, EMPLOYEE ASC
</sql-query>
<sql-query name="organizationCurrentEmployments">
<return alias="emp" class="Employment">
<return-property name="salary">
<!-- as multi column properties are not supported via the
{}-syntax, we need to provide an explicit column list for salary via <return-property> -->
<return-column name="`VALUE`"/>
<return-column name="CURRENCY"/>
</return-property>
<!-- Here we are remapping endDate. Notice that we can still use {emp.endDate} in the SQL. -->
<return-property name="endDate" column="myEndDate"/>
</return>
<synchronize table="EMPLOYMENT"/>
SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}, VALUE, CURRENCY
FROM EMPLOYMENT
WHERE EMPLOYER = :id AND ENDDATE IS NULL
ORDER BY STARTDATE ASC
</sql-query>
<sql-query name="simpleScalar" callable="true">
<return-scalar column="name" type="string"/>
<return-scalar column="`value`" type="long"/>
{ call simpleScalar(:number) }
</sql-query>
<sql-query name="paramhandling" callable="true">
<return-scalar column="`value`" type="long"/>
<return-scalar column="value2" type="long"/>
{ call paramHandling(?,?) }
</sql-query>
<sql-query name="paramhandling_mixed" callable="true">
<return-scalar column="`value`" type="long" />
<return-scalar column="value2" type="long" />
{ call paramHandling(?,:second) }
</sql-query>
<sql-query name="selectAllEmployments" callable="true">
<return alias="" class="Employment">
<return-property name="employee" column="EMPLOYEE"/>
<return-property name="employer" column="EMPLOYER"/>
<return-property name="startDate" column="STARTDATE"/>
<return-property name="endDate" column="ENDDATE"/>
<return-property name="regionCode" column="REGIONCODE"/>
<return-property name="id" column="EMPID"/>
<return-property name="salary">
<!-- as multi column properties are not supported via the
{}-syntax, we need to provide an explicit column list for salary via <return-property> -->
<return-column name="`VALUE`"/>
<return-column name="CURRENCY"/>
</return-property>
</return>
{ call selectAllEmployments() }
</sql-query>
<sql-query name="textholder">
<return alias="h" class="TextHolder" lock-mode="upgrade"/>
SELECT ID AS {h.id}, DESCRIPTION AS {h.description} FROM TEXTHOLDER WHERE ID=? /*FOR UPDATE*/
</sql-query>
<sql-query name="imageholder">
<return alias="h" class="ImageHolder" lock-mode="upgrade"/>
SELECT ID AS {h.id}, PHOTO AS {h.photo} FROM IMAGEHOLDER WHERE ID=? /*FOR UPDATE*/
</sql-query>
<database-object>
<create>
CREATE PROCEDURE selectAllEmployments ()
PARAMETER STYLE JAVA
LANGUAGE JAVA
READS SQL DATA
DYNAMIC RESULT SETS 2
EXTERNAL NAME 'org.hibernate.test.sql.hand.custom.derby.DerbyStoreProcedures.selectAllEmployments'
</create>
<drop>
DROP PROCEDURE selectAllEmployments
</drop>
</database-object>
<database-object>
<create>
CREATE PROCEDURE paramHandling (j SMALLINT, i SMALLINT)
PARAMETER STYLE JAVA
LANGUAGE JAVA
READS SQL DATA
DYNAMIC RESULT SETS 2
EXTERNAL NAME 'org.hibernate.test.sql.hand.custom.derby.DerbyStoreProcedures.paramHandling'
</create>
<drop>
DROP PROCEDURE paramHandling
</drop>
</database-object>
<database-object>
<create>
CREATE PROCEDURE simpleScalar (j SMALLINT)
PARAMETER STYLE JAVA
LANGUAGE JAVA
READS SQL DATA
DYNAMIC RESULT SETS 2
EXTERNAL NAME 'org.hibernate.test.sql.hand.custom.derby.DerbyStoreProcedures.simpleScalar'
</create>
<drop>
DROP PROCEDURE simpleScalar
</drop>
</database-object>
</hibernate-mapping>

View File

@ -12,6 +12,7 @@ import java.util.List;
import org.junit.Assert; import org.junit.Assert;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServerDialect; import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.SybaseDialect; import org.hibernate.dialect.SybaseDialect;
@ -27,7 +28,8 @@ import org.junit.Test;
@SkipForDialects({ @SkipForDialects({
@SkipForDialect(value = H2Dialect.class, comment = "H2 doesn't support this sql syntax"), @SkipForDialect(value = H2Dialect.class, comment = "H2 doesn't support this sql syntax"),
@SkipForDialect(value = SQLServerDialect.class, comment = "mssql doesn't support multiple columns in the 'where' clause of a 'where in' query"), @SkipForDialect(value = SQLServerDialect.class, comment = "mssql doesn't support multiple columns in the 'where' clause of a 'where in' query"),
@SkipForDialect(value = SybaseDialect.class, comment = "sybase doesn't support multiple columns in the 'where' clause of a 'where in' query")}) @SkipForDialect(value = SybaseDialect.class, comment = "sybase doesn't support multiple columns in the 'where' clause of a 'where in' query"),
@SkipForDialect(value = DerbyDialect.class, comment = "derby doesn't support multiple columns in the 'where' clause of a 'where in' query")})
@TestForIssue( jiraKey = "HHH-8312") @TestForIssue( jiraKey = "HHH-8312")
public class CompositeIdTypeBindingTest extends BaseCoreFunctionalTestCase { public class CompositeIdTypeBindingTest extends BaseCoreFunctionalTestCase {
@Override @Override

View File

@ -12,6 +12,7 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
@ -81,6 +82,7 @@ public class TimePropertyTest extends BaseCoreFunctionalTestCase {
} }
@javax.persistence.Entity @javax.persistence.Entity
@Table(name = "entity")
public static class Entity { public static class Entity {
@GeneratedValue @GeneratedValue
@Id @Id

View File

@ -12,6 +12,7 @@ import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
@ -140,6 +141,7 @@ public class TimestampPropertyTest extends BaseCoreFunctionalTestCase {
} }
@javax.persistence.Entity @javax.persistence.Entity
@Table(name = "MyEntity")
public static class Entity { public static class Entity {
@GeneratedValue @GeneratedValue
@Id @Id

View File

@ -127,7 +127,7 @@ public class BeforeCompletionFailureTest extends BaseNonConfigCoreFunctionalTest
public static class SimpleEntity { public static class SimpleEntity {
@Id @Id
public Integer id; public Integer id;
@Column(unique = true) @Column(unique = true, name = "entity_key")
public String key; public String key;
public String name; public String name;

View File

@ -160,7 +160,7 @@ public class ElementCollectionTests extends BaseNonConfigCoreFunctionalTestCase
}) })
@ElementCollection(fetch = FetchType.LAZY) @ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "entity_map", joinColumns = @JoinColumn(name = "entity_id", nullable = false)) @CollectionTable(name = "entity_map", joinColumns = @JoinColumn(name = "entity_id", nullable = false))
@MapKeyColumn(name = "key", nullable = false) @MapKeyColumn(name = "map_key", nullable = false)
@Column(name = "value", nullable = false) @Column(name = "value", nullable = false)
public Map<ValueType, ValueType> map = new HashMap<ValueType, ValueType>(); public Map<ValueType, ValueType> map = new HashMap<ValueType, ValueType>();

View File

@ -45,6 +45,7 @@
<exclude-superclass-listeners/> <exclude-superclass-listeners/>
<attributes> <attributes>
<basic name="year" optional="false"> <basic name="year" optional="false">
<column name="model_year"/>
<temporal>DATE</temporal> <temporal>DATE</temporal>
</basic> </basic>
</attributes> </attributes>

View File

@ -14,6 +14,7 @@ import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.junit.Test; import org.junit.Test;
@ -72,6 +73,7 @@ public class DetachAndContainsTest extends BaseEntityManagerFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "mouth")
public static class Mouth { public static class Mouth {
@Id @Id
@GeneratedValue @GeneratedValue
@ -81,6 +83,7 @@ public class DetachAndContainsTest extends BaseEntityManagerFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "tooth")
public static class Tooth { public static class Tooth {
@Id @Id
@GeneratedValue @GeneratedValue

View File

@ -15,6 +15,7 @@ import javax.persistence.EntityListeners;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.PrePersist; import javax.persistence.PrePersist;
import javax.persistence.Table;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -62,6 +63,7 @@ public class BasicCDITest extends BaseCDIIntegrationTest {
@Entity @Entity
@EntityListeners( Monitor.class ) @EntityListeners( Monitor.class )
@Table(name = "my_entity")
public static class MyEntity { public static class MyEntity {
private Integer id; private Integer id;
private String name; private String name;

View File

@ -11,6 +11,7 @@ package org.hibernate.jpa.test.connection;
import java.io.File; import java.io.File;
import javax.persistence.EntityManagerFactory; import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import org.hibernate.ejb.HibernatePersistence; import org.hibernate.ejb.HibernatePersistence;
@ -37,10 +38,14 @@ public class DataSourceInjectionTest {
emf.close(); emf.close();
} }
catch (Exception ignore) { catch (Exception ignore) {
int i = 0;
} }
} }
Assert.fail( "FakeDatasource should have been used" ); Assert.fail( "FakeDatasource should have been used" );
} }
catch (PersistenceException pe) {
Assert.assertTrue( pe.getCause() instanceof FakeDataSourceException );
}
catch (FakeDataSourceException fde) { catch (FakeDataSourceException fde) {
//success //success
} }

View File

@ -7,6 +7,7 @@
package org.hibernate.jpa.test.convert; package org.hibernate.jpa.test.convert;
import javax.persistence.AttributeConverter; import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Converter; import javax.persistence.Converter;
import javax.persistence.Embeddable; import javax.persistence.Embeddable;
import javax.persistence.Embedded; import javax.persistence.Embedded;
@ -86,8 +87,10 @@ public class QueryTest extends BaseEntityManagerFunctionalTestCase {
@Embeddable @Embeddable
public static class Name { public static class Name {
@Column(name = "first_name")
public String first; public String first;
public String middle; public String middle;
@Column(name = "last_name")
public String last; public String last;
public Name() { public Name() {

View File

@ -14,10 +14,12 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest; import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.jpa.test.metamodel.Product; import org.hibernate.jpa.test.metamodel.Product;
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.hibernate.testing.TestForIssue;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -26,6 +28,7 @@ public class CastTest extends AbstractMetamodelSpecificTest {
private static final int QUANTITY = 2; private static final int QUANTITY = 2;
@Test @Test
@SkipForDialect(value = DerbyDialect.class,comment = "Derby does not support cast from INTEGER to VARCHAR")
@TestForIssue( jiraKey = "HHH-5755" ) @TestForIssue( jiraKey = "HHH-5755" )
public void testCastToString() { public void testCastToString() {
EntityManager em = getOrCreateEntityManager(); EntityManager em = getOrCreateEntityManager();

View File

@ -20,6 +20,7 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
@Entity @Entity
@Table(name = "users")
public class User { public class User {
private Long id; private Long id;
private Set<Role> roles = new HashSet<Role>(); private Set<Role> roles = new HashSet<Role>();

View File

@ -27,6 +27,7 @@ import javax.persistence.EntityManager;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
@ -121,6 +122,7 @@ public class SelectCaseTest extends BaseEntityManagerFunctionalTestCase {
} }
@javax.persistence.Entity @javax.persistence.Entity
@Table(name = "entity")
public static class Entity { public static class Entity {
@Id @Id

View File

@ -19,6 +19,7 @@ import javax.persistence.Id;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Subgraph; import javax.persistence.Subgraph;
import javax.persistence.Table;
import org.hibernate.Hibernate; import org.hibernate.Hibernate;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
@ -248,6 +249,7 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "foo")
public static class Foo { public static class Foo {
@Id @Id
@ -262,6 +264,7 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "bar")
public static class Bar { public static class Bar {
@Id @Id
@ -273,6 +276,7 @@ public class EntityGraphTest extends BaseEntityManagerFunctionalTestCase {
} }
@Entity @Entity
@Table(name = "baz")
public static class Baz { public static class Baz {
@Id @Id

View File

@ -51,8 +51,8 @@ public class BasicSametable extends BaseEnversJPAFunctionalTestCase {
session.createSQLQuery( "DROP TABLE children" ).executeUpdate(); session.createSQLQuery( "DROP TABLE children" ).executeUpdate();
session.createSQLQuery( session.createSQLQuery(
"CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
).executeUpdate(); ).executeUpdate();
session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate();
session.createSQLQuery( session.createSQLQuery(
@ -60,8 +60,8 @@ public class BasicSametable extends BaseEnversJPAFunctionalTestCase {
", REVEND " + getDialect().getTypeName( Types.INTEGER ) + ", REVEND " + getDialect().getTypeName( Types.INTEGER ) +
", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) +
", parent_id " + getDialect().getTypeName( Types.INTEGER ) + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
).executeUpdate(); ).executeUpdate();
em.getTransaction().commit(); em.getTransaction().commit();
em.clear(); em.clear();

View File

@ -78,8 +78,8 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu
session session
.createSQLQuery( .createSQLQuery(
"CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
) )
.executeUpdate(); .executeUpdate();
session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate();
@ -90,8 +90,8 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu
", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) + ", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) +
", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) +
", parent_id " + getDialect().getTypeName( Types.INTEGER ) + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
) )
.executeUpdate(); .executeUpdate();
em.getTransaction().commit(); em.getTransaction().commit();

View File

@ -77,8 +77,8 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe
session session
.createSQLQuery( .createSQLQuery(
"CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
) )
.executeUpdate(); .executeUpdate();
session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate();
@ -89,8 +89,8 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe
", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) + ", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) +
", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) +
", parent_id " + getDialect().getTypeName( Types.INTEGER ) + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) +
", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() +
", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + getDialect().getNullColumnString() + " )"
) )
.executeUpdate(); .executeUpdate();
em.getTransaction().commit(); em.getTransaction().commit();

View File

@ -165,4 +165,16 @@ abstract public class DialectChecks {
return '\"' == dialect.openQuote() && '\"' == dialect.closeQuote(); return '\"' == dialect.openQuote() && '\"' == dialect.closeQuote();
} }
} }
public static class SupportSchemaCreation implements DialectCheck {
public boolean isMatch(Dialect dialect) {
return dialect.canCreateSchema();
}
}
public static class SupportCatalogCreation implements DialectCheck {
public boolean isMatch(Dialect dialect) {
return dialect.canCreateCatalog();
}
}
} }

View File

@ -18,6 +18,7 @@ import javax.persistence.SharedCacheMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Interceptor; import org.hibernate.Interceptor;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl; import org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl;
import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
@ -35,6 +36,7 @@ import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.AbstractReturningWork; import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jdbc.Work; import org.hibernate.jdbc.Work;
import org.hibernate.resource.transaction.TransactionCoordinator; import org.hibernate.resource.transaction.TransactionCoordinator;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce; import org.hibernate.testing.BeforeClassOnce;
@ -358,6 +360,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
if ( tdc.getStatus().canRollback() ) { if ( tdc.getStatus().canRollback() ) {
session.getTransaction().rollback(); session.getTransaction().rollback();
} }
session.close();
} }
protected void cleanupCache() { protected void cleanupCache() {
@ -369,16 +372,24 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
protected boolean isCleanupTestDataRequired() { protected boolean isCleanupTestDataRequired() {
return false; return false;
} }
protected void cleanupTestData() throws Exception { protected void cleanupTestData() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction(); Transaction transaction = s.beginTransaction();
s.createQuery( "delete from java.lang.Object" ).executeUpdate(); try {
s.getTransaction().commit(); s.createQuery( "delete from java.lang.Object" ).executeUpdate();
s.close(); transaction.commit();
}
catch (Exception e) {
if ( transaction.getStatus().canRollback() ) {
transaction.rollback();
}
}
finally {
s.close();
}
} }
private void cleanupSession() { private void cleanupSession() {
if ( session != null && ! ( (SessionImplementor) session ).isClosed() ) { if ( session != null && ! ( (SessionImplementor) session ).isClosed() ) {
session.close(); session.close();
@ -405,7 +416,9 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
} }
Session tmpSession = sessionFactory.openSession(); Session tmpSession = sessionFactory.openSession();
Transaction transaction = tmpSession.beginTransaction();
try { try {
List list = tmpSession.createQuery( "select o from java.lang.Object o" ).list(); List list = tmpSession.createQuery( "select o from java.lang.Object o" ).list();
Map<String,Integer> items = new HashMap<String,Integer>(); Map<String,Integer> items = new HashMap<String,Integer>();
@ -419,11 +432,16 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
items.put( tmpSession.getEntityName( element ), l ); items.put( tmpSession.getEntityName( element ), l );
System.out.println( "Data left: " + element ); System.out.println( "Data left: " + element );
} }
transaction.rollback();
fail( "Data is left in the database: " + items.toString() ); fail( "Data is left in the database: " + items.toString() );
} }
transaction.rollback();
} }
finally { finally {
try { try {
if(transaction.getStatus().canRollback()){
transaction.rollback();
}
tmpSession.close(); tmpSession.close();
} }
catch( Throwable t ) { catch( Throwable t ) {

View File

@ -81,7 +81,7 @@ ext {
shrinkwrap_api: 'org.jboss.shrinkwrap:shrinkwrap-api:1.0.0-beta-6', shrinkwrap_api: 'org.jboss.shrinkwrap:shrinkwrap-api:1.0.0-beta-6',
shrinkwrap: 'org.jboss.shrinkwrap:shrinkwrap-impl-base:1.0.0-beta-6', shrinkwrap: 'org.jboss.shrinkwrap:shrinkwrap-impl-base:1.0.0-beta-6',
h2: "com.h2database:h2:${h2Version}", h2: "com.h2database:h2:${h2Version}",
derby: "org.apache.derby:derby:10.9.1.0", derby: "org.apache.derby:derby:10.11.1.1",
jboss_jta: "org.jboss.jbossts:jbossjta:4.16.4.Final", jboss_jta: "org.jboss.jbossts:jbossjta:4.16.4.Final",
xapool: "com.experlog:xapool:1.5.0", xapool: "com.experlog:xapool:1.5.0",
mockito: 'org.mockito:mockito-core:1.9.0', mockito: 'org.mockito:mockito-core:1.9.0',