SimpleJdbcCall: Two Stored Procedure call in a class hang up application - java

I'm using SimpleJdbcCall to make a call to two stored procedure in two different functions using JdbcTemplate. The first Stored procedure call get successfull, but second Stored procedure call just hangs up & following message appears in log & nothing goes forward:
2019-10-23 02:00:33,043 DEBUG [http-nio-8080-exec-13:org.springframework.jdbc.datasource.DataSourceUtils] - Fetching JDBC Connection from DataSource
Here is the source code for config & code part
DataSourceConfig.java
#Configuration
public class DataSourceConfig {
#Autowired
private DataSource dataSource;
#Bean
public JdbcClientDetailsService jdbcClientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
}
OAuth2AuthorizationServerConfigurer
#Configuration
#EnableAuthorizationServer
public class OAuth2AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
#Autowired
private JdbcClientDetailsService jdbcClientDetailsService;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// clients.jdbc(dataSource);
clients.withClientDetails(jdbcClientDetailsService);
}
}
Class where two Stored Procedures are getting called & application hang's up at 2nd Stored Procedure call. (First stored procedure call is getting executed. If no data found in it's result, it will go into else block which is currently happening)
CompanyService.java
#Component
public class CompanyService {
#Autowired
private JdbcTemplate jdbcTemplate;
private static Logger logger = LoggerFactory.getLogger(CompanyService.class);
public CompanyInfo getCompanyDetails(Integer companyId){
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate);
simpleJdbcCall.withSchemaName("foo")
.withCatalogName("foo_pkg")
.withProcedureName("SELECT_COMPANY"); //select company Stored Procedure
SqlParameterSource in = new MapSqlParameterSource()
.addValue("companyId", companyId)
.addValue("name",null)
.addValue("uuid",null);
try {
Map<String, Object> out = simpleJdbcCall.execute(in);
return //some method to convert out into CompanyInfo
}catch (DataAccessException ex){
logger.error("getCompanyDetails"+ex.getMessage());
return null;
}
}
public CompanyInfo registerCompany(RegisterCompany registerCompany) {
CompanyInfo companyInfo = getCompanyDetails(registerCompany.getCompanyId());
if(companyInfo!=null){
//TODO: throw an exception
}
else{
SimpleJdbcCall mergeJdbcCall = new SimpleJdbcCall(jdbcTemplate);
mergeJdbcCall.withSchemaName("foo")
.withCatalogName("foo_pkg")
.withProcedureName("MERGE_COMPANY"); //Merge company Stored Procedure
SqlParameterSource in = new MapSqlParameterSource()
.addValue("companyId", registerCompany.getCompanyPartyClassId())
.addValue("name",getName())
.addValue("uuid",getUuid());
Map<String, Object> out = mergeJdbcCall.execute(in); //It's getting hang up at this level
}
return null;
}
}
What is the configuration I've missed here, which is causing an issue. I also went throug details of SimpleJdbcCall which describe
A SimpleJdbcCall is a multi-threaded, reusable object representing a call to a stored procedure or a stored function.
that's why I created two different object of it in class. Tried with defining it at class level as well, still the same issue.
Is it the case that SimpleJdbcCall works for one call in one class ? What are the other alternatives that I can use ? (Apart from PreparedStatement)

Related

Arango spring data rollback

I am doing a work on arango db. Dose arangodb-spring-boot-starter has the transition and rollback support
I have tried #Transition annotation in the custom repo layer. added a error by custom error, the service has a functionality to create multiple document. I was expecting the rollback which is not happened.
This is the arango repository code.
public interface RelationRepository extends ArangoRepository<Relation, String> {
#Transactional
#Query("insert { _from: #from, _to: #to } into #collection return NEW")
Set<Relation> createEdge(#Param("from") String from,#Param("to") String to;}
This is the code snippet for the service
#Service
public class RelationService {
#Autowired
private RelationRepository relationRepository;
private final Logger log = LoggerFactory.getLogger(RelationService.class);
#Transactional(rollbackFor = SQLException.class)
public HashMap<String,String> demoRelation() {
relationRepository.createEdge("vertex1/121286","vertex2/167744","relation",
Instant.now().toEpochMilli(),Long.MAX_VALUE);
if(true)
throw new SQLException("custom exception to check rollback");
return null;
}
}
I was expecting the rollback, instead it is creating records

Transaction partially committing or rolling back

I am facing some issue with transactions configured in my code.
Below is the code with transactions which writes data to DB.
Writer.java
class Writer {
#Inject
private SomeDAO someDAO;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void write(){
this.batchWrite();
}
private void batchWrite () {
try {
someDAO.writeToTable1(true);
} catch(Exception ex) {
someDAO.writeToTable1(false);
}
someDAO.writeToTable2();
}
}
SomeDAO.java
class SomeDAO {
#Inject
private JdbcTemplate JdbcTemplate;
public void writeToTable1(boolean flag) {
// Writes data to table 1 using jdbcTemplate
jdbcTemplate.update();
}
pulic void writeToTable2() {
// Writes data to table 2 using jdbcTemplate
jdbcTemplate.update();
}
}
Here data is getting stored into table 1 properly but sometimes, table 2 is getting skipped.
I am not sure how this is happening as both the tables have been written within same transaction.
Either transaction is partially committing the data or partially rolling back.
I have doubt that in the SomeDAO class I am injecting JdbcTemplate object which is creating new connection instead of using existing connection of transaction.
Can anyone please help me here?
Try binding a Transaction Manager bean having your jdbcTemplate inside #Transactional:
//Create a bean
#Bean
public PlatformTransactionManager txnManager() throws Exception {
return new DataSourceTransactionManager(jdbcTemplate().getDataSource());
}
And then use this transaction manager in #Transactional("txnManager").

JdbcTemplate insert success but no rows in database

This question was asked a couple of years ago, but the answer didn't work for me. I have added the suggested annotations to the config and to the dao. I am sure that Template is actually connecting to the DB because I was getting appropriate errors when I had a column too small. The update call is doing a single row insert and it is returning 1 with no exceptions. Yet, when I check the database there is no data in it.
Any help would be appreciated.
Config:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.XXX.query.repository")
public class SqlConfig {
#Autowired
private Environment env;
#Bean
public DataSource getDatasource() {
DriverManagerDataSource datasource = new DriverManagerDataSource();
datasource.setDriverClassName(env.getProperty("sql-datasource.driverClassName"));
datasource.setUrl(env.getProperty("sql-datasource.url"));
datasource.setUsername(env.getProperty("sql-datasource.username"));
datasource.setPassword(env.getProperty("sql-datasource.password"));
return datasource;
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(getDatasource());
}
DAO:
#Repository
public class SqlRepositoryImpl implements SqlRepository {
#Autowired
private JdbcTemplate template;
<snip>
#Transactional
#Override
public void addOrder(String foo, String bar, String bat, String cat) {
int i;
try {
// we may already have this data
System.out.println("here");
i = template.update(
"insert into someTable "
+ "(A, B, C, D)"
+ " values (?,?,?,?)",
foo, bar, bat, cat);
} catch (DataAccessException ex) {
checkForDupeKey(ex);
}
<snip>
There was a stupid mistake in the area that threw an exception and unwound the transaction. For some reason that exception never bubbled to the surface so I wasn't aware of it until I stepped through everything one line at a time. My apologies for wasting people's time.

Spring Batch multiple insert for a one read

I've a Spring Batch process that read Report objects from a CSV and insert Analytic objects into a MySQL DB correctly, but the logical has changed for a more than one Analytics insert for each Report readed.
I'm new in Spring Batch and the actually process was very difficult for me, and I don't know how to do this change.
I haven't XML configuration, all is with annotations. Report and Analytics classes have a getter and a setter for two fields, adId and value. The new logic has seven values for an adId and I need to insert seven rows into table.
I hide, delete or supress some code that not contribute for the question.
Here is my BatchConfiguration.java:
#Configuration
#EnableBatchProcessingpublic
class BatchConfiguration {
#Autowired
private transient JobBuilderFactory jobBuilderFactory;
#Autowired
private transient StepBuilderFactory stepBuilderFactory;
#Autowired
private transient DataSource dataSource;
public FlatFileItemReader<Report> reader() {
// The reader from the CSV works fine.
}
#Bean
public JdbcBatchItemWriter<Analytic> writer() {
final JdbcBatchItemWriter<Analytic> writer = new JdbcBatchItemWriter<Analytic>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Analytic>());
writer.setSql("INSERT INTO TABLE (ad_id, value) VALUES (:adId, :value)");
writer.setDataSource(dataSource);
return writer;
}
#Bean
public AnalyticItemProcessor processor() {
return new AnalyticItemProcessor();
}
#Bean
public Step step() {
return stepBuilderFactory.get("step1").<Report, Analytic> chunk(10000).reader(reader()).processor(processor()).writer(writer()).build();
}
#Bean
public Job process() {
final JobBuilder jobBuilder = jobBuilderFactory.get("process");
return jobBuilder.start(step()).build();
}
}
Then the AnalyticItemProcessor.java
public class AnalyticItemProcessor implements ItemProcessor<Report, Analytic> {
#Override
public Analytic process(final Report report) {
// Creates a new Analytic call BeanUtils.copyProperties(report, analytic) and returns analytic.
}
}
And the Process:
#SpringBootApplication
public class Process {
public static void main(String[] args) throws Exception {
SpringApplication.run(Process.class, args);
}
}
How can I do this change? Maybe with ItemPreparedStatementSetter or ItemSqlParameterSourceProvider? Thanks.
If I'm understanding your question correctly, you can use the CompositeItemWriter to wrap multiple JdbcBatchItemWriter instances (one per insert you need to accomplish). That would allow you to insert multiple rows per item. Otherwise, you'd need to write your own ItemWriter implementation.

Multiple SessionFactories' sessions together

I am trying to implement a sharded Hibernate logic. All Databases have same table called MyTable which is mapped to MyClass through Hibernate POJO.
public class SessionFactoryList {
List<SessionFactory> factories;
int minShard;
int maxShard;
// getters and setters here.
}
In my Dao implementation, I have a method getAll which is following -
public class MyClassDao {
#Autowired // through Spring
private SessionFactoryList list;
List<MyClass> getAll() {
List<MyClass> outputList = new ArrayList<>();
for(SessionFactory s : list.getFactories()) {
Criteria c = s.getCurrentSession.createCriteria(MyClass.class);
outputList.addAll(c.list());
}
return outputList;
}
Here is my test for the corresponding getAll implementation -
public class MyClassTest {
#Autowired
SessionFactoryList list;
#Autowired
MyClassDao myClassDao;
#Test
void getAllTest() {
Session session1 = list.getFactories.get(0).getCurrentSession();
session1.beginTransaction();
session1.save(new MyClass(// some parameters here));
Session session2 = list.getFactories.get(1).getCurrentSession();
session2.beginTransaction();
session2.save(new MyClass(// some parameters here));
//Set up done.
assert myClassDao.getAll().size() == 2
}
}
I am using HSQL in-memory database for the test cases.
I have verified that DB connections are correctly setup, but the Assert statement is failing.
'getAll' method of MyClassDao is returning 3 rows. MyClass object inserted in SessionFactory1's session is getting duplicated.
Is there anything I am missing out here?
I found it. The 2 sessionFactory configurations which I used for the test had same Database URL. Hence the same database was queried twice which caused the duplicates.

Categories