Skip to content

DATAJDBC-161: Share an SqlSession into a same transaction #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.data.jdbc.core.DataAccessStrategy;
import org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty;
import org.springframework.data.mapping.PropertyPath;
Expand All @@ -38,16 +39,22 @@
* For methods taking a {@link PropertyPath} the entityTyoe if the context is set to the class of the leaf type.
*
* @author Jens Schauder
* @author Kazuki Shimizu
*/
public class MyBatisDataAccessStrategy implements DataAccessStrategy {

private static final String MAPPER_SUFFIX = "Mapper";

private final SqlSessionFactory sqlSessionFactory;
private final SqlSession sqlSession;

public MyBatisDataAccessStrategy(SqlSessionFactory sqlSessionFactory) {

this.sqlSessionFactory = sqlSessionFactory;
this(new SqlSessionTemplate(sqlSessionFactory));
}

public MyBatisDataAccessStrategy(SqlSessionTemplate sqlSessionTemplate) {

this.sqlSession = sqlSessionTemplate;
}

@Override
Expand Down Expand Up @@ -139,6 +146,6 @@ private String mapper(Class<?> domainType) {
}

private SqlSession sqlSession() {
return sqlSessionFactory.openSession();
return this.sqlSession;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,17 @@

import java.util.Collections;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty;
import org.springframework.data.jdbc.mybatis.MyBatisContext;
import org.springframework.data.jdbc.mybatis.MyBatisDataAccessStrategy;
Expand All @@ -36,20 +41,27 @@
* Unit tests for the {@link MyBatisDataAccessStrategy}, mainly ensuring that the correct statements get's looked up.
*
* @author Jens Schauder
* @author Kazuki Shimizu
*/
public class MyBatisDataAccessStrategyUnitTests {

DataSource dataSource = mock(DataSource.class);
SqlSessionFactory sessionFactory = mock(SqlSessionFactory.class);
SqlSession session = mock(SqlSession.class);
ArgumentCaptor<MyBatisContext> captor = ArgumentCaptor.forClass(MyBatisContext.class);

MyBatisDataAccessStrategy accessStrategy = new MyBatisDataAccessStrategy(sessionFactory);
MyBatisDataAccessStrategy accessStrategy;

@Before
public void before() {

doReturn(session).when(sessionFactory).openSession();
Configuration configuration = new Configuration();
Environment environment = new Environment("unittest", new SpringManagedTransactionFactory(), dataSource);
configuration.setEnvironment(environment);
doReturn(configuration).when(sessionFactory).getConfiguration();
doReturn(session).when(sessionFactory).openSession(configuration.getDefaultExecutorType());
doReturn(false).when(session).selectOne(any(), any());
this.accessStrategy = new MyBatisDataAccessStrategy(sessionFactory);
}

@Test // DATAJDBC-123
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@
@Alias("DummyEntity")
class DummyEntity {

@Id final Long id;
@Id final long id;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change seems unrelated to DATAJDBC-161, possibly related to DATAJDBC-160

final String name;

public DummyEntity(String name) {
this(0L, name);
}
public DummyEntity(Long id, String name) {
this.id = id;
this.name = name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.mybatis;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Iterator;

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.jdbc.testing.TestConfiguration;
import org.springframework.data.repository.CrudRepository;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.transaction.annotation.Transactional;

/**
* Tests the integration with Mybatis batch mode.
*
* @author Kazuki Shimizu
*/
@ContextConfiguration
@Transactional
public class MyBatisBatchHsqlIntegrationTests {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again I don't understand the connection to the issue this tries to fix.


@org.springframework.context.annotation.Configuration
@Import(TestConfiguration.class)
@EnableJdbcRepositories(considerNestedRepositories = true)
static class Config {

@Bean
Class<?> testClass() {
return MyBatisBatchHsqlIntegrationTests.class;
}

@Bean
SqlSessionFactoryBean createSessionFactory(EmbeddedDatabase db) {

Configuration configuration = new Configuration();
configuration.setDefaultExecutorType(ExecutorType.BATCH);
configuration.getTypeAliasRegistry().registerAlias("MyBatisContext", MyBatisContext.class);

configuration.getTypeAliasRegistry().registerAlias(DummyEntity.class);
configuration.addMapper(DummyEntityMapper.class);

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(db);
sqlSessionFactoryBean.setConfiguration(configuration);

return sqlSessionFactoryBean;
}

@Bean
SqlSessionTemplate SqlSessionTemplate(SqlSessionFactory factory) {
return new SqlSessionTemplate(factory);
}

@Bean
MyBatisDataAccessStrategy dataAccessStrategy(SqlSessionTemplate template) {
return new MyBatisDataAccessStrategy(template);
}
}

@ClassRule public static final SpringClassRule classRule = new SpringClassRule();
@Rule public SpringMethodRule methodRule = new SpringMethodRule();

@Autowired DummyEntityRepository repository;

@Test
public void batchInsertAndSelect() {

DummyEntity entity1 = new DummyEntity("some name");
DummyEntity saved1 = repository.save(entity1);

DummyEntity entity2 = new DummyEntity("some name");
DummyEntity saved2 = repository.save(entity2);

assertThat(saved1.id).isEqualTo(0);
assertThat(saved2.id).isEqualTo(0);

Iterator<DummyEntity> loadedEntities = repository.findAll().iterator();

DummyEntity loaded1 = loadedEntities.next();
assertThat(saved1.id).isNotEqualTo(0);
assertThat(loaded1.id).isEqualTo(saved1.id);
assertThat(loaded1).isNotNull().extracting(e -> e.id, e -> e.name);

DummyEntity loaded2 = loadedEntities.next();
assertThat(saved2.id).isNotEqualTo(0);
assertThat(loaded2.id).isEqualTo(saved2.id);
assertThat(loaded2).isNotNull().extracting(e -> e.id, e -> e.name);

assertThat(loadedEntities.hasNext()).isFalse();

}

interface DummyEntityRepository extends CrudRepository<DummyEntity, Long> {

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,10 @@ public void mybatisSelfTest() {
@Test // DATAJDBC-123
public void myBatisGetsUsedForInsertAndSelect() {

DummyEntity entity = new DummyEntity(null, "some name");
DummyEntity entity = new DummyEntity("some name");
DummyEntity saved = repository.save(entity);

assertThat(saved.id).isNotNull();
assertThat(saved.id).isNotEqualTo(0);

DummyEntity reloaded = repository.findById(saved.id).orElseThrow(AssertionFailedError::new);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE dummyentity(id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY);
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@
<insert id="insert" parameterType="MyBatisContext" useGeneratedKeys="true" keyProperty="instance.id" keyColumn="ID">
INSERT INTO DummyEntity (id) VALUES (DEFAULT)
</insert>
<select id="findById" resultType="MyBatisContext" resultMap="dummyEntityMap">
<select id="findById" resultMap="dummyEntityMap">
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again possibly unrelated to the issue at hand.

SELECT
id,
'Name based on an id' || id AS name
FROM DummyEntity
WHERE id = #{id}
</select>
<select id="findAll" resultMap="dummyEntityMap">
SELECT
id,
'Name based on an id' || id AS name
FROM DummyEntity
ORDER BY id
</select>

</mapper>