Difference in HSQL and MySQL - java

I am using MySQL as my application database, but HSQL as test in-memory database. Now the issue is I have a SQL selectQuery like below :
SELECT date(a.created_at) as record_date
FROM table a
Now, date() is a function in MYSQL for converting DateTime to Date, but in HSQL the same function is to_date(). Now, I have a method which hits the above query to database and gets output.
public Response dbQueryThroughJdbcTemplate(String selectQuery){
jdbcTemplate.query(selectQuery, RowMapper); //RowMapper maps output to Response
}
Now, I have a test method for testing this method,
#Test
public void testDbQueryThroughJdbcTemplate(){
Response response = dbQueryThroughJdbcTemplate(selectQuery);
TestCase.assertEquals(expected, response); // avoided the code for making expected object
}
Now, as the test environment is using HSQL db, the test throws an error that date method is not available.
How to come out of this issue, or any better way to achieve this?

You can try an alternative that is supported by both HSQLDB and MySQL
SELECT CAST(a.created_at AS DATE) as record_date FROM table a

Related

Selenium Web driver and Mongo DB

I want to create a Java selinum Web driver script (Maven project)
I want to connect to my Mongo DB (database already exists), execute a query on a collection ({dublinCore.externalID: "123456"}) and get the result.
I try these lines of code but I'm stuck in this step:
#BeforeSuite
public void MongodbConnection()
{
Logger mongoLogger= Logger.getLogger("org.mongodb.driver");
mongoclient= MongoClients.create("");
mongodatabase= mongoclient.getDatabase("db01");
mongodatabase.runCommand()
}
I try to put my database URI in MongoClients.create("");
I try to put the query in mongodatabase.runCommand();
Is that only what I need to execute a query or what? I just want to get the result from the database to make assertion with the current result.

Stored procedure with Hibernate fails in embedded h2 database

Im saving data to myRepository1 and to be able to see the savings via the materialized view, i need to refresh it.
myRepository1.save(myObject);
myRepository2.refreshView();
myRepository2 has:
#Modifying
#Query(value = "BEGIN my_refresh_view(); END;", nativeQuery = true)
void refreshView();
Where my_refresh_view is a simple stored procedure.
This works fine in the real world (Oracle DB) - however, when i run my integration tests for the code above using an embedded h2 database, i get:
BEGIN my_refresh_view(); END; [42000-200]
org.springframework.dao.InvalidDataAccessResourceUsageException could not prepare statement;
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
Looks like the stored procedure and h2 dont match well together.
Any ideas how to make it work, or maybe there are workarounds?
Hibernate JPA (at least 5.0.0 and below) does not support stored procedures for H2Dialect.H2Dialect inherits Dialect.getCallableStatementSupport() which returns StandardCallableStatementSupport.NO_REF_CURSOR_INSTANCE. The standard callable statement support does not properly handle the H2 "out" parameter which is a Java return value and not a statement parameter
check details here

Potential Limitations to using getString() insted of getClob() for PostgreSQL database

I am currently working with a product which has either a PostgreSQL database or an Oracle database
In this application, there is a getClob() which will return a clob from an oracle database. However this becomes a problem when the application is using a PostgreSQL database, as the getClob() produces errors, but getString() works perfectly
My question is then: will there be any limitations if I use getString() insted of using getClob()? Limitations such as getString can only handle half the data a clob can etc
Any Help would be appriciated :)

Copying a Clob in another Clob with different implementation

In my company we are performing a database migration. For lots of reasons we cannot use a database migration tool, so we had to develop our migration tool to copy from a DB to another all rows contained in some specific tables. We have developed a tool using JDBC of multiple database. At the moment, we are migrating from DB2 to Oracle, with an intermediate step to H2. Same tables ha a Clob column. When we export this column from DB2 to H2 we get no errors or issues, but when we try to copy the Clob from H2 to Oracle using JDBC we get the following exception:
ClassCastException: cannot cast from org.h2.jdbc.JdbcClob to oracle.jdbc.Clob
Is there a way or a procedure to perform this kind of conversion? Something like a ClobCopy utility within different Clob types? Unfortunately we can do this task only using Java and Jdbc, no JPA or DB migration tools due to customer specifications.
This is an example of what I'm trying to do:
public class CopyTable {
public void doCopy(){
Connection h2 = getH2Connection(); //suppose this exists and works
Connection oracle = getOracleConnection(); //suppose this exists and works
String sqlSelect = "select * from tabletoexport";
String sqlInsert = "insert into tabletofill(ID, DATA) values (?,?)";
PreparedStatement select = h2.prepareStatement(sqlSelect);
PreparedStatement insert = oracle.prepareStatement(sqlInsert);
ResultSet rs = select.executeQuery();
while (rs.next()){
insert.setLong(1, rs.getLong("ID"));
insert.setClob(2, rs.getClob("DATA")); //this throws an exception
insert.executeUpdate();
}
}
}
The Clob interface has a getCharacterStream() method which returns a Reader, and the PreparedStatement interface has a setClob() method which takes a Reader. All you need to do to get the copy working is to use these methods.
In other words, replace the line
insert.setClob(2, rs.getClob("DATA")); //this throws an exception
with
insert.setClob(2, rs.getClob("DATA").getCharacterStream());
As for why the import from DB/2 to H2 didn't complain, perhaps the H2 JDBC driver doesn't assume that Clob values passed in to setClob come from H2, but the Oracle JDBC driver does assume that Clobs passed in in the same way are from Oracle. However, the Oracle JDBC can't reasonably make any such assumptions about a Reader, as these could come from anywhere

How could I log the sql query (with the actual parameters) in java + Spring

how could I log the sql query (with the actual parameters) in java + Spring.
My dev environment
Java
Spring JdbcTemplate.
Let me elaborate the question.
My pseudo code is like this.
String sql = "SELECT COLUMN1 FROM MYTABLE WHERE COLUMN2=? "
List<MyVO> MyVOList = getJdbcTemplate().query(sql, new Object[] { date },
new RowMapper...
Now if I wanted to log the sql - with the actual date that was sent to it - I dont know how to do it.
Option 1 : I can always log the SQL and log the parameters seperately, but I want to have the actual SQL in the logs so the support staff could just copy paste the SQL and run it from a SQL client if need be.
Option 2 : I can think of doing a string substituition and creating the SQL in java and then logging it. However, that always leaves the possibility that because of some freak coding error the actual SQL and the logged SQL are different.
Has someone tried to solve this issue and made any progress?
Please share. Thanks.
Note: I have already read the post Log SQL that is communicated with the database. Using this solution is not an option for me. I am working within an enterprise setup and jdbcdslog-exp is not on the approved list of softwares.
Logging SQL queries with Spring
JdbcTemplate.query() method finally calls execute method.
Below is the execute method in JdbcTemplete spring class.
Extend this class and log for this.val$sql this may give what you need.
public void execute(String sql) throws DataAccessException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Executing SQL statement [" + sql + "]");
}
execute(new StatementCallback(sql) {
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(this.val$sql);
return null;
}
public String getSql() {
return this.val$sql;
}
});
}

Categories