How to get OracleConnection for storing JGeometry to Oracle DB - java

I am trying store JGeometry to Oracle database with the following code:
#PersistenceContext
private EntityManager entityManager;
...
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
#Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("UPDATE SAMPLE_AREA SET GEOMETRY=? WHERE ID = " + sampleAreaId + " AND SAMPLE_ID = " + sampleId);
System.out.println(connection); // prints: org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler#321ca777[valid=true]
System.out.println(connection.getClass().getName()); // prints: com.sun.proxy.$Proxy125
STRUCT obj = JGeometry.store(jGeometry, connection);
ps.setObject(1, obj);
ps.execute();
}
});
I am getting java.lang.ClassCastException: com.sun.proxy.$Proxy125 cannot be cast to oracle.jdbc.OracleConnection when calling JGeometry.store.
How can I get OracleConnection?
I am using "hibernate.dialect = org.hibernate.dialect.Oracle10gDialect"

I figured out the solution. Instead of using Connection as parameter to JGeometry.store one needs to use OracleConnection. That can be unwrapped from Connection. I think I tried this before, but most likely I had wrong import, correct is oracle.jdbc.OracleConnection.
import oracle.jdbc.OracleConnection;
...
OracleConnection oracleConnection = connection.unwrap( OracleConnection.class );
STRUCT obj = JGeometry.store(jGeometry, oracleConnection);

Related

Cannot capture XML returned by SQL Server stored procedure using Java

I am trying to run a SQL Server 2014 stored procedure from Java (Spring) code and get some xml results.
When I run this in a SQL client e.g. RazorSQL I get a bunch of xmls (which is expected because the there are multiple stored procedures within it, that returns those xml).
Here is the Exec call from my SQL client:
EXEC [dbo].[sp_GetType]
#TRAN_ID = 42
#QUAL_ID = 0
GetType does a RETURN 0 at the end (so basically if all steps succeed, it returns 0)
This opens multiple tabs in my client with the xmls.
And one example stored procedure within GetType has these lines:
SELECT TOP 1 ModifiedBy = CASE WHEN #IS_ID = 1 FROM TABLE23.dbo.TRX
TrxId WITH (NOLOCK) WHERE #DD_ID = #TRAN_ID
FOR XML AUTO, ELEMENTS
My goal is to capture all the xmls returned by GetType into a List of objects.
Here is my dao:
private final JdbcTemplate jdbcTemplate;
#Autowired
public TransactionDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Transactional(readOnly = true)
public List<Object> getTransaction(Integer tranId, Integer qualId) {
Object dt = new Object();
List<Object> resultList = (List<Object>) jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
String storedProc = "{call sp_GetType(?,?)}";
CallableStatement cs = con.prepareCall(storedProc);
cs.setInt(1, tranId);
cs.setInt(2, qualId);
return cs;
}
}, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement > cs) throws SQLException,
DataAccessException {
List<Object> results = new ArrayList<Object>();
cs.execute();
if(cs.getMoreResults())
{
ResultSet rs = cs.getResultSet();
while(rs.next()) //rs has only one record
{
InputStream in = null;
Clob clob = rs.getClob(1);
in = clob.getAsciiStream();
}
rs.close();
}
return results;
}
});
return resultList;
}
I'm using the jtds 1.3.1 driver (I tried connecting using mssql-jdbc but no luck).
Any help is much appreciated.

call procedure with out parameters in hibernate3

I work with hibernate3 and didn't use JPA
I have a procedure in oracle which return 2 out parameter
For test I execute this procedure in oracle with this query.
declare
req_type number;
req_seq number;
begin
insert_req(1111,req_type,req_seq);
dbms_output.put_line('req_type='||req_type);
dbms_output.put_line('req_seq='||req_seq);
end;
Now I want to call this procedure using hibernate
I try with native query without success using this code :
public void insertReq(String numEmp) {
int req_type ;
int req_seq;
String sql = " insert_req(1111,:in1,:in2) ";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("in1", req_type);
query.setParameter("in2", req_seq);
List results = query.list();
System.out.println(req_type);
System.out.println(req_seq);
}
when I have a function I can run it using hibernate using this code as an example :
public void insertOrder(String numEmp) {
String query = "call insert_order(" + numEmp + ",50)";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
sqlQuery.executeUpdate();
}
but the problem is how to call procedure with 2 out parameter using hibernate.
you have to use CallableStatement and registerOutParameter.
you can get a connection from your hibernate session and create the callablestatement.
hibernate does not provide a mecanism to deal with this (at least as i know).
i hope that helps.
Try this and let me know.
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
session.doWork(new Work() {
#Override
public void execute(Connection con) throws SQLException {
// do something useful
try (CallableStatement stmt = con.prepareCall("{call my_sp()}")) {
stmt.execute();
}
}
});
em.close();
Best regards.

Calling a Postgres stored Procedure using Spring + No value specified for parameter

I have a stored procedure defined in PostgresSql as below:
CREATE OR REPLACE FUNCTION update_points(accountId bigint, points numeric(19,5)) RETURNS void AS $$
...
...
$$ LANGUAGE plpgsql;
And I call the following method to call the procedure:
public void updatePoints(final Account account, final BigDecimal points) {
SimpleJdbcCall simpleCall = new SimpleJdbcCall(coreJdbcTemplate).withFunctionName("update_points");
SqlParameterSource inputs = new MapSqlParameterSource()
.addValue("accountId", account.getId())
.addValue("points", points);
simpleCall.execute(inputs);
}
When the method is called, I get following spring error:
org.springframework.dao.DataIntegrityViolationException: CallableStatementCallback; SQL [{? = call update_points()}]; No value specified for parameter 1.; nested exception is org.postgresql.util.PSQLException: No value specified for parameter 1.
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:102)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1137)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1173)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:388)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:348)
at org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SimpleJdbcCall.java:190)
at net.exchangesolutions.veo.dao.AccountTransactionDaoImpl.updateRewardsConsumedAmount(AccountTransactionDaoImpl.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
I tried another way to call the procedure with CallableStatement in which case the function is not called at all.
Do you know what is the problem with the code or have you any suggestion about how to call the procedure from SpringJPA?
Thanks!
EDIT:
This is how I call with CallableStatement:
public void updatePoints(final Account account, final BigDecimal points) {
Connection connection;
try {
connection = coreJdbcTemplate.getDataSource().getConnection();
CallableStatement callableSt = connection.prepareCall("{call update_points(?, ?)}");
callableSt.setLong(1, account.getId());
callableSt.setBigDecimal(2, points);
callableSt.executeUpdate();
} catch (SQLException e) {
}
}
I resolved this problem by using following method. I could not figure out why the two approaches above did not work. Anyway, following solution is working now.
public void updatePoints(final Account account,
final BigDecimal points) {
coreJdbcTemplate.execute(new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con)
throws SQLException {
CallableStatement cs = con
.prepareCall("{call update_points(?, ?)}");
cs.setLong(1, account.getId());
cs.setBigDecimal(2, points);
return cs;
}
}, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs)
throws SQLException {
cs.execute();
return null;
}
});

Java DAO object SQLexception

New to Java and MySQL.
Am using a DAO object to query a table, running via Eclipse. MySQL edited via Workbench. table exists and Getting the following exceptions:
SELECT movie_name, release_dd, release_mm, release_yyyy, duration, language, director, genre, actor_1, actor_2 FROM movie_details_table WHERE movie_name = 'Piku'
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:787)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5206)
at com.library.model.MovieDAO.getMovieDetails(MovieDAO.java:41)
at com.library.model.MovieDetTest.main(MovieDetTest.java:18)
MovieDAO class:
package com.library.model;
import java.util.*;
import java.sql.*;
import java.io.*;
import com.library.model.beans.*;
public class MovieDAO {
private static final String DB_URL =
"jdbc:mysql://localhost/planner";
// Database credentials
private static final String USER = "Sudipto";
private static final String PASS = "sudi85";
public MovieDetails getMovieDetails(String inputMov) throws
SQLException {
MovieDetails movieDetails = new MovieDetails();
try {
//Open a connection
Connection conn = DriverManager.getConnection
(DB_URL,USER,PASS);
//Create and execute query
String queryString = "SELECT movie_name, release_dd, release_mm, release_yyyy, duration, language, director, genre, actor_1, actor_2 FROM movie_details_table WHERE movie_name = '" + inputMov + "'";
System.out.println(queryString);
PreparedStatement statement = conn.prepareStatement
(queryString);
ResultSet rsMovieDetails = statement.executeQuery();
movieDetails.setMovieName(rsMovieDetails.getString
("movie_name"));
movieDetails.setReleaseDate
(rsMovieDetails.getInt ("release_dd"), rsMovieDetails.getInt ("release_mm"), rsMovieDetails.getInt ("release_yyyy"));
movieDetails.setDuration(rsMovieDetails.getInt
("duration"));
movieDetails.setLanguage(rsMovieDetails.getString
("language"));
movieDetails.setDirector(rsMovieDetails.getString
("director"));
movieDetails.setGenre(rsMovieDetails.getString
("genre"));
movieDetails.setActor1(rsMovieDetails.getString
("actor_1"));
movieDetails.setActor2(rsMovieDetails.getString
("actor_2"));
}
catch (SQLException e) {
e.printStackTrace();
}
return movieDetails;
}
}
Have the following error log in MySQL workbench:
2015-05-31T15:04:36, 27, Note, Aborted connection 27 to db: 'planner' user: 'Sudipto' host: 'localhost' (Got an error reading communication packets)
Can anyone please suggest how and what I need to fix?
Use rsMovieDetails.next() to retrive details. Like rs.next() is used in https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html.
rs.next() shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise returns false. If row is present then u should retrieve the data

Error with connection() to Hibernate

I encountered some errors connecting to Hibernate. This gives an error:
public static void makeReport(String type, Map<String, Object> param) throws JRException, IOException{
JasperPrint jasperPrint = null;
**Connection con = HibernateUtil.getSessionFactory().openSession().connection();**error here
String outputFileName = "Hóa đơn ";
JRAbstractExporter exporter = null;
if(type == "7" || type == "8" || type == "9"){
if(type==REPORT_BY_MONTH){
jasperPrint = JasperFillManager.fillReport("data\\Thống kê theo tháng.jasper", param, con);
outputFileName += "thống kê theo tháng " + param.get("#Month") + "-" + param.get("#Year") + ".xlsx";;
}
You can find the code project here.
I think you are trying to generated a JSper report for that you might need JDBC conventional Connection Object.
Are you trying to get JDBC Connection object you use this below code.
public void doWorkOnConnection(Session session) {
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
//use the connection here...
}
});
}
if you are looing for a Connection object just to interact with DB in hibernate way.
Session session - HibernateUtil.getSessionFactory().openSession();//or getSession()
Session object here is kind of wrapper class for JDBC conncetion object. you can sue Session object as Connection convention object JDBC procedure.

Categories