code_snippet
stringlengths
92
2.48k
score
float64
1.83
4.89
@SuppressWarnings( {"unchecked"}) @Test public void testAnyMappingReference() { Session s = openSession(); s.beginTransaction(); PropertyValue redValue = new StringPropertyValue( "red" ); PropertyValue loneliestNumberValue = new IntegerPropertyValue( 1 ); Long id; PropertySet ps = new PropertySet( "my properties" ); ps.setSomeSpecificProperty( redValue ); ps.getGeneralProperties().put( "the loneliest number", loneliestNumberValue ); ps.getGeneralProperties().put( "i like", new StringPropertyValue( "pina coladas" ) ); ps.getGeneralProperties().put( "i also like", new StringPropertyValue( "getting caught in the rain" ) ); s.save( ps ); s.getTransaction().commit(); id = ps.getId(); s.clear(); s.beginTransaction(); // TODO : setEntity() currently will not work here, but that would be *very* nice // does not work because the corresponding EntityType is then used as the "bind type" rather // than the "discovered" AnyType... s.createQuery( "from PropertySet p where p.someSpecificProperty = :ssp" ).setParameter( "ssp", redValue ).list(); s.createQuery( "from PropertySet p where p.someSpecificProperty.id is not null" ).list(); s.createQuery( "from PropertySet p join p.generalProperties gp where gp.id is not null" ).list(); s.delete( s.load( PropertySet.class, id ) ); s.getTransaction().commit(); s.close(); }
3.666667
@Test public void testFetchInSubqueryFails() { Session s = openSession(); try { s.createQuery( "from Animal a where a.mother in (select m from Animal a1 inner join a1.mother as m join fetch m.mother)" ).list(); fail( "fetch join allowed in subquery" ); } catch( QueryException expected ) { // expected behavior } s.close(); }
4.333333
@Test @TestForIssue( jiraKey = "HHH-429" ) @SuppressWarnings( {"unchecked"}) public void testSuperclassPropertyReferenceAfterCollectionIndexedAccess() { // note: simply performing syntax checking in the db Session s = openSession(); s.beginTransaction(); Mammal tiger = new Mammal(); tiger.setDescription( "Tiger" ); s.persist( tiger ); Mammal mother = new Mammal(); mother.setDescription( "Tiger's mother" ); mother.setBodyWeight( 4.0f ); mother.addOffspring( tiger ); s.persist( mother ); Zoo zoo = new Zoo(); zoo.setName( "Austin Zoo" ); zoo.setMammals( new HashMap() ); zoo.getMammals().put( "tiger", tiger ); s.persist( zoo ); s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); List results = s.createQuery( "from Zoo zoo where zoo.mammals['tiger'].mother.bodyWeight > 3.0f" ).list(); assertEquals( 1, results.size() ); s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); s.delete( tiger ); s.delete( mother ); s.delete( zoo ); s.getTransaction().commit(); s.close(); }
3.777778
@Test @SuppressWarnings( {"UnusedAssignment", "UnusedDeclaration"}) public void testSelectExpressions() { createTestBaseData(); Session session = openSession(); Transaction txn = session.beginTransaction(); Human h = new Human(); h.setName( new Name( "Gavin", 'A', "King" ) ); h.setNickName("Oney"); h.setBodyWeight( 1.0f ); session.persist( h ); List results = session.createQuery("select 'found', lower(h.name.first) from Human h where lower(h.name.first) = 'gavin'").list(); results = session.createQuery("select 'found', lower(h.name.first) from Human h where concat(h.name.first, ' ', h.name.initial, ' ', h.name.last) = 'Gavin A King'").list(); results = session.createQuery("select 'found', lower(h.name.first) from Human h where h.name.first||' '||h.name.initial||' '||h.name.last = 'Gavin A King'").list(); results = session.createQuery("select a.bodyWeight + m.bodyWeight from Animal a join a.mother m").list(); results = session.createQuery("select 2.0 * (a.bodyWeight + m.bodyWeight) from Animal a join a.mother m").list(); results = session.createQuery("select sum(a.bodyWeight + m.bodyWeight) from Animal a join a.mother m").list(); results = session.createQuery("select sum(a.mother.bodyWeight * 2.0) from Animal a").list(); results = session.createQuery("select concat(h.name.first, ' ', h.name.initial, ' ', h.name.last) from Human h").list(); results = session.createQuery("select h.name.first||' '||h.name.initial||' '||h.name.last from Human h").list(); results = session.createQuery("select nickName from Human").list(); results = session.createQuery("select lower(nickName) from Human").list(); results = session.createQuery("select abs(bodyWeight*-1) from Human").list(); results = session.createQuery("select upper(h.name.first||' ('||h.nickName||')') from Human h").list(); results = session.createQuery("select abs(a.bodyWeight-:param) from Animal a").setParameter("param", new Float(2.0)).list(); results = session.createQuery("select abs(:param - a.bodyWeight) from Animal a").setParameter("param", new Float(2.0)).list(); results = session.createQuery("select lower(upper('foo')) from Animal").list(); results = session.createQuery("select lower(upper('foo') || upper('bar')) from Animal").list(); results = session.createQuery("select sum(abs(bodyWeight - 1.0) * abs(length('ffobar')-3)) from Animal").list(); session.delete(h); txn.commit(); session.close(); destroyTestBaseData(); }
3.444444
/** * Build a normal attribute. * * @param ownerType The descriptor of the attribute owner (aka declarer). * @param property The Hibernate property descriptor for the attribute * @param <X> The type of the owner * @param <Y> The attribute type * * @return The built attribute descriptor or null if the attribute is not part of the JPA 2 model (eg backrefs) */ @SuppressWarnings({"unchecked"}) public <X, Y> AttributeImplementor<X, Y> buildAttribute(AbstractManagedType<X> ownerType, Property property) { if ( property.isSynthetic() ) { // hide synthetic/virtual properties (fabricated by Hibernate) from the JPA metamodel. LOG.tracef( "Skipping synthetic property %s(%s)", ownerType.getTypeName(), property.getName() ); return null; } LOG.trace( "Building attribute [" + ownerType.getTypeName() + "." + property.getName() + "]" ); final AttributeContext<X> attributeContext = wrap( ownerType, property ); final AttributeMetadata<X, Y> attributeMetadata = determineAttributeMetadata( attributeContext, normalMemberResolver ); if ( attributeMetadata == null ) { return null; } if ( attributeMetadata.isPlural() ) { return buildPluralAttribute( (PluralAttributeMetadata) attributeMetadata ); } final SingularAttributeMetadata<X, Y> singularAttributeMetadata = (SingularAttributeMetadata<X, Y>) attributeMetadata; final Type<Y> metaModelType = getMetaModelType( singularAttributeMetadata.getValueContext() ); return new SingularAttributeImpl<X, Y>( attributeMetadata.getName(), attributeMetadata.getJavaType(), ownerType, attributeMetadata.getMember(), false, false, property.isOptional(), metaModelType, attributeMetadata.getPersistentAttributeType() ); }
2.888889
@Test public void testOtherSyntax() throws Exception { parse( "select bar from org.hibernate.test.Bar bar order by ((bar.x - :valueX)*(bar.x - :valueX))" ); parse( "from bar in class org.hibernate.test.Bar, foo in elements(bar.baz.fooSet)" ); parse( "from one in class org.hibernate.test.One, many in elements(one.manies) where one.id = 1 and many.id = 1" ); parse( "from org.hibernate.test.Inner _inner join _inner.middles middle" ); parse( "FROM m IN CLASS org.hibernate.test.Master WHERE NOT EXISTS ( FROM d IN elements(m.details) WHERE NOT d.i=5 )" ); parse( "FROM m IN CLASS org.hibernate.test.Master WHERE NOT 5 IN ( SELECT d.i FROM d IN elements(m.details) )" ); parse( "SELECT m FROM m IN CLASS org.hibernate.test.Master, d IN elements(m.details) WHERE d.i=5" ); parse( "SELECT m FROM m IN CLASS org.hibernate.test.Master, d IN elements(m.details) WHERE d.i=5" ); parse( "SELECT m.id FROM m IN CLASS org.hibernate.test.Master, d IN elements(m.details) WHERE d.i=5" ); // I'm not sure about these... [jsd] // parse("select bar.string, foo.string from bar in class org.hibernate.test.Bar inner join bar.baz as baz inner join elements(baz.fooSet) as foo where baz.name = 'name'"); // parse("select bar.string, foo.string from bar in class org.hibernate.test.Bar, bar.baz as baz, elements(baz.fooSet) as foo where baz.name = 'name'"); // parse("select count(*) where this.amount>-1 and this.name is null"); // parse("from sm in class org.hibernate.test.SubMulti where exists sm.children.elements"); }
3.888889
@Test public void testPathologicalKeywordAsIdentifier() throws Exception { // Super evil badness... a legitimate keyword! parse( "from Order order" ); //parse( "from Order order join order.group" ); parse( "from X x order by x.group.by.from" ); parse( "from Order x order by x.order.group.by.from" ); parse( "select order.id from Order order" ); parse( "select order from Order order" ); parse( "from Order order where order.group.by.from is not null" ); parse( "from Order order order by order.group.by.from" ); // Okay, now this is getting silly. parse( "from Group as group group by group.by.from" ); }
4
@Test public void testHHH1780() throws Exception { // verifies the tree contains a NOT->EXISTS subtree class Verifier { public boolean verify(AST root) { Stack<AST> queue = new Stack<AST>(); queue.push( root ); while ( !queue.isEmpty() ) { AST parent = queue.pop(); AST child = parent.getFirstChild(); while ( child != null ) { if ( parent.getType() == HqlTokenTypes.NOT && child.getType() == HqlTokenTypes.EXISTS ) { return true; } queue.push( child ); child = child.getNextSibling(); } } return false; } } // test inversion of AND AST ast = doParse( "from Person p where not ( p.name is null and exists(select a.id from Address a where a.id=p.id))", false ); assertTrue( new Verifier().verify( ast ) ); // test inversion of OR ast = doParse( "from Person p where not ( p.name is null or exists(select a.id from Address a where a.id=p.id))", false ); assertTrue( new Verifier().verify( ast ) ); }
3.222222
@Test public void testDateTimeArithmeticReturnTypesAndParameterGuessing() { QueryTranslatorImpl translator = createNewQueryTranslator( "select o.orderDate - o.orderDate from Order o" ); assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); translator = createNewQueryTranslator( "select o.orderDate + 2 from Order o" ); assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); assertEquals( "incorrect return type", CalendarDateType.INSTANCE, translator.getReturnTypes()[0] ); translator = createNewQueryTranslator( "select o.orderDate -2 from Order o" ); assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); assertEquals( "incorrect return type", CalendarDateType.INSTANCE, translator.getReturnTypes()[0] ); translator = createNewQueryTranslator( "from Order o where o.orderDate > ?" ); assertEquals( "incorrect expected param type", CalendarDateType.INSTANCE, translator.getParameterTranslations().getOrdinalParameterExpectedType( 1 ) ); translator = createNewQueryTranslator( "select o.orderDate + ? from Order o" ); assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); assertEquals( "incorrect return type", CalendarDateType.INSTANCE, translator.getReturnTypes()[0] ); assertEquals( "incorrect expected param type", DoubleType.INSTANCE, translator.getParameterTranslations().getOrdinalParameterExpectedType( 1 ) ); }
3.666667
@Test public void testExpressionWithParamInFunction() { assertTranslation("from Animal a where abs(a.bodyWeight-:param) < 2.0"); assertTranslation("from Animal a where abs(:param - a.bodyWeight) < 2.0"); assertTranslation("from Animal where abs(:x - :y) < 2.0"); assertTranslation("from Animal where lower(upper(:foo)) like 'f%'"); if ( ! ( getDialect() instanceof SybaseDialect ) && ! ( getDialect() instanceof Sybase11Dialect ) && ! ( getDialect() instanceof SybaseASE15Dialect ) && ! ( getDialect() instanceof SQLServerDialect ) ) { // Transact-SQL dialects (except SybaseAnywhereDialect) map the length function -> len; // classic translator does not consider that *when nested*; // SybaseAnywhereDialect supports the length function assertTranslation("from Animal a where abs(abs(a.bodyWeight - 1.0 + :param) * abs(length('ffobar')-3)) = 3.0"); } if ( !( getDialect() instanceof MySQLDialect ) && ! ( getDialect() instanceof SybaseDialect ) && ! ( getDialect() instanceof Sybase11Dialect ) && !( getDialect() instanceof SybaseASE15Dialect ) && ! ( getDialect() instanceof SybaseAnywhereDialect ) && ! ( getDialect() instanceof SQLServerDialect ) ) { assertTranslation("from Animal where lower(upper('foo') || upper(:bar)) like 'f%'"); } if ( getDialect() instanceof PostgreSQLDialect || getDialect() instanceof PostgreSQL81Dialect ) { return; } if ( getDialect() instanceof AbstractHANADialect ) { // HANA returns // ...al0_7_.mammal where [abs(cast(1 as float(19))-cast(? as float(19)))=1.0] return; } assertTranslation("from Animal where abs(cast(1 as float) - cast(:param as float)) = 1.0"); }
2.888889
@Test public void testHHH6635() throws Exception { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> set = mBeanServer.queryNames( null, null ); boolean mbeanfound = false; for ( ObjectName obj : set ) { if ( obj.getKeyPropertyListString().indexOf( "PooledDataSource" ) > 0 ) { mbeanfound = true; // see according c3p0 settings in META-INF/persistence.xml int actual_minPoolSize = (Integer) mBeanServer.getAttribute( obj, "minPoolSize" ); assertEquals( 50, actual_minPoolSize ); int actual_initialPoolSize = (Integer) mBeanServer.getAttribute( obj, "initialPoolSize" ); assertEquals( 50, actual_initialPoolSize ); int actual_maxPoolSize = (Integer) mBeanServer.getAttribute( obj, "maxPoolSize" ); assertEquals( 800, actual_maxPoolSize ); int actual_maxStatements = (Integer) mBeanServer.getAttribute( obj, "maxStatements" ); assertEquals( 50, actual_maxStatements ); int actual_maxIdleTime = (Integer) mBeanServer.getAttribute( obj, "maxIdleTime" ); assertEquals( 300, actual_maxIdleTime ); int actual_idleConnectionTestPeriod = (Integer) mBeanServer.getAttribute( obj, "idleConnectionTestPeriod" ); assertEquals( 3000, actual_idleConnectionTestPeriod ); break; } } assertTrue( "PooledDataSource BMean not found, please verify version of c3p0", mbeanfound ); }
3.666667
@Test public void testFilterApplicationOnHqlQueryWithImplicitSubqueryContainingPositionalParameter() { TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.beginTransaction(); final String queryString = "from Order o where ? in ( select sp.name from Salesperson sp )"; // first a control-group query List result = session.createQuery( queryString ).setParameter( 0, "steve" ).list(); assertEquals( 2, result.size() ); // now lets enable filters on Order... session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() ); result = session.createQuery( queryString ).setParameter( 0, "steve" ).list(); assertEquals( 1, result.size() ); // now, lets additionally enable filter on Salesperson. First a valid one... session.enableFilter( "regionlist" ).setParameterList( "regions", new String[] { "APAC" } ); result = session.createQuery( queryString ).setParameter( 0, "steve" ).list(); assertEquals( 1, result.size() ); // ... then a silly one... session.enableFilter( "regionlist" ).setParameterList( "regions", new String[] { "gamma quadrant" } ); result = session.createQuery( queryString ).setParameter( 0, "steve" ).list(); assertEquals( 0, result.size() ); session.getTransaction().commit(); session.close(); testData.release(); }
4.222222
@SuppressWarnings( {"unchecked"}) @Test public void testDistinctSelectWithJoin() { feedDatabase(); Session s = openSession(); List<Entry> entries = s.createQuery("select distinct e from Entry e join e.tags t where t.surrogate != null order by e.name").setFirstResult(10).setMaxResults(5).list(); // System.out.println(entries); Entry firstEntry = entries.remove(0); assertFalse("The list of entries should not contain dublicated Entry objects as we've done a distinct select", entries.contains(firstEntry)); s.close(); }
4.555556
@Test @SkipForDialect( value = { MySQLMyISAMDialect.class, AbstractHANADialect.class }, comment = "MySQL (MyISAM) / Hana do not support FK violation checking" ) public void testIntegrityViolation() throws Exception { final Session session = openSession(); session.beginTransaction(); session.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { // Attempt to insert some bad values into the T_MEMBERSHIP table that should // result in a constraint violation PreparedStatement ps = null; try { ps = ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( "INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)" ); ps.setLong(1, 52134241); // Non-existent user_id ps.setLong(2, 5342); // Non-existent group_id ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( ps ); fail("INSERT should have failed"); } catch (ConstraintViolationException ignore) { // expected outcome } finally { releaseStatement( session, ps ); } } } ); session.getTransaction().rollback(); session.close(); }
3.666667
@Test public void testBadGrammar() throws Exception { final Session session = openSession(); session.beginTransaction(); session.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { // prepare/execute a query against a non-existent table PreparedStatement ps = null; try { ps = ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( "SELECT user_id, user_name FROM tbl_no_there" ); ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( ps ); fail("SQL compilation should have failed"); } catch (SQLGrammarException ignored) { // expected outcome } finally { releaseStatement( session, ps ); } } } ); session.getTransaction().rollback(); session.close(); }
3.222222
private void releaseStatement(Session session, PreparedStatement ps) { if ( ps != null ) { try { ( (SessionImplementor) session ).getTransactionCoordinator().getJdbcCoordinator().release( ps ); } catch ( Throwable ignore ) { // ignore... } } }
3.888889
@Test public void testEntityWithLazyAssnList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { protected Criteria getCriteria(Session s) { // should use RootEntityTransformer by default return s.createCriteria( Student.class ) .addOrder( Order.asc( "studentNumber" ) ); } }; HqlExecutor hqlExecutor = new HqlExecutor() { public Query getQuery(Session s) { return s.createQuery( "from Student order by studentNumber" ); } }; ResultChecker checker = new ResultChecker() { public void check(Object results) { List resultList = ( List ) results; assertEquals( 2, resultList.size() ); assertEquals( yogiExpected, resultList.get( 0 ) ); assertEquals( shermanExpected, resultList.get( 1 ) ); assertNotNull( ((Student) resultList.get( 0 )).getEnrolments() ); assertNotNull( ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ); assertNotNull( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ); assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ) ); assertFalse( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); } }; runTest( hqlExecutor, criteriaExecutor, checker, false ); }
3.111111
@Test public void testJoinWithFetchJoinListCriteria() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { protected Criteria getCriteria(Session s) { return s.createCriteria( Student.class, "s" ) .createAlias( "s.preferredCourse", "pc", Criteria.LEFT_JOIN ) .setFetchMode( "enrolments", FetchMode.JOIN ) .addOrder( Order.asc( "s.studentNumber") ); } }; ResultChecker checker = new ResultChecker() { public void check(Object results) { List resultList = ( List ) results; assertEquals( 2, resultList.size() ); assertEquals( yogiExpected, resultList.get( 0 ) ); // The following fails for criteria due to HHH-3524 //assertEquals( yogiExpected.getPreferredCourse(), ( ( Student ) resultList.get( 0 ) ).getPreferredCourse() ); assertEquals( yogiExpected.getPreferredCourse().getCourseCode(), ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() ); assertEquals( shermanExpected, resultList.get( 1 ) ); assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); if ( areDynamicNonLazyAssociationsChecked() ) { assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); } } }; runTest( null, criteriaExecutor, checker, false ); }
2.777778
@Test public void testEntityWithAliasedJoinFetchedLazyOneToManySingleElementListHql() throws Exception { HqlExecutor hqlExecutor = new HqlExecutor() { public Query getQuery(Session s) { return s.createQuery( "from Student s left join fetch s.enrolments e order by s.studentNumber" ); } }; ResultChecker checker = new ResultChecker() { public void check(Object results) { List resultList = ( List ) results; assertEquals( 2, resultList.size() ); assertEquals( yogiExpected, resultList.get( 0 ) ); assertEquals( yogiExpected.getPreferredCourse().getCourseCode(), ( ( Student ) resultList.get( 0 ) ).getPreferredCourse().getCourseCode() ); assertEquals( shermanExpected, resultList.get( 1 ) ); assertNull( ( ( Student ) resultList.get( 1 ) ).getPreferredCourse() ); if ( areDynamicNonLazyAssociationsChecked() ) { assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 0 ) ).getEnrolments() ) ); assertEquals( yogiExpected.getEnrolments(), ( ( Student ) resultList.get( 0 ) ).getEnrolments() ); assertTrue( Hibernate.isInitialized( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) resultList.get( 1 ) ).getEnrolments() ) ); } } }; runTest( hqlExecutor, null, checker, false); }
3
@Test public void testMultiSelectNewMapUsingAliasesWithFetchJoinList() throws Exception { CriteriaExecutor criteriaExecutor = new CriteriaExecutor() { protected Criteria getCriteria(Session s) { return s.createCriteria( Student.class, "s" ) .createAlias( "s.preferredCourse", "pc", Criteria.LEFT_JOIN ) .setFetchMode( "enrolments", FetchMode.JOIN ) .addOrder( Order.asc( "s.studentNumber" )) .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP ); } }; HqlExecutor hqlSelectNewMapExecutor = new HqlExecutor() { public Query getQuery(Session s) { return s.createQuery( "select new map(s as s, pc as pc) from Student s left join s.preferredCourse pc left join fetch s.enrolments order by s.studentNumber" ); } }; ResultChecker checker = new ResultChecker() { public void check(Object results) { List resultList = ( List ) results; assertEquals( 2, resultList.size() ); Map yogiMap = ( Map ) resultList.get( 0 ); assertEquals( yogiExpected, yogiMap.get( "s" ) ); assertEquals( yogiExpected.getPreferredCourse(), yogiMap.get( "pc" ) ); Map shermanMap = ( Map ) resultList.get( 1 ); assertEquals( shermanExpected, shermanMap.get( "s" ) ); assertNull( shermanMap.get( "pc" ) ); if ( areDynamicNonLazyAssociationsChecked() ) { assertTrue( Hibernate.isInitialized( ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ) ); assertEquals( yogiExpected.getEnrolments(), ( ( Student ) yogiMap.get( "s" ) ).getEnrolments() ); assertTrue( Hibernate.isInitialized( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); assertEquals( shermanExpected.getEnrolments(), ( ( ( Student ) shermanMap.get( "s" ) ).getEnrolments() ) ); } } }; runTest( hqlSelectNewMapExecutor, criteriaExecutor, checker, false ); }
3.222222
public void afterSessionFactoryBuilt() { super.afterSessionFactoryBuilt(); final Session session = sessionFactory().openSession(); session.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { Statement st = ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().createStatement(); try { ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().execute( st, "drop table Point"); } catch (Exception ignored) { } ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().execute( st, "create table Point (\"x\" number(19,2) not null, \"y\" number(19,2) not null, description varchar2(255) )"); ((SessionImplementor)session).getTransactionCoordinator().getJdbcCoordinator().release( st ); } } ); session.close(); }
3.666667
@Test public void testNoLoss() { assertNoLoss( "insert into Address (city, state, zip, \"from\") values (?, ?, ?, 'insert value')" ); assertNoLoss( "delete from Address where id = ? and version = ?" ); assertNoLoss( "update Address set city = ?, state=?, zip=?, version = ? where id = ? and version = ?" ); assertNoLoss( "update Address set city = ?, state=?, zip=?, version = ? where id in (select aid from Person)" ); assertNoLoss( "select p.name, a.zipCode, count(*) from Person p left outer join Employee e on e.id = p.id and p.type = 'E' and (e.effective>? or e.effective<?) join Address a on a.pid = p.id where upper(p.name) like 'G%' and p.age > 100 and (p.sex = 'M' or p.sex = 'F') and coalesce( trim(a.street), a.city, (a.zip) ) is not null order by p.name asc, a.zipCode asc" ); assertNoLoss( "select ( (m.age - p.age) * 12 ), trim(upper(p.name)) from Person p, Person m where p.mother = m.id and ( p.age = (select max(p0.age) from Person p0 where (p0.mother=m.id)) and p.name like ? )" ); assertNoLoss( "select * from Address a join Person p on a.pid = p.id, Person m join Address b on b.pid = m.id where p.mother = m.id and p.name like ?" ); assertNoLoss( "select case when p.age > 50 then 'old' when p.age > 18 then 'adult' else 'child' end from Person p where ( case when p.age > 50 then 'old' when p.age > 18 then 'adult' else 'child' end ) like ?" ); assertNoLoss( "/* Here we' go! */ select case when p.age > 50 then 'old' when p.age > 18 then 'adult' else 'child' end from Person p where ( case when p.age > 50 then 'old' when p.age > 18 then 'adult' else 'child' end ) like ?" ); }
3.333333
/** * Throws {@link org.hibernate.PropertyValueException} if there are any unresolved * entity insert actions that depend on non-nullable associations with * a transient entity. This method should be called on completion of * an operation (after all cascades are completed) that saves an entity. * * @throws org.hibernate.PropertyValueException if there are any unresolved entity * insert actions; {@link org.hibernate.PropertyValueException#getEntityName()} * and {@link org.hibernate.PropertyValueException#getPropertyName()} will * return the entity name and property value for the first unresolved * entity insert action. */ public void checkNoUnresolvedActionsAfterOperation() throws PropertyValueException { if ( isEmpty() ) { LOG.trace( "No entity insert actions have non-nullable, transient entity dependencies." ); } else { final AbstractEntityInsertAction firstDependentAction = dependenciesByAction.keySet().iterator().next(); logCannotResolveNonNullableTransientDependencies( firstDependentAction.getSession() ); final NonNullableTransientDependencies nonNullableTransientDependencies = dependenciesByAction.get( firstDependentAction ); final Object firstTransientDependency = nonNullableTransientDependencies.getNonNullableTransientEntities().iterator().next(); final String firstPropertyPath = nonNullableTransientDependencies.getNonNullableTransientPropertyPaths( firstTransientDependency ).iterator().next(); throw new TransientPropertyValueException( "Not-null property references a transient value - transient instance must be saved before current operation", firstDependentAction.getSession().guessEntityName( firstTransientDependency ), firstDependentAction.getEntityName(), firstPropertyPath ); } }
3.333333
/** * Handle sending notifications needed for natural-id after saving * * @param generatedId The generated entity identifier */ public void handleNaturalIdPostSaveNotifications(Serializable generatedId) { if ( isEarlyInsert() ) { // with early insert, we still need to add a local (transactional) natural id cross-reference getSession().getPersistenceContext().getNaturalIdHelper().manageLocalNaturalIdCrossReference( getPersister(), generatedId, state, null, CachedNaturalIdValueSource.INSERT ); } // after save, we need to manage the shared cache entries getSession().getPersistenceContext().getNaturalIdHelper().manageSharedNaturalIdCrossReference( getPersister(), getId(), state, null, CachedNaturalIdValueSource.INSERT ); }
3.888889
private boolean initializeLazyProperty( final String fieldName, final Object entity, final SessionImplementor session, final Object[] snapshot, final int j, final Object propValue) { setPropertyValue( entity, lazyPropertyNumbers[j], propValue ); if ( snapshot != null ) { // object have been loaded with setReadOnly(true); HHH-2236 snapshot[ lazyPropertyNumbers[j] ] = lazyPropertyTypes[j].deepCopy( propValue, factory ); } return fieldName.equals( lazyPropertyNames[j] ); }
3.888889
private void initOrdinaryPropertyPaths(Mapping mapping) throws MappingException { for ( int i = 0; i < getSubclassPropertyNameClosure().length; i++ ) { propertyMapping.initPropertyPaths( getSubclassPropertyNameClosure()[i], getSubclassPropertyTypeClosure()[i], getSubclassPropertyColumnNameClosure()[i], getSubclassPropertyColumnReaderClosure()[i], getSubclassPropertyColumnReaderTemplateClosure()[i], getSubclassPropertyFormulaTemplateClosure()[i], mapping ); } }
3.888889
/** * Delete an object */ public void delete(Serializable id, Object version, Object object, SessionImplementor session) throws HibernateException { final int span = getTableSpan(); boolean isImpliedOptimisticLocking = !entityMetamodel.isVersioned() && isAllOrDirtyOptLocking(); Object[] loadedState = null; if ( isImpliedOptimisticLocking ) { // need to treat this as if it where optimistic-lock="all" (dirty does *not* make sense); // first we need to locate the "loaded" state // // Note, it potentially could be a proxy, so doAfterTransactionCompletion the location the safe way... final EntityKey key = session.generateEntityKey( id, this ); Object entity = session.getPersistenceContext().getEntity( key ); if ( entity != null ) { EntityEntry entry = session.getPersistenceContext().getEntry( entity ); loadedState = entry.getLoadedState(); } } final String[] deleteStrings; if ( isImpliedOptimisticLocking && loadedState != null ) { // we need to utilize dynamic delete statements deleteStrings = generateSQLDeletStrings( loadedState ); } else { // otherwise, utilize the static delete statements deleteStrings = getSQLDeleteStrings(); } for ( int j = span - 1; j >= 0; j-- ) { delete( id, version, j, object, deleteStrings[j], session, loadedState ); } }
3.555556
private UniqueEntityLoader getAppropriateLoader(LockOptions lockOptions, SessionImplementor session) { if ( queryLoader != null ) { // if the user specified a custom query loader we need to that // regardless of any other consideration return queryLoader; } else if ( isAffectedByEnabledFilters( session ) ) { // because filters affect the rows returned (because they add // restrictions) these need to be next in precedence return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() ); } else if ( session.getLoadQueryInfluencers().getInternalFetchProfile() != null && LockMode.UPGRADE.greaterThan( lockOptions.getLockMode() ) ) { // Next, we consider whether an 'internal' fetch profile has been set. // This indicates a special fetch profile Hibernate needs applied // (for its merge loading process e.g.). return ( UniqueEntityLoader ) getLoaders().get( session.getLoadQueryInfluencers().getInternalFetchProfile() ); } else if ( isAffectedByEnabledFetchProfiles( session ) ) { // If the session has associated influencers we need to adjust the // SQL query used for loading based on those influencers return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() ); } else if ( isAffectedByEntityGraph( session ) ) { return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); } else if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) { return createEntityLoader( lockOptions, session.getLoadQueryInfluencers() ); } else { return ( UniqueEntityLoader ) getLoaders().get( lockOptions.getLockMode() ); } }
3.888889
public String[] toColumns(String alias, String propertyName) throws QueryException { if ( propertyName.equals(CollectionPropertyNames.COLLECTION_ELEMENTS) ) { return memberPersister.getElementColumnNames(alias); } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_INDICES) ) { if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in indices()"); return memberPersister.getIndexColumnNames(alias); } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) { String[] cols = memberPersister.getKeyColumnNames(); return new String[] { "count(" + alias + '.' + cols[0] + ')' }; } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_INDEX) ) { if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in maxIndex()"); String[] cols = memberPersister.getIndexColumnNames(alias); if ( cols.length!=1 ) throw new QueryException("composite collection index in maxIndex()"); return new String[] { "max(" + cols[0] + ')' }; } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_INDEX) ) { if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in minIndex()"); String[] cols = memberPersister.getIndexColumnNames(alias); if ( cols.length!=1 ) throw new QueryException("composite collection index in minIndex()"); return new String[] { "min(" + cols[0] + ')' }; } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) { String[] cols = memberPersister.getElementColumnNames(alias); if ( cols.length!=1 ) throw new QueryException("composite collection element in maxElement()"); return new String[] { "max(" + cols[0] + ')' }; } else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) { String[] cols = memberPersister.getElementColumnNames(alias); if ( cols.length!=1 ) throw new QueryException("composite collection element in minElement()"); return new String[] { "min(" + cols[0] + ')' }; } else { //return memberPersister.toColumns(alias, propertyName); throw new QueryException("illegal syntax near collection: " + propertyName); } }
3.333333
private void bindIndex(final Mappings mappings) { if ( !indexColumn.isImplicit() ) { PropertyHolder valueHolder = PropertyHolderBuilder.buildPropertyHolder( this.collection, StringHelper.qualify( this.collection.getRole(), "key" ), null, null, propertyHolder, mappings ); List list = (List) this.collection; if ( !list.isOneToMany() ) indexColumn.forceNotNull(); indexColumn.setPropertyHolder( valueHolder ); SimpleValueBinder value = new SimpleValueBinder(); value.setColumns( new Ejb3Column[] { indexColumn } ); value.setExplicitType( "integer" ); value.setMappings( mappings ); SimpleValue indexValue = value.make(); indexColumn.linkWithValue( indexValue ); list.setIndex( indexValue ); list.setBaseIndex( indexColumn.getBase() ); if ( list.isOneToMany() && !list.getKey().isNullable() && !list.isInverse() ) { String entityName = ( (OneToMany) list.getElement() ).getReferencedEntityName(); PersistentClass referenced = mappings.getClass( entityName ); IndexBackref ib = new IndexBackref(); ib.setName( '_' + propertyName + "IndexBackref" ); ib.setUpdateable( false ); ib.setSelectable( false ); ib.setCollectionRole( list.getRole() ); ib.setEntityName( list.getOwner().getEntityName() ); ib.setValue( list.getIndex() ); referenced.addProperty( ib ); } } else { Collection coll = this.collection; throw new AnnotationException( "List/array has to be annotated with an @OrderColumn (or @IndexColumn): " + coll.getRole() ); } }
3
/** * Perform {@link org.hibernate.action.spi.Executable#execute()} on each element of the list * * @param list The list of Executable elements to be performed * * @throws HibernateException */ private <E extends Executable & Comparable<?> & Serializable> void executeActions(ExecutableList<E> list) throws HibernateException { // todo : consider ways to improve the double iteration of Executables here: // 1) we explicitly iterate list here to perform Executable#execute() // 2) ExecutableList#getQuerySpaces also iterates the Executables to collect query spaces. try { for ( E e : list ) { try { e.execute(); } finally { beforeTransactionProcesses.register( e.getBeforeTransactionCompletionProcess() ); afterTransactionProcesses.register( e.getAfterTransactionCompletionProcess() ); } } } finally { if ( session.getFactory().getSettings().isQueryCacheEnabled() ) { // Strictly speaking, only a subset of the list may have been processed if a RuntimeException occurs. // We still invalidate all spaces. I don't see this as a big deal - after all, RuntimeExceptions are // unexpected. Set<Serializable> propertySpaces = list.getQuerySpaces(); invalidateSpaces( propertySpaces.toArray( new Serializable[propertySpaces.size()] ) ); } } list.clear(); session.getTransactionCoordinator().getJdbcCoordinator().executeBatch(); }
3.555556
@SuppressWarnings( {"SimplifiableIfStatement"}) private boolean isUnequivocallyNonDirty(Object entity) { if(entity instanceof SelfDirtinessTracker) return ((SelfDirtinessTracker) entity).$$_hibernate_hasDirtyAttributes(); final CustomEntityDirtinessStrategy customEntityDirtinessStrategy = persistenceContext.getSession().getFactory().getCustomEntityDirtinessStrategy(); if ( customEntityDirtinessStrategy.canDirtyCheck( entity, getPersister(), (Session) persistenceContext.getSession() ) ) { return ! customEntityDirtinessStrategy.isDirty( entity, getPersister(), (Session) persistenceContext.getSession() ); } if ( getPersister().hasMutableProperties() ) { return false; } if ( getPersister().getInstrumentationMetadata().isInstrumented() ) { // the entity must be instrumented (otherwise we cant check dirty flag) and the dirty flag is false return ! getPersister().getInstrumentationMetadata().extractInterceptor( entity ).isDirty(); } return false; }
3
public static String expandBatchIdPlaceholder( String sql, Serializable[] ids, String alias, String[] keyColumnNames, Dialect dialect) { if ( keyColumnNames.length == 1 ) { // non-composite return StringHelper.replace( sql, BATCH_ID_PLACEHOLDER, repeat( "?", ids.length, "," ) ); } else { // composite if ( dialect.supportsRowValueConstructorSyntaxInInList() ) { final String tuple = "(" + StringHelper.repeat( "?", keyColumnNames.length, "," ); return StringHelper.replace( sql, BATCH_ID_PLACEHOLDER, repeat( tuple, ids.length, "," ) ); } else { final String keyCheck = joinWithQualifier( keyColumnNames, alias, " and " ); return replace( sql, BATCH_ID_PLACEHOLDER, repeat( keyCheck, ids.length, " or " ) ); } } }
3.888889
/** * Interpret a long as its binary form * * @param longValue The long to interpret to binary * * @return The binary */ public static byte[] fromLong(long longValue) { byte[] bytes = new byte[8]; bytes[0] = (byte) ( longValue >> 56 ); bytes[1] = (byte) ( ( longValue << 8 ) >> 56 ); bytes[2] = (byte) ( ( longValue << 16 ) >> 56 ); bytes[3] = (byte) ( ( longValue << 24 ) >> 56 ); bytes[4] = (byte) ( ( longValue << 32 ) >> 56 ); bytes[5] = (byte) ( ( longValue << 40 ) >> 56 ); bytes[6] = (byte) ( ( longValue << 48 ) >> 56 ); bytes[7] = (byte) ( ( longValue << 56 ) >> 56 ); return bytes; }
4.111111
/** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof OHLC)) { return false; } OHLC that = (OHLC) obj; if (this.open != that.open) { return false; } if (this.close != that.close) { return false; } if (this.high != that.high) { return false; } if (this.low != that.low) { return false; } return true; }
4.666667
public final void caseSList() throws RecognitionException, TokenStreamException { { _loop119: do { if ((_tokenSet_6.member(LA(1)))) { statement(); } else { break _loop119; } } while (true); } }
3.333333
public void write(BufferedReader reader, BufferedWriter writer, Stack parseStateStack) throws IOException { ParseState parseState = (ParseState) parseStateStack.peek(); Object mInterface = /*(MInterface)*/ parseState.newClassifier(name); if (mInterface != null) { parseStateStack.push(new ParseState(mInterface)); StringBuffer sbText = GeneratorJava.getInstance().generateClassifierStart(mInterface); if (sbText != null) { writer.write (sbText.toString()); } // dispose code piece in reader ffCodePiece(reader, null); } else { // not in model, so write the original code ffCodePiece(reader, writer); } }
3.555556
protected final void mHEX_DIGIT(boolean _createToken) throws RecognitionException, CharStreamException, TokenStreamException { int _ttype; Token _token=null; int _begin=text.length(); _ttype = HEX_DIGIT; int _saveIndex; { switch ( LA(1)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { matchRange('0','9'); break; } case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': { matchRange('A','F'); break; } case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': { matchRange('a','f'); break; } default: { throw new NoViableAltForCharException((char)LA(1), getFilename(), getLine(), getColumn()); } } } if ( _createToken && _token==null && _ttype!=Token.SKIP ) { _token = makeToken(_ttype); _token.setText(new String(text.getBuffer(), _begin, text.length()-_begin)); } _returnToken = _token; }
3.555556
/** * The constructor. */ public TabChecklist() { super("tab.checklist"); tableModel = new TableModelChecklist(this); table.setModel(tableModel); Font labelFont = LookAndFeelMgr.getInstance().getStandardFont(); table.setFont(labelFont); table.setIntercellSpacing(new Dimension(0, 1)); table.setShowVerticalLines(false); table.getSelectionModel().addListSelectionListener(this); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); TableColumn checkCol = table.getColumnModel().getColumn(0); TableColumn descCol = table.getColumnModel().getColumn(1); checkCol.setMinWidth(20); checkCol.setMaxWidth(30); checkCol.setWidth(30); descCol.setPreferredWidth(900); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); table.sizeColumnsToFit(-1); JScrollPane sp = new JScrollPane(table); setLayout(new BorderLayout()); add(new JLabel(Translator.localize("tab.checklist.warning")), BorderLayout.NORTH); add(sp, BorderLayout.CENTER); addComponentListener(this); }
3.888889
public void vetoableChange(PropertyChangeEvent pce) { if ("ownedElement".equals(pce.getPropertyName())) { Vector oldOwned = (Vector) pce.getOldValue(); Object eo = pce.getNewValue(); Object me = Model.getFacade().getModelElement(eo); if (oldOwned.contains(eo)) { LOG.debug("model removed " + me); if (Model.getFacade().isANode(me)) { removeNode(me); } if (Model.getFacade().isANodeInstance(me)) { removeNode(me); } if (Model.getFacade().isAComponent(me)) { removeNode(me); } if (Model.getFacade().isAComponentInstance(me)) { removeNode(me); } if (Model.getFacade().isAClass(me)) { removeNode(me); } if (Model.getFacade().isAInterface(me)) { removeNode(me); } if (Model.getFacade().isAObject(me)) { removeNode(me); } if (Model.getFacade().isAAssociation(me)) { removeEdge(me); } if (Model.getFacade().isADependency(me)) { removeEdge(me); } if (Model.getFacade().isALink(me)) { removeEdge(me); } } else { LOG.debug("model added " + me); } } }
4.111111
public List getInEdges(Object port) { Vector res = new Vector(); //wasteful! if (Model.getFacade().isAClassifierRole(port)) { Object cr = port; Collection ends = Model.getFacade().getAssociationEnds(cr); if (ends == null) { return res; // empty Vector } Iterator iter = ends.iterator(); while (iter.hasNext()) { Object aer = iter.next(); res.addElement(Model.getFacade().getAssociation(aer)); } } return res; }
3.888889
/** * Displays visual indications of pending ToDoItems. * Please note that the list of advices (ToDoList) is not the same * as the list of element known by the FigNode (_figs). Therefore, * it is necessary to check if the graphic item exists before drawing * on it. See ClAttributeCompartment for an example. * @param g the graphics device * @see org.argouml.uml.cognitive.critics.ClAttributeCompartment */ public void paintClarifiers(Graphics g) { int iconX = getX(); int iconY = getY() - 10; ToDoList list = Designer.theDesigner().getToDoList(); Vector items = list.elementsForOffender(getOwner()); int size = items.size(); for (int i = 0; i < size; i++) { ToDoItem item = (ToDoItem) items.elementAt(i); Icon icon = item.getClarifier(); if (icon instanceof Clarifier) { ((Clarifier) icon).setFig(this); ((Clarifier) icon).setToDoItem(item); } if (icon != null) { icon.paintIcon(null, g, iconX, iconY); iconX += icon.getIconWidth(); } } items = list.elementsForOffender(this); size = items.size(); for (int i = 0; i < size; i++) { ToDoItem item = (ToDoItem) items.elementAt(i); Icon icon = item.getClarifier(); if (icon instanceof Clarifier) { ((Clarifier) icon).setFig(this); ((Clarifier) icon).setToDoItem(item); } if (icon != null) { icon.paintIcon(null, g, iconX, iconY); iconX += icon.getIconWidth(); } } }
3.333333
public void mouseMoved(MouseEvent me) { //- RedrawManager.lock(); translateMouseEvent(me); Globals.curEditor(this); setUnderMouse(me); Fig currentFig = getCurrentFig(); if (currentFig != null && Globals.getShowFigTips()) { String tip = currentFig.getTipString(me); if (tip != null && (getJComponent() != null)) { JComponent c = getJComponent(); if (c.getToolTipText() == null || !(c.getToolTipText().equals(tip))) { c.setToolTipText(tip); } } } else if (getJComponent() != null && getJComponent().getToolTipText() != null) { getJComponent().setToolTipText(null); //was "" } _selectionManager.mouseMoved(me); _modeManager.mouseMoved(me); //- RedrawManager.unlock(); //- _redrawer.repairDamage(); }
3.222222
public Set getDependencies(Object parent) { if (Model.getFacade().isAClass(parent)) { Set set = new HashSet(); set.add(parent); set.addAll(Model.getFacade().getAttributes(parent)); set.addAll(Model.getFacade().getOperations(parent)); set.addAll(Model.getFacade().getAssociationEnds(parent)); set.addAll(Model.getFacade().getSupplierDependencies(parent)); set.addAll(Model.getFacade().getClientDependencies(parent)); set.addAll(Model.getFacade().getGeneralizations(parent)); set.addAll(Model.getFacade().getSpecializations(parent)); return set; } return null; }
4.666667
@Test public void listenersAreCalledCorrectlyInTheFaceOfFailures() throws Exception { JUnitCore core = new JUnitCore(); final List<Failure> failures = new ArrayList<Failure>(); core.addListener(new RunListener() { @Override public void testRunFinished(Result result) throws Exception { failures.addAll(result.getFailures()); } }); fMax.run(Request.aClass(TwoTests.class), core); assertEquals(1, failures.size()); }
3.222222
private Exception createTimeoutException(Thread thread) { StackTraceElement[] stackTrace = thread.getStackTrace(); final Thread stuckThread = fLookForStuckThread ? getStuckThread(thread) : null; Exception currThreadException = new Exception(String.format( "test timed out after %d %s", fTimeout, fTimeUnit.name().toLowerCase())); if (stackTrace != null) { currThreadException.setStackTrace(stackTrace); thread.interrupt(); } if (stuckThread != null) { Exception stuckThreadException = new Exception ("Appears to be stuck in thread " + stuckThread.getName()); stuckThreadException.setStackTrace(getStackTrace(stuckThread)); return new MultipleFailureException (Arrays.<Throwable>asList(currThreadException, stuckThreadException)); } else { return currThreadException; } }
2.888889
/** * Build the metamodel using the information from the collection of Hibernate * {@link PersistentClass} models as well as the Hibernate {@link org.hibernate.SessionFactory}. * * @param persistentClasses Iterator over the Hibernate (config-time) metamodel * @param mappedSuperclasses All known MappedSuperclasses * @param sessionFactory The Hibernate session factory. * @param ignoreUnsupported ignore unsupported/unknown annotations (like @Any) * * @return The built metamodel */ public static MetamodelImpl buildMetamodel( Iterator<PersistentClass> persistentClasses, Set<MappedSuperclass> mappedSuperclasses, SessionFactoryImplementor sessionFactory, boolean ignoreUnsupported) { MetadataContext context = new MetadataContext( sessionFactory, mappedSuperclasses, ignoreUnsupported ); while ( persistentClasses.hasNext() ) { PersistentClass pc = persistentClasses.next(); locateOrBuildEntityType( pc, context ); } handleUnusedMappedSuperclasses( context ); context.wrapUp(); return new MetamodelImpl( context.getEntityTypeMap(), context.getEmbeddableTypeMap(), context.getMappedSuperclassTypeMap(), context.getEntityTypesByEntityName() ); }
3.111111
@Test public void testExplicitJoining() throws Exception { assertFalse( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); SessionImplementor session = (SessionImplementor) sessionFactory().withOptions().autoJoinTransactions( false ).openSession(); TransactionImplementor transaction = (TransactionImplementor) ( (Session) session ).getTransaction(); assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() ); assertFalse( transaction.isParticipating() ); session.getFlushMode(); // causes a call to TransactionCoordinator#pulse assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() ); assertFalse( transaction.isParticipating() ); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertTrue( transaction.isActive() ); assertFalse( transaction.isParticipating() ); assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() ); session.getFlushMode(); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertTrue( transaction.isActive() ); assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() ); assertFalse( transaction.isParticipating() ); transaction.markForJoin(); transaction.join(); session.getFlushMode(); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); assertTrue( transaction.isActive() ); assertTrue( session.getTransactionCoordinator().isSynchronizationRegistered() ); assertTrue( transaction.isParticipating() ); ( (Session) session ).close(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit(); }
2.777778
@Test public void testImplicitJoining() throws Exception { assertFalse( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); assertTrue( JtaStatusHelper.isActive( TestingJtaPlatformImpl.INSTANCE.getTransactionManager() ) ); SessionImplementor session = (SessionImplementor) sessionFactory().withOptions().autoJoinTransactions( false ).openSession(); session.getFlushMode(); }
3.333333
public void testOneToOnePropertyRefGeneratedIds() { try { Session s = openSession(); s.beginTransaction(); Child c2 = new Child( "c2" ); ChildInfo info = new ChildInfo( "blah blah blah" ); c2.setInfo( info ); info.setOwner( c2 ); s.persist( c2 ); try { s.getTransaction().commit(); fail( "expecting TransientObjectException on flush" ); } catch( TransientObjectException e ) { // expected result log.trace( "handled expected exception : " + e ); s.getTransaction().rollback(); } finally { s.close(); } } finally { cleanupData(); } }
4.111111
@Test public void testBuildEntityCollectionRegionOverridesOnly() { AdvancedCache cache; Properties p = new Properties(); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "LIRS"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "30000"); p.setProperty("hibernate.cache.infinispan.collection.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.collection.eviction.wake_up_interval", "3500"); p.setProperty("hibernate.cache.infinispan.collection.eviction.max_entries", "35000"); InfinispanRegionFactory factory = createRegionFactory(p); try { factory.getCacheManager(); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null); assertNull(factory.getTypeOverrides().get("com.acme.Address")); cache = region.getCache(); Configuration cacheCfg = cache.getCacheConfiguration(); assertEquals(EvictionStrategy.LIRS, cacheCfg.eviction().strategy()); assertEquals(3000, cacheCfg.expiration().wakeUpInterval()); assertEquals(30000, cacheCfg.eviction().maxEntries()); // Max idle value comes from base XML configuration assertEquals(100000, cacheCfg.expiration().maxIdle()); CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null); assertNull(factory.getTypeOverrides().get("com.acme.Person.addresses")); cache = collectionRegion.getCache(); cacheCfg = cache.getCacheConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy()); assertEquals(3500, cacheCfg.expiration().wakeUpInterval()); assertEquals(35000, cacheCfg.eviction().maxEntries()); assertEquals(100000, cacheCfg.expiration().maxIdle()); } finally { factory.stop(); } }
3.222222
@Test public void testBuildEntityRegionPersonPlusEntityOverridesWithoutCfg() { final String person = "com.acme.Person"; Properties p = new Properties(); // Third option, no cache defined for entity and overrides for generic entity data type and entity itself. p.setProperty("hibernate.cache.infinispan.com.acme.Person.eviction.strategy", "LRU"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000"); p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000"); p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache"); p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO"); p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000"); p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000"); InfinispanRegionFactory factory = createRegionFactory(p); try { factory.getCacheManager(); assertNotNull(factory.getTypeOverrides().get(person)); assertFalse(factory.getDefinedConfigurations().contains(person)); EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion(person, p, null); assertNotNull(factory.getTypeOverrides().get(person)); assertTrue(factory.getDefinedConfigurations().contains(person)); AdvancedCache cache = region.getCache(); Configuration cacheCfg = cache.getCacheConfiguration(); assertEquals(EvictionStrategy.LRU, cacheCfg.eviction().strategy()); assertEquals(3000, cacheCfg.expiration().wakeUpInterval()); assertEquals(10000, cacheCfg.eviction().maxEntries()); assertEquals(60000, cacheCfg.expiration().lifespan()); assertEquals(30000, cacheCfg.expiration().maxIdle()); } finally { factory.stop(); } }
3.333333
private InfinispanRegionFactory createRegionFactory(final EmbeddedCacheManager manager, Properties p) { final InfinispanRegionFactory factory = new SingleNodeTestCase.TestInfinispanRegionFactory() { @Override protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup(Settings settings, Properties properties) { return new HibernateTransactionManagerLookup(null, null) { @Override public TransactionManager getTransactionManager() throws Exception { AbstractJtaPlatform jta = new JBossStandAloneJtaPlatform(); jta.injectServices(ServiceRegistryBuilder.buildServiceRegistry()); return jta.getTransactionManager(); } }; } @Override protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { if (manager != null) return manager; else return super.createCacheManager(properties); } }; factory.start(null, p); return factory; }
2.888889
@Test public void testAcceptsUnresolvedPropertyTypesIfATargetEntityIsExplicitlySet() { Session s = openSession(); Transaction tx = s.beginTransaction(); Gene item = new Gene(); s.persist( item ); s.flush(); tx.rollback(); s.close(); }
4.555556
@Test @TestForIssue( jiraKey = "HHH-4685" ) public void testOneToManyEmbeddableBiDirectionalDotNotationInMappedBy() throws Exception { // Section 11.1.26 // The ManyToOne annotation may be used within an embeddable class to specify a relationship from the embeddable // class to an entity class. If the relationship is bidirectional, the non-owning OneToMany entity side must use the // mappedBy element of the OneToMany annotation to specify the relationship field or property of the embeddable field // or property on the owning side of the relationship. The dot (".") notation syntax must be used in the mappedBy // element to indicate the relationship attribute within the embedded attribute. The value of each identifier used // with the dot notation is the name of the respective embedded field or property. Session s; s = openSession(); s.getTransaction().begin(); Employee e = new Employee(); JobInfo job = new JobInfo(); job.setJobDescription( "Sushi Chef" ); ProgramManager pm = new ProgramManager(); Collection<Employee> employees = new ArrayList<Employee>(); employees.add(e); pm.setManages( employees ); job.setPm(pm); e.setJobInfo( job ); s.persist( e ); s.getTransaction().commit(); s.close(); s = openSession(); s.getTransaction().begin(); e = (Employee) s.get( e.getClass(), e.getId() ); assertEquals( "same job in both directions", e.getJobInfo().getJobDescription(), e.getJobInfo().getPm().getManages().iterator().next().getJobInfo().getJobDescription() ); s.getTransaction().commit(); s.close(); }
3.777778
@Test public void testAssociationRelatedAnnotations() throws Exception { XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" ); Field field = Administration.class.getDeclaredField( "defaultBusTrip" ); JPAOverriddenAnnotationReader reader = new JPAOverriddenAnnotationReader( field, context ); assertNotNull( reader.getAnnotation( OneToOne.class ) ); assertNull( reader.getAnnotation( JoinColumns.class ) ); assertNotNull( reader.getAnnotation( PrimaryKeyJoinColumns.class ) ); assertEquals( "pk", reader.getAnnotation( PrimaryKeyJoinColumns.class ).value()[0].name() ); assertEquals( 5, reader.getAnnotation( OneToOne.class ).cascade().length ); assertEquals( FetchType.LAZY, reader.getAnnotation( OneToOne.class ).fetch() ); assertEquals( "test", reader.getAnnotation( OneToOne.class ).mappedBy() ); context = buildContext( "org/hibernate/test/annotations/reflection/metadata-complete.xml" ); field = BusTrip.class.getDeclaredField( "players" ); reader = new JPAOverriddenAnnotationReader( field, context ); assertNotNull( reader.getAnnotation( OneToMany.class ) ); assertNotNull( reader.getAnnotation( JoinColumns.class ) ); assertEquals( 2, reader.getAnnotation( JoinColumns.class ).value().length ); assertEquals( "driver", reader.getAnnotation( JoinColumns.class ).value()[0].name() ); assertNotNull( reader.getAnnotation( MapKey.class ) ); assertEquals( "name", reader.getAnnotation( MapKey.class ).name() ); field = BusTrip.class.getDeclaredField( "roads" ); reader = new JPAOverriddenAnnotationReader( field, context ); assertNotNull( reader.getAnnotation( ManyToMany.class ) ); assertNotNull( reader.getAnnotation( JoinTable.class ) ); assertEquals( "bus_road", reader.getAnnotation( JoinTable.class ).name() ); assertEquals( 2, reader.getAnnotation( JoinTable.class ).joinColumns().length ); assertEquals( 1, reader.getAnnotation( JoinTable.class ).inverseJoinColumns().length ); assertEquals( 2, reader.getAnnotation( JoinTable.class ).uniqueConstraints()[0].columnNames().length ); assertNotNull( reader.getAnnotation( OrderBy.class ) ); assertEquals( "maxSpeed", reader.getAnnotation( OrderBy.class ).value() ); }
2.666667
@Test @TestForIssue(jiraKey = "HHH-4699") @SkipForDialect(value = { Oracle8iDialect.class, AbstractHANADialect.class }, jiraKey = "HHH-8516", comment = "HHH-4699 was specifically for using a CHAR, but Oracle/HANA do not handle the 2nd query correctly without VARCHAR. ") public void testTrimmedEnumChar() throws SQLException { // use native SQL to insert, forcing whitespace to occur final Session s = openSession(); final Connection connection = ((SessionImplementor)s).connection(); final Statement statement = connection.createStatement(); statement.execute("insert into EntityEnum (id, trimmed) values(1, '" + Trimmed.A.name() + "')"); statement.execute("insert into EntityEnum (id, trimmed) values(2, '" + Trimmed.B.name() + "')"); s.getTransaction().begin(); // ensure EnumType can do #fromName with the trimming List<EntityEnum> resultList = s.createQuery("select e from EntityEnum e").list(); assertEquals( resultList.size(), 2 ); assertEquals( resultList.get(0).getTrimmed(), Trimmed.A ); assertEquals( resultList.get(1).getTrimmed(), Trimmed.B ); // ensure querying works final Query query = s.createQuery("select e from EntityEnum e where e.trimmed=?"); query.setParameter( 0, Trimmed.A ); resultList = query.list(); assertEquals( resultList.size(), 1 ); assertEquals( resultList.get(0).getTrimmed(), Trimmed.A ); statement.execute( "delete from EntityEnum" ); s.getTransaction().commit(); s.close(); }
3.666667
@Test public void testWithEJB3NamingStrategy() throws Exception { SessionFactory sf = null; try { AnnotationConfiguration config = new AnnotationConfiguration(); config.setNamingStrategy(EJB3NamingStrategy.INSTANCE); config.addAnnotatedClass(A.class); config.addAnnotatedClass(AddressEntry.class); sf = config.buildSessionFactory( serviceRegistry ); Mappings mappings = config.createMappings(); boolean foundIt = false; for ( Iterator iter = mappings.iterateTables(); iter.hasNext(); ) { Table table = (Table) iter.next(); log.info("testWithEJB3NamingStrategy table = " + table.getName()); if ( table.getName().equalsIgnoreCase("A_ADDRESS")) { foundIt = true; } // make sure we use A_ADDRESS instead of AEC_address assertFalse("got table name mapped to: AEC_address (should be A_ADDRESS) which violates JPA-2 spec section 11.1.8 ([OWNING_ENTITY_NAME]_[COLLECTION_ATTRIBUTE_NAME])",table.getName().equalsIgnoreCase("AEC_address")); } assertTrue("table not mapped to A_ADDRESS which violates JPA-2 spec section 11.1.8",foundIt); } catch( Exception e ) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); log.debug(writer.toString()); fail(e.getMessage()); } finally { if( sf != null ){ sf.close(); } } }
3
@Test @SkipForDialects( { @SkipForDialect( value = { HSQLDialect.class }, comment = "The used join conditions does not work in HSQLDB. See HHH-4497." ), @SkipForDialect( value = { SQLServer2005Dialect.class } ), @SkipForDialect( value = { Oracle8iDialect.class }, comment = "Oracle/DB2 do not support 'substring' function" ), @SkipForDialect( value = { DB2Dialect.class }, comment = "Oracle/DB2 do not support 'substring' function" ) } ) public void testManyToOneFromNonPkToNonPk() throws Exception { // also tests usage of the stand-alone @JoinFormula annotation (i.e. not wrapped within @JoinColumnsOrFormulas) Session s = openSession(); Transaction tx = s.beginTransaction(); Product kit = new Product(); kit.id = 1; kit.productIdnf = "KIT"; kit.description = "Kit"; s.persist(kit); Product kitkat = new Product(); kitkat.id = 2; kitkat.productIdnf = "KIT_KAT"; kitkat.description = "Chocolate"; s.persist(kitkat); s.flush(); s.clear(); kit = (Product) s.get(Product.class, 1); kitkat = (Product) s.get(Product.class, 2); System.out.println(kitkat.description); assertNotNull(kitkat); assertEquals(kit, kitkat.getProductFamily()); assertEquals(kit.productIdnf, kitkat.getProductFamily().productIdnf); assertEquals("KIT_KAT", kitkat.productIdnf.trim()); assertEquals("Chocolate", kitkat.description.trim()); tx.rollback(); s.close(); }
3.777778
public CollectionListeners( SessionFactory sf) { preCollectionRecreateListener = new PreCollectionRecreateListener( this ); initializeCollectionListener = new InitializeCollectionListener( this ); preCollectionRemoveListener = new PreCollectionRemoveListener( this ); preCollectionUpdateListener = new PreCollectionUpdateListener( this ); postCollectionRecreateListener = new PostCollectionRecreateListener( this ); postCollectionRemoveListener = new PostCollectionRemoveListener( this ); postCollectionUpdateListener = new PostCollectionUpdateListener( this ); EventListenerRegistry registry = ( (SessionFactoryImplementor) sf ).getServiceRegistry().getService( EventListenerRegistry.class ); registry.setListeners( EventType.INIT_COLLECTION, initializeCollectionListener ); registry.setListeners( EventType.PRE_COLLECTION_RECREATE, preCollectionRecreateListener ); registry.setListeners( EventType.POST_COLLECTION_RECREATE, postCollectionRecreateListener ); registry.setListeners( EventType.PRE_COLLECTION_REMOVE, preCollectionRemoveListener ); registry.setListeners( EventType.POST_COLLECTION_REMOVE, postCollectionRemoveListener ); registry.setListeners( EventType.PRE_COLLECTION_UPDATE, preCollectionUpdateListener ); registry.setListeners( EventType.POST_COLLECTION_UPDATE, postCollectionUpdateListener ); }
4.111111
@Test public void testUpdateParentOneChildDiffCollectionDiffChild() { CollectionListeners listeners = new CollectionListeners( sessionFactory() ); ParentWithCollection parent = createParentWithOneChild( "parent", "child" ); Child oldChild = ( Child ) parent.getChildren().iterator().next(); listeners.clear(); assertEquals( 1, parent.getChildren().size() ); Session s = openSession(); Transaction tx = s.beginTransaction(); parent = ( ParentWithCollection ) s.get( parent.getClass(), parent.getId() ); if ( oldChild instanceof Entity ) { oldChild = ( Child ) s.get( oldChild.getClass(), ( ( Entity ) oldChild).getId() ); } Collection oldCollection = parent.getChildren(); parent.newChildren( createCollection() ); Child newChild = parent.addChild( "new1" ); tx.commit(); s.close(); int index = 0; if ( ( (PersistentCollection) oldCollection ).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), parent, oldCollection, index++ ); } if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { ChildWithBidirectionalManyToMany oldChildWithManyToMany = ( ChildWithBidirectionalManyToMany ) oldChild; if ( ( ( PersistentCollection ) oldChildWithManyToMany.getParents() ).wasInitialized() ) { checkResult( listeners, listeners.getInitializeCollectionListener(), oldChildWithManyToMany, index++ ); } } checkResult( listeners, listeners.getPreCollectionRemoveListener(), parent, oldCollection, index++ ); checkResult( listeners, listeners.getPostCollectionRemoveListener(), parent, oldCollection, index++ ); if ( oldChild instanceof ChildWithBidirectionalManyToMany ) { checkResult( listeners, listeners.getPreCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); checkResult( listeners, listeners.getPostCollectionUpdateListener(), ( ChildWithBidirectionalManyToMany ) oldChild, index++ ); checkResult( listeners, listeners.getPreCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), ( ChildWithBidirectionalManyToMany ) newChild, index++ ); } checkResult( listeners, listeners.getPreCollectionRecreateListener(), parent, index++ ); checkResult( listeners, listeners.getPostCollectionRecreateListener(), parent, index++ ); checkNumberOfResults( listeners, index ); }
2.444444
public int hashCode() { final int PRIME = 31; int result = 1; if ( name != null ) { result += name.hashCode(); } result *= PRIME; if ( num != null ) { result += num.hashCode(); } return result; }
4.333333
@Test public void testCascadeBasedBuild() { EntityPersister ep = (EntityPersister) sessionFactory().getClassMetadata(Message.class); CascadeStyleLoadPlanBuildingAssociationVisitationStrategy strategy = new CascadeStyleLoadPlanBuildingAssociationVisitationStrategy( CascadingActions.MERGE, sessionFactory(), LoadQueryInfluencers.NONE, LockMode.NONE ); LoadPlan plan = MetamodelDrivenLoadPlanBuilder.buildRootEntityLoadPlan( strategy, ep ); assertFalse( plan.hasAnyScalarReturns() ); assertEquals( 1, plan.getReturns().size() ); Return rtn = plan.getReturns().get( 0 ); EntityReturn entityReturn = ExtraAssertions.assertTyping( EntityReturn.class, rtn ); assertNotNull( entityReturn.getFetches() ); assertEquals( 1, entityReturn.getFetches().length ); Fetch fetch = entityReturn.getFetches()[0]; EntityFetch entityFetch = ExtraAssertions.assertTyping( EntityFetch.class, fetch ); assertNotNull( entityFetch.getFetches() ); assertEquals( 0, entityFetch.getFetches().length ); LoadPlanTreePrinter.INSTANCE.logTree( plan, new AliasResolutionContextImpl( sessionFactory() ) ); }
3.111111
public LoadPlan buildLoadPlan( SessionFactoryImplementor sf, OuterJoinLoadable persister, LoadQueryInfluencers influencers, LockMode lockMode) { FetchStyleLoadPlanBuildingAssociationVisitationStrategy strategy = new FetchStyleLoadPlanBuildingAssociationVisitationStrategy( sf, influencers, lockMode ); return MetamodelDrivenLoadPlanBuilder.buildRootEntityLoadPlan( strategy, persister ); }
3.333333
private void compare(JoinWalker walker, LoadQueryDetails details) { System.out.println( "------ SQL -----------------------------------------------------------------" ); System.out.println( "WALKER : " + walker.getSQLString() ); System.out.println( "LOAD-PLAN : " + details.getSqlStatement() ); System.out.println( "----------------------------------------------------------------------------" ); System.out.println( ); System.out.println( "------ SUFFIXES ------------------------------------------------------------" ); System.out.println( "WALKER : " + StringHelper.join( ", ", walker.getSuffixes() ) + " : " + StringHelper.join( ", ", walker.getCollectionSuffixes() ) ); System.out.println( "----------------------------------------------------------------------------" ); System.out.println( ); }
4.888889
@Test public void testExceptionHandling() { Session session = openSession(); SessionImplementor sessionImpl = (SessionImplementor) session; boolean caught = false; try { PreparedStatement ps = sessionImpl.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer() .prepareStatement( "select count(*) from NON_EXISTENT" ); sessionImpl.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().execute( ps ); } catch ( JDBCException ok ) { caught = true; } finally { session.close(); } assertTrue( "The connection did not throw a JDBCException as expected", caught ); }
3.888889
private void doBasicPluralAttributeBinding(PluralAttributeSource source, AbstractPluralAttributeBinding binding) { binding.setFetchTiming( source.getFetchTiming() ); binding.setFetchStyle( source.getFetchStyle() ); binding.setCascadeStyles( source.getCascadeStyles() ); binding.setCaching( source.getCaching() ); binding.getHibernateTypeDescriptor().setJavaTypeName( source.getPluralAttributeNature().reportedJavaType().getName() ); binding.getHibernateTypeDescriptor().setExplicitTypeName( source.getTypeInformation().getName() ); binding.getHibernateTypeDescriptor().getTypeParameters().putAll( source.getTypeInformation().getParameters() ); if ( StringHelper.isNotEmpty( source.getCustomPersisterClassName() ) ) { binding.setCollectionPersisterClass( currentBindingContext.<CollectionPersister>locateClassByName( source.getCustomPersisterClassName() ) ); } if ( source.getCustomPersisterClassName() != null ) { binding.setCollectionPersisterClass( metadata.<CollectionPersister>locateClassByName( source.getCustomPersisterClassName() ) ); } binding.setCustomLoaderName( source.getCustomLoaderName() ); binding.setCustomSqlInsert( source.getCustomSqlInsert() ); binding.setCustomSqlUpdate( source.getCustomSqlUpdate() ); binding.setCustomSqlDelete( source.getCustomSqlDelete() ); binding.setCustomSqlDeleteAll( source.getCustomSqlDeleteAll() ); binding.setMetaAttributeContext( buildMetaAttributeContext( source.metaAttributes(), binding.getContainer().getMetaAttributeContext() ) ); doBasicAttributeBinding( source, binding ); }
2.777778
private void pushHibernateTypeInformationDownIfNeeded( HibernateTypeDescriptor hibernateTypeDescriptor, Value value, Type resolvedHibernateType) { if ( resolvedHibernateType == null ) { return; } if ( hibernateTypeDescriptor.getResolvedTypeMapping() == null ) { hibernateTypeDescriptor.setResolvedTypeMapping( resolvedHibernateType ); } // java type information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ( hibernateTypeDescriptor.getJavaTypeName() == null ) { hibernateTypeDescriptor.setJavaTypeName( resolvedHibernateType.getReturnedClass().getName() ); } // todo : this can be made a lot smarter, but for now this will suffice. currently we only handle single value bindings if ( SimpleValue.class.isInstance( value ) ) { SimpleValue simpleValue = ( SimpleValue ) value; if ( simpleValue.getDatatype() == null ) { simpleValue.setDatatype( new Datatype( resolvedHibernateType.sqlTypes( metadata )[0], resolvedHibernateType.getName(), resolvedHibernateType.getReturnedClass() ) ); } } }
3.444444
public static Iterable<AttributeDefinition> getCompositeCollectionIndexSubAttributes(CompositeCollectionElementDefinition compositionElementDefinition){ final QueryableCollection collectionPersister = (QueryableCollection) compositionElementDefinition.getCollectionDefinition().getCollectionPersister(); return getSingularSubAttributes( compositionElementDefinition.getSource(), (OuterJoinLoadable) collectionPersister.getOwnerEntityPersister(), (CompositeType) collectionPersister.getIndexType(), collectionPersister.getTableName(), collectionPersister.getIndexColumnNames() ); }
3
/** * As per sections 12.2.3.23.9, 12.2.4.8.9 and 12.2.5.3.6 of the JPA 2.0 * specification, the element-collection subelement completely overrides the * mapping for the specified field or property. Thus, any methods which * might in some contexts merge with annotations must not do so in this * context. */ private void getElementCollection(List<Annotation> annotationList, XMLContext.Default defaults) { for ( Element element : elementsForProperty ) { if ( "element-collection".equals( element.getName() ) ) { AnnotationDescriptor ad = new AnnotationDescriptor( ElementCollection.class ); addTargetClass( element, ad, "target-class", defaults ); getFetchType( ad, element ); getOrderBy( annotationList, element ); getOrderColumn( annotationList, element ); getMapKey( annotationList, element ); getMapKeyClass( annotationList, element, defaults ); getMapKeyTemporal( annotationList, element ); getMapKeyEnumerated( annotationList, element ); getMapKeyColumn( annotationList, element ); buildMapKeyJoinColumns( annotationList, element ); Annotation annotation = getColumn( element.element( "column" ), false, element ); addIfNotNull( annotationList, annotation ); getTemporal( annotationList, element ); getEnumerated( annotationList, element ); getLob( annotationList, element ); //Both map-key-attribute-overrides and attribute-overrides //translate into AttributeOverride annotations, which need //need to be wrapped in the same AttributeOverrides annotation. List<AttributeOverride> attributes = new ArrayList<AttributeOverride>(); attributes.addAll( buildAttributeOverrides( element, "map-key-attribute-override" ) ); attributes.addAll( buildAttributeOverrides( element, "attribute-override" ) ); annotation = mergeAttributeOverrides( defaults, attributes, false ); addIfNotNull( annotationList, annotation ); annotation = getAssociationOverrides( element, defaults, false ); addIfNotNull( annotationList, annotation ); getCollectionTable( annotationList, element, defaults ); annotationList.add( AnnotationFactory.create( ad ) ); getAccessType( annotationList, element ); } } }
2.888889
@Override public void release() { if ( reader == null ) { return; } try { reader.close(); } catch (IOException ignore) { } }
4.777778
@Override protected XMLEvent internalNextEvent() throws XMLStreamException { //If there is an iterator to read from reset was called, use the iterator //until it runs out of events. if (this.bufferReader != null) { final XMLEvent event = this.bufferReader.next(); //If nothing left in the iterator, remove the reference and fall through to direct reading if (!this.bufferReader.hasNext()) { this.bufferReader = null; } return event; } //Get the next event from the underlying reader final XMLEvent event = this.getParent().nextEvent(); //if buffering add the event if (this.eventLimit != 0) { this.eventBuffer.offer(event); //If limited buffer size and buffer is too big trim the buffer. if (this.eventLimit > 0 && this.eventBuffer.size() > this.eventLimit) { this.eventBuffer.poll(); } } return event; }
4.555556
@Override public final String getElementText() throws XMLStreamException { XMLEvent event = this.previousEvent; if (event == null) { throw new XMLStreamException("Must be on START_ELEMENT to read next text, element was null"); } if (!event.isStartElement()) { throw new XMLStreamException("Must be on START_ELEMENT to read next text", event.getLocation()); } final StringBuilder text = new StringBuilder(); while (!event.isEndDocument()) { switch (event.getEventType()) { case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.SPACE: case XMLStreamConstants.CDATA: { final Characters characters = event.asCharacters(); text.append(characters.getData()); break; } case XMLStreamConstants.ENTITY_REFERENCE: { final EntityReference entityReference = (EntityReference)event; final EntityDeclaration declaration = entityReference.getDeclaration(); text.append(declaration.getReplacementText()); break; } case XMLStreamConstants.COMMENT: case XMLStreamConstants.PROCESSING_INSTRUCTION: { //Ignore break; } default: { throw new XMLStreamException("Unexpected event type '" + XMLStreamConstantsUtils.getEventName(event.getEventType()) + "' encountered. Found event: " + event, event.getLocation()); } } event = this.nextEvent(); } return text.toString(); }
4.111111
public Point getClosestPoint(Point anotherPt) { Rectangle r = getBounds(); int[] xs = {r.x + r.width / 2, r.x + r.width, r.x + r.width / 2, r.x, r.x + r.width / 2, }; int[] ys = {r.y, r.y + r.height / 2, r.y + r.height, r.y + r.height / 2, r.y, }; Point p = Geometry.ptClosestTo( xs, ys, 5, anotherPt); return p; }
4.333333
protected void modelChanged(PropertyChangeEvent mee) { super.modelChanged(mee); final Object trCollection = mee.getNewValue(); final String eName = mee.getPropertyName(); final Object owner = getOwner(); /* * A Concurrent region cannot have incoming or outgoing transitions so * incoming or outgoing transitions are redirected to its concurrent * composite state container. */ SwingUtilities.invokeLater(new Runnable() { public void run() { Object tr = null; // TODO: Is this comparison correct? // Where is the string created? if (eName == "incoming") { if (!((Collection) trCollection).isEmpty()) { tr = ((Collection) trCollection).iterator().next(); } if (tr != null && Model.getFacade().isATransition(tr)) { Model.getCommonBehaviorHelper().setTarget(tr, Model.getFacade().getContainer(owner)); } } else if (eName == "outgoing") { if (!((Collection) trCollection).isEmpty()) { tr = ((Collection) trCollection).iterator().next(); } if (tr != null && Model.getFacade().isATransition(tr)) { Model.getStateMachinesHelper().setSource(tr, Model.getFacade().getContainer(owner)); } } } }); }
3
public void setEnclosingFig(Fig encloser) { if (getOwner() != null) { Object nod = getOwner(); if (encloser != null) { Object comp = encloser.getOwner(); if (Model.getFacade().isAComponentInstance(comp)) { if (Model.getFacade().getComponentInstance(nod) != comp) { Model.getCommonBehaviorHelper() .setComponentInstance(nod, comp); super.setEnclosingFig(encloser); } } else if (Model.getFacade().isANode(comp)) { super.setEnclosingFig(encloser); } } else if (encloser == null) { if (isVisible() // If we are not visible most likely // we're being deleted. // TODO: This indicates a more fundamental problem that should // be investigated - tfm - 20061230 && Model.getFacade().getComponentInstance(nod) != null) { Model.getCommonBehaviorHelper() .setComponentInstance(nod, null); super.setEnclosingFig(encloser); } } } if (getLayer() != null) { // elementOrdering(figures); Collection contents = new ArrayList(getLayer().getContents()); Iterator it = contents.iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof FigEdgeModelElement) { FigEdgeModelElement figedge = (FigEdgeModelElement) o; figedge.getLayer().bringToFront(figedge); } } } }
2.888889
protected Object[] getUmlActions() { Object[] actions = { getActionPackage(), getActionClass(), null, getAssociationActions(), getAggregationActions(), getCompositionActions(), getActionAssociationEnd(), getActionGeneralization(), null, getActionInterface(), getActionRealization(), null, getDependencyActions(), null, getActionAttribute(), getActionOperation(), getActionAssociationClass(), null, getDataTypeActions(), }; return actions; }
3.222222
public void buildModel() { if (getTarget() != null) { Object target = getTarget(); Object kind = Model.getFacade().getAggregation(target); if (kind == null || kind.equals( Model.getAggregationKind().getNone())) { setSelected(ActionSetAssociationEndAggregation.NONE_COMMAND); } else { if (kind.equals( Model.getAggregationKind().getAggregate())) { setSelected(ActionSetAssociationEndAggregation .AGGREGATE_COMMAND); } else { if (kind.equals( Model.getAggregationKind() .getComposite())) { setSelected(ActionSetAssociationEndAggregation .COMPOSITE_COMMAND); } else { setSelected(ActionSetAssociationEndAggregation .NONE_COMMAND); } } } } }
2.555556
/** * Construct a property panel for Node Instance elements. */ public PropPanelNodeInstance() { super("Node Instance", lookupIcon("NodeInstance"), ConfigLoader.getTabPropsOrientation()); addField(Translator.localize("label.name"), getNameTextField()); addField(Translator.localize("label.namespace"), getNamespaceSelector()); addSeparator(); addField(Translator.localize("label.stimili-sent"), getStimuliSenderScroll()); addField(Translator.localize("label.stimili-received"), getStimuliReceiverScroll()); JList resList = new UMLLinkedList(new UMLContainerResidentListModel()); addField(Translator.localize("label.residents"), new JScrollPane(resList)); addSeparator(); AbstractActionAddModelElement a = new ActionAddInstanceClassifier(Model.getMetaTypes().getNode()); JScrollPane classifierScroll = new JScrollPane(new UMLMutableLinkedList( new UMLInstanceClassifierListModel(), a, null, null, true)); addField(Translator.localize("label.classifiers"), classifierScroll); addAction(new ActionNavigateContainerElement()); addAction(new ActionNewStereotype()); addAction(getDeleteAction()); }
2.666667
@Test public void shouldReturnOnlyTheNamedDataPoints() throws Throwable { SpecificDataPointsSupplier supplier = new SpecificDataPointsSupplier(new TestClass(TestClassWithNamedDataPoints.class)); List<PotentialAssignment> assignments = supplier.getValueSources(signature("methodWantingAllNamedStrings")); List<String> assignedStrings = getStringValuesFromAssignments(assignments); assertEquals(4, assignedStrings.size()); assertThat(assignedStrings, hasItems("named field", "named method", "named single value", "named single method value")); }
3.666667
@Test public void throwTimeoutExceptionOnSecondCallAlthoughFirstCallThrowsException() throws Throwable { thrown.expectMessage("test timed out after 100 milliseconds"); try { evaluateWithException(new RuntimeException()); } catch (Throwable expected) { } evaluateWithWaitDuration(TIMEOUT + 50); }
4.333333
@Test public void stackTraceContainsRealCauseOfTimeout() throws Throwable { StuckStatement stuck = new StuckStatement(); FailOnTimeout stuckTimeout = new FailOnTimeout(stuck, TIMEOUT); try { stuckTimeout.evaluate(); // We must not get here, we expect a timeout exception fail("Expected timeout exception"); } catch (Exception timeoutException) { StackTraceElement[] stackTrace = timeoutException.getStackTrace(); boolean stackTraceContainsTheRealCauseOfTheTimeout = false; boolean stackTraceContainsOtherThanTheRealCauseOfTheTimeout = false; for (StackTraceElement element : stackTrace) { String methodName = element.getMethodName(); if ("theRealCauseOfTheTimeout".equals(methodName)) { stackTraceContainsTheRealCauseOfTheTimeout = true; } if ("notTheRealCauseOfTheTimeout".equals(methodName)) { stackTraceContainsOtherThanTheRealCauseOfTheTimeout = true; } } assertTrue( "Stack trace does not contain the real cause of the timeout", stackTraceContainsTheRealCauseOfTheTimeout); assertFalse( "Stack trace contains other than the real cause of the timeout, which can be very misleading", stackTraceContainsOtherThanTheRealCauseOfTheTimeout); } }
3.555556
@Test public void testQueryCacheModes() { EntityManager em = getOrCreateEntityManager(); Query jpaQuery = em.createQuery( "from SimpleEntity" ); AbstractQueryImpl hibQuery = (AbstractQueryImpl) ( (HibernateQuery) jpaQuery ).getHibernateQuery(); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE ); assertEquals( CacheStoreMode.USE, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.NORMAL, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS ); assertEquals( CacheStoreMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.GET, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH ); assertEquals( CacheStoreMode.REFRESH, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.REFRESH, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.REFRESH, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.IGNORE, hibQuery.getCacheMode() ); jpaQuery.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE ); assertEquals( CacheRetrieveMode.BYPASS, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) ); assertEquals( CacheStoreMode.USE, jpaQuery.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) ); assertEquals( CacheMode.PUT, hibQuery.getCacheMode() ); }
2.666667
@Test public void testRestrictedCorrelationNoExplicitSelection() { CriteriaBuilder builder = entityManagerFactory().getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery<Order> criteria = builder.createQuery( Order.class ); Root<Order> orderRoot = criteria.from( Order.class ); criteria.select( orderRoot ); // create correlated subquery Subquery<Customer> customerSubquery = criteria.subquery( Customer.class ); Root<Order> orderRootCorrelation = customerSubquery.correlate( orderRoot ); Join<Order, Customer> orderCustomerJoin = orderRootCorrelation.join( "customer" ); customerSubquery.where( builder.like( orderCustomerJoin.<String>get( "name" ), "%Caruso" ) ); criteria.where( builder.exists( customerSubquery ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); }
2.888889
/** * Get the value mapped to this key, or null if no value is mapped to this key. * * @param key The cache key * * @return The cached data */ public final Object get(Object key) { try { final Element element = getCache().get( key ); if ( element == null ) { return null; } else { return element.getObjectValue(); } } catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); return null; } else { throw new CacheException( e ); } } }
4.222222
@Test public void testModFlagProperties() { assertEquals( TestTools.makeSet( "comp1_MOD" ), TestTools.extractModProperties( getCfg().getClassMapping( "org.hibernate.envers.test.entities.components.ComponentTestEntity_AUD" ) ) ); }
4.333333
@Test public void testHistoryOfEdIng2() { SetOwnedEntity ed1 = getEntityManager().find( SetOwnedEntity.class, ed1_id ); SetOwnedEntity ed2 = getEntityManager().find( SetOwnedEntity.class, ed2_id ); SetOwningEntity rev1 = getAuditReader().find( SetOwningEntity.class, ing2_id, 1 ); SetOwningEntity rev2 = getAuditReader().find( SetOwningEntity.class, ing2_id, 2 ); SetOwningEntity rev3 = getAuditReader().find( SetOwningEntity.class, ing2_id, 3 ); SetOwningEntity rev4 = getAuditReader().find( SetOwningEntity.class, ing2_id, 4 ); SetOwningEntity rev5 = getAuditReader().find( SetOwningEntity.class, ing2_id, 5 ); assert rev1.getReferences().equals( Collections.EMPTY_SET ); assert rev2.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); assert rev3.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); assert rev4.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); assert rev5.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); }
3.666667
@Test public void testTernaryMap() { final TernaryMapEntity ternaryMap = new TernaryMapEntity(); ternaryMap.setId( ternaryMapId ); ternaryMap.getMap().put( intEntity1, stringEntity1 ); ternaryMap.getMap().put( new IntTestPrivSeqEntity( 2, intEntity2.getId() ) , new StrTestPrivSeqEntity( "Value 2", stringEntity2.getId() ) ); TernaryMapEntity entity = getAuditReader().find( TernaryMapEntity.class, ternaryMapId, 15 ); Assert.assertEquals( ternaryMap.getMap(), entity.getMap() ); ternaryMap.getMap().clear(); ternaryMap.getMap().put( intEntity1, stringEntity1 ); ternaryMap.getMap().put( intEntity2, stringEntity2 ); entity = getAuditReader().find( TernaryMapEntity.class, ternaryMapId, 16 ); Assert.assertEquals( ternaryMap.getMap(), entity.getMap() ); List queryResult = getAuditReader().createQuery().forRevisionsOfEntity( TernaryMapEntity.class, false, true ) .add( AuditEntity.id().eq( ternaryMapId ) ) .add( AuditEntity.revisionType().eq( RevisionType.DEL ) ) .getResultList(); Object[] objArray = (Object[]) queryResult.get( 0 ); Assert.assertEquals( 17, getRevisionNumber( objArray[1] ) ); entity = (TernaryMapEntity) objArray[0]; Assert.assertEquals( ternaryMap.getMap(), entity.getMap() ); }
2.777778
@Test @Priority(10) public void initData() { EntityManager em = getEntityManager(); // Revision 1 em.getTransaction().begin(); country = Country.of( 123, "Germany" ); em.persist( country ); em.getTransaction().commit(); }
4.555556
@Override public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( !super.equals( obj ) ) { return false; } if ( getClass() != obj.getClass() ) { return false; } VersionsJoinTableRangeTestAlternateEntity other = (VersionsJoinTableRangeTestAlternateEntity) obj; if ( alternateValue == null ) { if ( other.alternateValue != null ) { return false; } } else if ( !alternateValue.equals( other.alternateValue ) ) { return false; } return true; }
4.222222
private Element createMiddleEntityXml(String auditMiddleTableName, String auditMiddleEntityName, String where) { final String schema = mainGenerator.getSchema( propertyAuditingData.getJoinTable().schema(), propertyValue.getCollectionTable() ); final String catalog = mainGenerator.getCatalog( propertyAuditingData.getJoinTable().catalog(), propertyValue.getCollectionTable() ); final Element middleEntityXml = MetadataTools.createEntity( xmlMappingData.newAdditionalMapping(), new AuditTableData( auditMiddleEntityName, auditMiddleTableName, schema, catalog ), null, null ); final Element middleEntityXmlId = middleEntityXml.addElement( "composite-id" ); // If there is a where clause on the relation, adding it to the middle entity. if ( where != null ) { middleEntityXml.addAttribute( "where", where ); } middleEntityXmlId.addAttribute( "name", mainGenerator.getVerEntCfg().getOriginalIdPropName() ); // Adding the revision number as a foreign key to the revision info entity to the composite id of the // middle table. mainGenerator.addRevisionInfoRelation( middleEntityXmlId ); // Adding the revision type property to the entity xml. mainGenerator.addRevisionType( isEmbeddableElementType() ? middleEntityXmlId : middleEntityXml, middleEntityXml ); // All other properties should also be part of the primary key of the middle entity. return middleEntityXmlId; }
3.111111
private void addTransactionFactories(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( TransactionFactory.class, JdbcTransactionFactory.SHORT_NAME, JdbcTransactionFactory.class ); strategySelector.registerStrategyImplementor( TransactionFactory.class, "org.hibernate.transaction.JDBCTransactionFactory", JdbcTransactionFactory.class ); strategySelector.registerStrategyImplementor( TransactionFactory.class, JtaTransactionFactory.SHORT_NAME, JtaTransactionFactory.class ); strategySelector.registerStrategyImplementor( TransactionFactory.class, "org.hibernate.transaction.JTATransactionFactory", JtaTransactionFactory.class ); strategySelector.registerStrategyImplementor( TransactionFactory.class, CMTTransactionFactory.SHORT_NAME, CMTTransactionFactory.class ); strategySelector.registerStrategyImplementor( TransactionFactory.class, "org.hibernate.transaction.CMTTransactionFactory", CMTTransactionFactory.class ); }
3.888889
@Override public String call() throws Exception { try { if (isTrace) log.tracef("[%s] Wait for all executions paths to be ready to perform calls", title(warmup)); barrier.await(); long start = System.nanoTime(); int runs = 0; if (isTrace) log.tracef("[%s] Start time: %d", title(warmup), start); // while (USE_TIME && PutFromLoadStressTestCase.this.run.get()) { // if (runs % 100000 == 0) // log.infof("[%s] Query run # %d", title(warmup), runs); // //// Customer customer = query(); //// deleteCached(customer); queryItems(); // deleteCachedItems(); // // runs++; // } long end = System.nanoTime(); long duration = end - start; if (isTrace) log.tracef("[%s] End time: %d, duration: %d, runs: %d", title(warmup), start, duration, runs); return opsPerMS(duration, runs); } finally { if (isTrace) log.tracef("[%s] Wait for all execution paths to finish", title(warmup)); barrier.await(); } }
3.666667
private void registeredPutWithInterveningRemovalTest( final boolean transactional, final boolean removeRegion) throws Exception { withCacheManager(new CacheManagerCallable( TestCacheManagerFactory.createCacheManager(false)) { @Override public void call() { PutFromLoadValidator testee = new PutFromLoadValidator(cm, transactional ? tm : null, PutFromLoadValidator.NAKED_PUT_INVALIDATION_PERIOD); try { if (transactional) { tm.begin(); } testee.registerPendingPut(KEY1); if (removeRegion) { testee.invalidateRegion(); } else { testee.invalidateKey(KEY1); } boolean lockable = testee.acquirePutFromLoadLock(KEY1); try { assertFalse(lockable); } finally { if (lockable) { testee.releasePutFromLoadLock(KEY1); } } } catch (Exception e) { throw new RuntimeException(e); } } }); }
2.777778
@Override protected void prepareBootstrapRegistryBuilder(BootstrapServiceRegistryBuilder builder) { super.prepareBootstrapRegistryBuilder( builder ); builder.with( new Integrator() { @Override public void integrate( Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { integrate(serviceRegistry); } @Override public void integrate( MetadataImplementor metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry ) { integrate(serviceRegistry); } private void integrate( SessionFactoryServiceRegistry serviceRegistry ) { serviceRegistry.getService( EventListenerRegistry.class ).prependListeners(EventType.LOAD, new CustomLoadListener()); } @Override public void disintegrate( SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { } } ); }
3.444444
@Test @TestForIssue( jiraKey = "HHH-2277") public void testLoadEntityWithEagerFetchingToKeyManyToOneReferenceBackToSelf() { sessionFactory().getStatistics().clear(); // long winded method name to say that this is a test specifically for HHH-2277 ;) // essentially we have a bidirectional association where one side of the // association is actually part of a composite PK. // // The way these are mapped causes the problem because both sides // are defined as eager which leads to the infinite loop; if only // one side is marked as eager, then all is ok. In other words the // problem arises when both pieces of instance data are coming from // the same result set. This is because no "entry" can be placed // into the persistence context for the association with the // composite key because we are in the process of trying to build // the composite-id instance Session s = openSession(); s.beginTransaction(); Customer cust = new Customer( "Acme, Inc." ); Order order = new Order( new Order.Id( cust, 1 ) ); cust.getOrders().add( order ); s.save( cust ); s.getTransaction().commit(); s.close(); s = openSession(); s.beginTransaction(); try { cust = ( Customer ) s.get( Customer.class, cust.getId() ); } catch( OverflowCondition overflow ) { fail( "get()/load() caused overflow condition" ); } s.delete( cust ); s.getTransaction().commit(); s.close(); }
4
@Test public void testNoChildren() throws Exception { reader = getReader( Entity2.class, "field1", "element-collection.orm1.xml" ); assertAnnotationPresent( ElementCollection.class ); assertAnnotationNotPresent( OrderBy.class ); assertAnnotationNotPresent( OrderColumn.class ); assertAnnotationNotPresent( MapKey.class ); assertAnnotationNotPresent( MapKeyClass.class ); assertAnnotationNotPresent( MapKeyTemporal.class ); assertAnnotationNotPresent( MapKeyEnumerated.class ); assertAnnotationNotPresent( MapKeyColumn.class ); assertAnnotationNotPresent( MapKeyJoinColumns.class ); assertAnnotationNotPresent( MapKeyJoinColumn.class ); assertAnnotationNotPresent( Column.class ); assertAnnotationNotPresent( Temporal.class ); assertAnnotationNotPresent( Enumerated.class ); assertAnnotationNotPresent( Lob.class ); assertAnnotationNotPresent( AttributeOverride.class ); assertAnnotationNotPresent( AttributeOverrides.class ); assertAnnotationNotPresent( AssociationOverride.class ); assertAnnotationNotPresent( AssociationOverrides.class ); assertAnnotationNotPresent( CollectionTable.class ); assertAnnotationNotPresent( Access.class ); ElementCollection relAnno = reader.getAnnotation( ElementCollection.class ); assertEquals( FetchType.LAZY, relAnno.fetch() ); assertEquals( void.class, relAnno.targetClass() ); }
3.555556
@Test public void testMultipleMapKeyAttributeOverrides() throws Exception { reader = getReader( Entity3.class, "field1", "element-collection.orm11.xml" ); assertAnnotationPresent( ElementCollection.class ); assertAnnotationNotPresent( MapKey.class ); assertAnnotationNotPresent( MapKeyClass.class ); assertAnnotationNotPresent( MapKeyTemporal.class ); assertAnnotationNotPresent( MapKeyEnumerated.class ); assertAnnotationNotPresent( MapKeyColumn.class ); assertAnnotationNotPresent( MapKeyJoinColumns.class ); assertAnnotationNotPresent( MapKeyJoinColumn.class ); assertAnnotationNotPresent( AttributeOverride.class ); assertAnnotationPresent( AttributeOverrides.class ); AttributeOverrides overridesAnno = reader .getAnnotation( AttributeOverrides.class ); AttributeOverride[] overrides = overridesAnno.value(); assertEquals( 2, overrides.length ); assertEquals( "field1", overrides[0].name() ); assertEquals( "", overrides[0].column().name() ); assertFalse( overrides[0].column().unique() ); assertTrue( overrides[0].column().nullable() ); assertTrue( overrides[0].column().insertable() ); assertTrue( overrides[0].column().updatable() ); assertEquals( "", overrides[0].column().columnDefinition() ); assertEquals( "", overrides[0].column().table() ); assertEquals( 255, overrides[0].column().length() ); assertEquals( 0, overrides[0].column().precision() ); assertEquals( 0, overrides[0].column().scale() ); assertEquals( "field2", overrides[1].name() ); assertEquals( "col1", overrides[1].column().name() ); assertTrue( overrides[1].column().unique() ); assertFalse( overrides[1].column().nullable() ); assertFalse( overrides[1].column().insertable() ); assertFalse( overrides[1].column().updatable() ); assertEquals( "int", overrides[1].column().columnDefinition() ); assertEquals( "table1", overrides[1].column().table() ); assertEquals( 50, overrides[1].column().length() ); assertEquals( 2, overrides[1].column().precision() ); assertEquals( 1, overrides[1].column().scale() ); }
2.888889
@Test public void testExplicitPropertyAccessAnnotationsWithHibernateStyleOverride() throws Exception { AnnotationConfiguration cfg = new AnnotationConfiguration(); Class<?> classUnderTest = Course3.class; cfg.addAnnotatedClass( classUnderTest ); cfg.addAnnotatedClass( Student.class ); SessionFactoryImplementor factory = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry ); EntityTuplizer tuplizer = factory.getEntityPersister( classUnderTest.getName() ) .getEntityMetamodel() .getTuplizer(); assertTrue( "Field access should be used.", tuplizer.getIdentifierGetter() instanceof DirectPropertyAccessor.DirectGetter ); assertTrue( "Property access should be used.", tuplizer.getGetter( 0 ) instanceof BasicPropertyAccessor.BasicGetter ); factory.close(); }
3.222222
@Test @TestForIssue( jiraKey = "HHH-7309" ) public void testInsertUpdateEntity_NaturalIdCachedAfterTransactionSuccess() { Session session = openSession(); session.getSessionFactory().getStatistics().clear(); session.beginTransaction(); Another it = new Another( "it"); session.save( it ); // schedules an InsertAction it.setSurname("1234"); // schedules an UpdateAction, without bug-fix // this will re-cache natural-id with identical key and at same time invalidate it session.flush(); session.getTransaction().commit(); session.close(); session = openSession(); session.beginTransaction(); it = (Another) session.bySimpleNaturalId(Another.class).load("it"); assertNotNull(it); session.delete(it); session.getTransaction().commit(); assertEquals("In a strict access strategy we would excpect a hit here", 1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount()); }
3.222222