Dynamic query with hibernate - postgresql

I'm trying to select object from dynamic tables but when I run my code I get some erros... There's a way for to do it... I'm using JPA, hibernate and postgres
#Query(nativeQuery = true,
value =
"SELECT u.* " +
"FROM " +
" ?1 AS u ")
Map<String, String> findAny(String tableName);
Here is the error...
org.springframework.dao.InvalidDataAccessResourceUsageException",
"debugMessage": "org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialec
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

With Hibernate, you can't set table name as paramater, this is to ensure against security risks like SQL injection.

you have to mentions the table that you are getting the data from
value ="SELECT * FROM TableName u ?1")

Related

PostgreSQL {call Update Set ...} getting "syntax error at or near SET"

I'm changing queries from an Oracle Database to PostgreSQL, and in this query I am getting this error:
ERROR: syntax error at or near "SET"
the query is:
{call UPDATE alarm_instance SET last_update_time=default, wait_expire_time=null, core_number=nextval(SEQ_ALRM_NUMBR)
where wait_time <= current_date RETURNING alarm_instance_id bulk collect INTO ?}
I am using JDBC to connect to the database and here is the call code
try (CallableStatement cs = super.prepareCall_(query)) {
cs.registerOutParameter(1, Types.ARRAY);
cs.execute();
...
I have taken a long look at Postgres documentation and cannot find what is wrong and didn't find any answer to this specific situation
An UPDATE statement can't be executed with a CallableStatement. A CallableStatement is essentially only intended to call stored procedures. In case of Oracle that includes anonymous PL/SQL blocks.
And bulk collect is invalid in Postgres to begin with.
It seems you want something like this:
String sql =
"UPDATE alarm_instance " +
" SET last_update_time=default, " +
" wait_expire_time=null, "
" core_number=nextval('SEQ_ALRM_NUMBR') " +
" where wait_time <= current_date RETURNING alarm_instance_id";
Statement stmt = connection.createStatement();
stmt.execute(sql);
int rowsUpdated = stmt.getUpdateCount();
ResultSet rs = stmt.getResultSet();
while (rs.next() {
// do something with the returned IDs
}

JPA query not fetching results

i am working on a certain project. I have a JPA query, which i want to give me a result set but the result has to exclude entries matching some data in another table thus am using NOT IN. My query is as below:
String sql = "SELECT DISTINCT(tia.voucherId) As Voucher, "
+ "e.farmId.name As Farm, CONCAT(e.farmId.farmerId.firstName, ' ', e.farmId.farmerId.lastName) AS Farmer,"
+ " tia.seasonId.name Season, e.farmingActivityId.name As FarmingActivity FROM Enrollment e,"
+ " TemporaryInputsAllocated tia where e.farmId = tia.farmId"
+ " AND tia.voucherId NOT IN (SELECT DISTINCT(ia.voucherId) from InputsAllocated ia )";
When i run my code i get the error:
ERROR controllers.ContractApplicationController - java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [SELECT DISTINCT(tia.voucherId) As Voucher, e.farmId.name As Farm, CONCAT(e.farmId.farmerId.firstName, ' ', e.farmId.farmerId.lastName) AS Farmer, tia.seasonId.name Season, e.farmingActivityId.name As FarmingActivity FROM Enrollment e, TemporaryInputsAllocated tia where e.farmId = tia.farmId AND tia.voucherId NOT IN (SELECT DISTINCT(ia.voucherId) from InputsAllocated ia )], line 1, column 333: unexpected token [(].
Internal Exception: NoViableAltException(83#[1302:1: simpleSelectExpression returns [Object node] : (n= singleValuedPathExpression | n= aggregateExpression | n= variableAccessOrTypeConstant );])

Hibernate Query Language syntax error in query

My Hibernate query is:
SELECT targets from " + TargetSystem.class.getName()
+ " targets join fetch targets.targetSystemType type"
+ " where type.targetSystemTypeName = '"
+ Constants.Constant_TARGET_SYSTEM_TYPE + "'"
And the error I get when I try to execute the query is below
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'TargetSystem targets join fetch targets.targetSystemType ty' at line 1
note: targetSystemTypeName is the Java name of the column in the entity and targetSystemType is a foreign key.
Query execution code:
Query executeQuery = entityManager.createNativeQuery(query,
TargetSystem.class);
#SuppressWarnings("unchecked")
List<TargetSystem> targetSystems = executeQuery.getResultList();
I can't figure out what is the error

Sql column alias not working in Ebeans rawsql

I am facing strange issue with raw SQLs, and I need some help to figure out the best way to fix it. I could, of course, add the columnMappings, but I want to make sure it's not because I am doing something wrong.
Play Framework APP
Ebeans ORM
Postgresql 9.,4
Executing the following RawSQL against a Postgresql database fails if I don't define columnMappings, although I have an alias defined:
String sql
= " Select date_trunc('day', end_time) as theDate, "
+ " count(*) as value "
+ " From ebay_item "
+ " group by date_trunc('day', end_time) ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.create();
Error:
016-03-25 12:05:15,303 ERROR m.c.a.e.s.p.SimpleDBPromiseService - Error executing named query
javax.persistence.PersistenceException: Property [dateTrunc('day'] not found on models.com.abiesolano.ebay.sqlpojos.RangedDateCounter
If I switch to an H2 database:
String sql
= " SELECT trunc(end_time) as theDate, "
+ " count(*) as value "
+ " From ebay_item "
+ " Group by trunc(end_time)";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.create();
it works no problems.
Any suggestion would be really appreciated.
I don't think mysql likes to group or order by functions, you should use your alias "theDate" instead.
Note that if you're mapping to a bean object, the alias must be a #Transient property of your bean to be mapped by Ebean (otherwise, you'll get an unknown property error).

IF EXISTS not recognized in Derby

DROP TABLE IF EXISTS Pose ;
results in the error
Error code -1, SQL state 42X01: Syntax error: Encountered "EXISTS" at line 1, column 15.
I'm running this from inside NetBeans 7.3 using the default Derby sample db.
Derby does not currently support IF EXISTS
Are you trying to create a table? If yes, this is what you should do:
public void createTables() throws SQLException {
Statement statement = getConnection().createStatement();
System.out.println("Checking database for table");
DatabaseMetaData databaseMetadata = getConnection().getMetaData();
ResultSet resultSet = databaseMetadata.getTables(null, null, "PATIENT", null);
if (resultSet.next()) {
System.out.println("TABLE ALREADY EXISTS");
} else {
//language=MySQL
statement.execute("CREATE TABLE Patient (" +
"CardNumber CHAR(10) NOT NULL PRIMARY KEY, " +
" FirstName CHAR(50)," +
" MiddleName CHAR(50)," +
" LastName CHAR(50) )");
}
}
Remember to use all caps for the table name you pass into databaseMetadata.getTables(...)
The MySQL 6.0 syntax for declaring a table is this:
CREATE TABLE [IF NOT EXISTS] tableName ...
and the MySQL syntax for removing a table is this:
DROP TABLE [IF EXISTS] tableName ...
These clauses are MySQL extensions which are not part of the ANSI/ISO SQL Standard. This functionality may be peculiar to MySQL: I can't find anything similar documented for Derby, Postgres, Oracle, or DB2.
The best alternative I can find is to query the system tables to see if the table exists.
select count(*) from sys.systables where tablename = 'YOUR_TABLE_NAME'"
I had a similar issue dropping stored procedures. They can be queried using this statement.
select count(*) from sys.sysaliases where alias = 'YOUR_STORED_PROCEDURE_NAME'
If someone is looking to drop and create a table in an sql file that is Run with Spring test framework, Check https://stackoverflow.com/a/47459214/3584693 for an answer that ensures that no exception is thrown when drop table is invoked when said table doesn't exist.