Calling a Stored procedure with SimpleJdbcCall returns null result set from Temp table. The stored procedure have no input and out put paramets - java

I have to call stored procedures From java spring. The procedures doesn't have input and out put parameters. when I call stored procedure using SimpleJdbcCall, it returns null result. How can I fix this Problem? Thank you
Stored Procedure
ALTER PROCEDURE "DBA"."Records" ()
RESULT ( Number integer
, Alias varchar(255)
, File varchar(255)
, ConnCount integer
, PageSize integer
, LogName varchar(255)
)
BEGIN
DECLARE dbid integer;
DECLARE local temporary table t_db_info
( Number integer null
, Alias varchar(255) null
, File varchar(255) null
, ConnCount integer null
, PageSize integer null
, LogName varchar(255) null
) on commit delete rows;
set dbid=next_database(null);
lbl: loop
if dbid is null then
leave lbl
end if
;
insert into t_db_info values(
dbid,db_property('Alias',
dbid),db_property('File',
dbid),db_property('ConnCount',
dbid),db_property('PageSize',
dbid),db_property('LogName',
dbid));
set dbid=next_database(dbid)
end loop lbl
;
select * from t_db_info
ORDER BY alias
END
Java Code
public class Generic <T>{
protected NamedParameterJdbcTemplate namedJdbcTemplate;
protected JdbcTemplate jdbcTemplate;
protected SimpleJdbcCall procReadAllorgs;
public GenericDAO(DataSource ds) {
this.procReadAllorgs = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("DBA.Records")
.returningResultSet("records",
BeanPropertyRowMapper.newInstance(Records.class));
init();
}
}
DAO Impl class
public class OrganDAOImpl implements Generic <T> {
public List getList() {
Map m = procReadAllorgs.execute(new HashMap<String, Object>(0));
return (List) m.get("records");
}
}
Controller class
#RequestMapping("/org")
public class TestController {
#Autowired
protected OrganDAOImpl organDAOImpl;
#RequestMapping(value = "/sunday", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody List getAll() {
logger.debug("calling the controller...");
return OrganDAOImpl.getList();
}
}
Model class
public class Records {
private Integer Number;
private String Alias;
private String File;
private Integer ConnCount;
private Integer PageSize;
private String LogName;
//getter and setter
}

I don't think this procedure returning anything?!
It doesn't have an out parameter to return it, (I am not a plsql expert)
.withProcedureName("Records")
.withCatalogName("DBA")
.withSchemaName(schema);
two cases you will get a null from the DB.
1- if the call is wrong and you don't have exception handling/ try and catch
2- the procedure does not return anything.

Problem: How to get an output param back from simplejdbccall!! I'm using MSSQL Server with Java Spring Framework.
I checked my stored procedure and discovered I forgot to mark the #out_personId variable as output:
ALTER PROCEDURE [dbo].[spNewUser]( #in_firstName nvarchar(20), #in_lastName nvarchar(20),#in_addressLine1 nvarchar(50), #in_addressLine2 nvarchar(50), #in_addressLine3 nvarchar(50), #in_addressLine4 nvarchar(50),#in_dob datetime, #in_gender nvarchar(1), #in_email nvarchar(100), #in_mobileNo nvarchar(50), #in_landLineNo nvarchar(50),#out_personId intoutput)
After this change (in bold) I was able to read the returned int value via SimpleJDBCCall. Here is the code sample:
public Person createPerson(final Person person) {
SimpleJdbcCall storedProcedure = new SimpleJdbcCall(dataSource)
.withProcedureName("spNewUser")
.withReturnValue();
SqlParameterSource params = new MapSqlParameterSource()
.addValue("in_firstName", person.getFirstName())
.addValue("in_lastName", person.getLastName())
.addValue("in_addressLine1", person.getAddressLine1())
.addValue("in_addressLine2", person.getAddressLine2())
.addValue("in_addressLine3", person.getAddressLine3())
.addValue("in_addressLine4", person.getAddressLine4())
.addValue("in_dob", new java.sql.Date(person.getDob().getTime()))
.addValue("in_gender", person.getGender())
.addValue("in_email", person.getEmail())
.addValue("in_mobileNo", person.getMobileNo())
.addValue("in_landLineNo", person.getLandLineNo())
.addValue("out_personId", 0);
Map<String, Object> output = storedProcedure.execute(params);
Integer id = (Integer) output.get("out_personId");
person.setId(id);
return person;
}

Related

How to use criteria Query filter in azure cosmos DB

I am trying to use Criteria Query for Azure cosmosDB , but I am getting blank return everytime. I am trying to pass a model which will contain 5 parameters and some of them will be null while passing the model to the request method , here is the code which i am trying to use
Map map = new Map();
if(p.getA()!=null || p.getB() !=null || p.getC()!=null || p.getD()!=null){
map.put(p.getA()); //any of them can be null while passing
map.put(p.getB());//any of them can be null while passing
map.put(p.getC());//any of them can be null while passing
map.put(p.getD());//any of them can be null while passing
}
Criteria criteria = Criteria.getInstance(CriteriaType.ARRAY_CONTAINS,"TableA",Collections.singletonList(map),Part.IgnoreCaseType.ALWAYS);
CosmosQuery cosmos = new CosmosQuery(criteria).with(Sort.unsorted());
Iterable<BaseTable> items = cosmosTemplate.find(cosmos,BaseTable.class,"TableA");
Now this BaseTable contains all the table fields and TableA is extending that
public class TableA extends BaseTable{
}
BaseTable
public class BaseTable{
#Id
public String id;
public String A;
public String B;
public String C;
...............
}
Can anyone please tell me why every time i am getting null in the items, what is missing in the Criteria.

Mybatis get clob field

We want to get a clob field in a annotation based call to a oracle function. This function return a CLOB field Oracle.
We have this code:
#Select("{ #{result, javaType=java.lang.String ,jdbcType = CLOB, mode=OUT } = call pkg_exportacion_datos.f_recupera_dgp_pac( "
+ "#{cipAuto, jdbcType=VARCHAR, mode=IN},#{idExplotacion, jdbcType=NUMERIC, mode=IN} )}")
#Options(statementType = StatementType.CALLABLE)
#Results(
value = {
#Result(
property = "result",
column = "result",
javaType = String.class)
})
String getListadoDGPPaciente(String cipAuto,long idExplotacion,String result);
We can debug in ClobTypeHandler on method private String toString(Clob clob) throws SQLException and inside this method field CLOB has a valid value, but this value not return inside variable result.
Inside variable resul set a null value.
Can anybody help me?
Thanks.
The method should look as follows:
#Update({
"{#{result,javaType=java.lang.String,jdbcType=CLOB,mode=OUT}",
"= call pkg_exportacion_datos.f_recupera_dgp_pac(",
"#{cipAuto,jdbcType=VARCHAR,mode=IN},",
"#{idExplotacion,jdbcType=NUMERIC,mode=IN}",
")}"
})
#Options(statementType = StatementType.CALLABLE)
void getListadoDGPPaciente(ParamBean param);
Note that the result is returned as an OUT parameter, not the method return value.
So, you should use #Update or #Insert instead of #Select.
And to receive the OUT parameter, the method parameter must be a Map or a bean like the following.
public class ParamBean {
private String cipAuto;
private long idExplotacion;
private String result;
// getters / setters
}
The code that calls the method would look as follows.
ParamBean param = new ParamBean();
param.setCipAuto("foo");
param.setIdExplotacion(123L);
mapper.getListadoDGPPaciente(param);
return param.getResult(); // returns the CLOB as a String

jdbc.update succed in database, but keyholder no content return

this is my code
private long saveTacoInfo(Taco taco) {
taco.setCreatedAt(new Date());
PreparedStatementCreator psc =
new PreparedStatementCreatorFactory(
"insert into Taco (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(
Arrays.asList(
taco.getName(),
new Timestamp(taco.getCreatedAt().getTime())));
KeyHolder keyHolder = new GeneratedKeyHolder();
int res = jdbc.update(psc, keyHolder);
log.info("res " + res);
return keyHolder.getKey().longValue();
}
after debugging, found keyHolder.getKey() return null, because GeneratedKeyHolder keyList is empty!
any suggestions?
this is my Taco table sql:
create table if not exists Taco (
id identity,
name varchar(50) not null,
createdAt timestamp not null
);
the Insert statment is execute ok! h2 database has the data. but keyHolder.getKey is null.
I ran into the same problem as you. Apparently, you used the example from the book "Spring in action".
It seems that the problem in the code, namely in the "PreparedStatementCreatorFactory" class, the "returnGeneratedKeys" field is set to false.
I do not know why the example works in the book or why it is not specified that the variable needs to be changed. The value of this variable, according to Github, has not changed since 2008.
Here is a piece of class code:
public class PreparedStatementCreatorFactory {
/** The SQL, which won't change when the parameters change. */
private final String sql;
/** List of SqlParameter objects (may not be {#code null}). */
private final List<SqlParameter> declaredParameters;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
private boolean updatableResults = false;
private boolean returnGeneratedKeys = false;
#Nullable
private String[] generatedKeysColumnNames;
The problem is solved by setting the value of the "returnGeneratedKeys" field to true. Something like this:
var preparedStatementCreatorFactory = new PreparedStatementCreatorFactory(query, Types.VARCHAR, Types.TIMESTAMP);
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);
PreparedStatementCreator preparedStatementCreator =
preparedStatementCreatorFactory
.newPreparedStatementCreator(Arrays.asList(users.getName(), users.getCreateDateTime()));

Postgres: Calling function from spring jdbc template

What is the correct way to call postgres function with custom types from the spring StoredProcedure?
Say I have a function and custom types as defined:
CREATE OR REPLACE FUNCTION addUser(user IN O_USER) RETURNS VOID
AS
$$
BEGIN
end;
$$ language plpgsql;
CREATE TYPE O_USER AS (
id NUMERIC,
name VARCHAR(50)
);
While calling it from Spring I am converting user object to String as shown below:
public class AddUserProcedurePostgres extends StoredProcedure {
public AddUserProcedurePostgres(DataSource dataSource) {
super(dataSource, "addUser");
setFunction(true);
declareParameter(new SqlParameter("i_User", Types.OTHER, "O_USER"));
compile();
}
public void execute(SessionContext sessionContext, Dashboard dashboard) {
Map<String, Object> input = new HashMap<>();
input.put("i_User", "(1,Vishal)");
execute(input);
}
}
Now my questions are:
Is it the right way to create a String corresponding to the object and then pass it? Or is there any better way?
Suppose I need to add array of other custom type in the existing O_USER, then how the string need to be formatted?
CREATE TYPE O_USER AS (
id NUMERIC,
name VARCHAR(50)
addresses O_ADDRESS[]
);

Calling stored procedure using OUT parameter with Spring Spring JPA 2.*

I am calling a stored procedure using IN parameter - it's working fine.
public interface ABCRepository extends JpaRepository<ABC, Integer> {
#Query(nativeQuery=true, value="exec p_NextSequence :clazName , 1")
Integer callSequenceForClaz(#Param ("clazName")String clazName);
}
Need help how to do it for OUT parameters.
Refer below link for how to call a stored procedure.
https://dzone.com/articles/calling-stored-procedures-from-spring-data-jpa
Simply define method annnotating it with Stored Procedure name, Map input param of stored Procedure with method parameters, Map output param of SP as the return type of the method, Example.
#Repository
public interface EmployeeJPA extends JpaRepository<Employee, Long> {
#Procedure(procedureName = "enroll_employee_program")
public String enrollEmpProgram(Long employeeId, Long programId, LocalDate createdDate, String createdBy);
}
You can use #Procedure used on a repository
#Procedure(procedureName="SP_MP_LOG_CONSULTA",outputParameterName="response")
int called(#Param("name") name);
I had to use the outputParameterName --> cause it was giving me an out undefined column error.
Encontre este ejemplo que me funciono, saludos
#Procedure(procedureName = "con_nombreSP", outputParameterName = "out_parameter")
public double nameMethod (#Param ("in_param") double param,
#Param ("in_param2") double param2,
#Param ("in_param3") int param3);

Categories