use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class SimpleResultSetProcessorTest method testSimpleEntityProcessing.
@Test
public void testSimpleEntityProcessing() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister(SimpleEntity.class.getName());
// create some test data
Session session = openSession();
session.beginTransaction();
session.save(new SimpleEntity(1, "the only"));
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan(sessionFactory(), entityPersister);
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails(plan, sessionFactory());
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
((SessionImplementor) workSession).getFactory().getServiceRegistry().getService(JdbcServices.class).getSqlStatementLogger().logStatement(sql);
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, 1);
ResultSet resultSet = ps.executeQuery();
results.addAll(resultSetProcessor.extractResults(resultSet, (SessionImplementor) workSession, new QueryParameters(), new NamedParameterContext() {
@Override
public int[] getNamedParameterLocations(String name) {
return new int[0];
}
}, true, false, null, null));
resultSet.close();
ps.close();
}
});
assertEquals(1, results.size());
Object result = results.get(0);
assertNotNull(result);
SimpleEntity workEntity = ExtraAssertions.assertTyping(SimpleEntity.class, result);
assertEquals(1, workEntity.id.intValue());
assertEquals("the only", workEntity.name);
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery("delete SimpleEntity").executeUpdate();
session.getTransaction().commit();
session.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class CriteriaQueryImpl method interpret.
@Override
public CriteriaInterpretation interpret(RenderingContext renderingContext) {
final StringBuilder jpaqlBuffer = new StringBuilder();
queryStructure.render(jpaqlBuffer, renderingContext);
if (!getOrderList().isEmpty()) {
jpaqlBuffer.append(" order by ");
String sep = "";
for (Order orderSpec : getOrderList()) {
jpaqlBuffer.append(sep).append(((Renderable) orderSpec.getExpression()).render(renderingContext)).append(orderSpec.isAscending() ? " asc" : " desc");
sep = ", ";
}
}
final String jpaqlString = jpaqlBuffer.toString();
log.debugf("Rendered criteria query -> %s", jpaqlString);
return new CriteriaInterpretation() {
@Override
@SuppressWarnings("unchecked")
public QueryImplementor buildCompiledQuery(SessionImplementor entityManager, final InterpretedParameterMetadata parameterMetadata) {
final Map<String, Class> implicitParameterTypes = extractTypeMap(parameterMetadata.implicitParameterBindings());
QueryImplementor<T> jpaqlQuery = entityManager.createQuery(jpaqlString, getResultType(), getSelection(), new HibernateEntityManagerImplementor.QueryOptions() {
@Override
public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
return selection == null ? null : selection.getValueHandlers();
}
@Override
public Map<String, Class> getNamedParameterExplicitTypes() {
return implicitParameterTypes;
}
@Override
public ResultMetadataValidator getResultMetadataValidator() {
return new HibernateEntityManagerImplementor.QueryOptions.ResultMetadataValidator() {
@Override
public void validate(Type[] returnTypes) {
SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
if (selection != null) {
if (selection.isCompoundSelection()) {
if (returnTypes.length != selection.getCompoundSelectionItems().size()) {
throw new IllegalStateException("Number of return values [" + returnTypes.length + "] did not match expected [" + selection.getCompoundSelectionItems().size() + "]");
}
} else {
if (returnTypes.length > 1) {
throw new IllegalStateException("Number of return values [" + returnTypes.length + "] did not match expected [1]");
}
}
}
}
};
}
});
for (ImplicitParameterBinding implicitParameterBinding : parameterMetadata.implicitParameterBindings()) {
implicitParameterBinding.bind(jpaqlQuery);
}
return new CriteriaQueryTypeQueryAdapter(entityManager, jpaqlQuery, parameterMetadata.explicitParameterInfoMap());
}
private Map<String, Class> extractTypeMap(List<ImplicitParameterBinding> implicitParameterBindings) {
final HashMap<String, Class> map = new HashMap<String, Class>();
for (ImplicitParameterBinding implicitParameter : implicitParameterBindings) {
map.put(implicitParameter.getParameterName(), implicitParameter.getJavaType());
}
return map;
}
};
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteConnectedSesssion.
@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteConnectedSesssion() {
Parent p = new Parent();
Child c = new Child();
p.children.add(c);
Session s1 = openSession();
s1.getTransaction().begin();
s1.saveOrUpdate(p);
// The collection is "connected" to s1 because it contains the CollectionEntry
CollectionEntry ce = ((SessionImplementor) s1).getPersistenceContext().getCollectionEntry((PersistentCollection) p.children);
assertNotNull(ce);
// the collection session should be s1
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
Session s2 = openSession();
s2.getTransaction().begin();
Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
assertFalse(triggerable.wasTriggered());
// The following should trigger warning because we're unsetting a different session
// We should not do this in practice; it is done here only to force the warning.
// Since s1 was not flushed, the collection role will not be known (no way to test that).
assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
assertTrue(triggerable.wasTriggered());
// collection's session should still be s1
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
s2.getTransaction().rollback();
s2.close();
s1.getTransaction().rollback();
s1.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteConnectedSesssionFlushed.
@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteConnectedSesssionFlushed() {
Parent p = new Parent();
Child c = new Child();
p.children.add(c);
Session s1 = openSession();
s1.getTransaction().begin();
s1.saveOrUpdate(p);
// flush the session so that p.children will contain its role
s1.flush();
// The collection is "connected" to s1 because it contains the CollectionEntry
CollectionEntry ce = ((SessionImplementor) s1).getPersistenceContext().getCollectionEntry((PersistentCollection) p.children);
assertNotNull(ce);
// the collection session should be s1
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
Session s2 = openSession();
s2.getTransaction().begin();
Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
assertFalse(triggerable.wasTriggered());
// The following should trigger warning because we're unsetting a different session
// We should not do this in practice; it is done here only to force the warning.
// The collection role and key should be included in the message (no way to test that other than inspection).
assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
assertTrue(triggerable.wasTriggered());
// collection's session should still be s1
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
s2.getTransaction().rollback();
s2.close();
s1.getTransaction().rollback();
s1.close();
}
use of org.hibernate.engine.spi.SessionImplementor in project hibernate-orm by hibernate.
the class MultipleSessionCollectionWarningTest method testUnsetSessionCannotOverwriteNonConnectedSesssion.
@Test
@TestForIssue(jiraKey = "HHH-9518")
public void testUnsetSessionCannotOverwriteNonConnectedSesssion() {
Parent p = new Parent();
Child c = new Child();
p.children.add(c);
Session s1 = openSession();
s1.getTransaction().begin();
s1.saveOrUpdate(p);
// Now remove the collection from the PersistenceContext without unsetting its session
// This should never be done in practice; it is done here only to test that the warning
// gets logged. s1 will not function properly so the transaction will ultimately need
// to be rolled-back.
CollectionEntry ce = (CollectionEntry) ((SessionImplementor) s1).getPersistenceContext().getCollectionEntries().remove(p.children);
assertNotNull(ce);
// the collection session should still be s1; the collection is no longer "connected" because its
// CollectionEntry has been removed.
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
Session s2 = openSession();
s2.getTransaction().begin();
Triggerable triggerable = logInspection.watchForLogMessages("HHH000471:");
assertFalse(triggerable.wasTriggered());
// The following should trigger warning because we're unsetting a different session.
// We should not do this in practice; it is done here only to force the warning.
// Since s1 was not flushed, the collection role will not be known (no way to test that).
assertFalse(((PersistentCollection) p.children).unsetSession((SessionImplementor) s2));
assertTrue(triggerable.wasTriggered());
// collection's session should still be s1
assertSame(s1, ((AbstractPersistentCollection) p.children).getSession());
s2.getTransaction().rollback();
s2.close();
s1.getTransaction().rollback();
s1.close();
}
Aggregations