what is this following error about in spring rest webservice api? - java

I'am creating a restapi , i am using java spring and i'am getting the following error.
Error:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
My daoImpl class
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ?
and password=?";
String name =null;
try{
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{
vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
}catch(Exception e){
e.printStackTrace();
}
return name;
}
my controller
#RequestMapping(value = Constants.REQ_MAP_LOGIN,
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public String vendorloginMethodPost(#RequestBody VendorLogin vendoridlogin) {
String message = Constants.EMPTY_STRING;
String id = dao.getLoginDetails(vendoridlogin);
String password = dao.getLoginDetails(vendoridlogin);
if (id == null && password==null) {
message = "login FAIL";
}else{
message =" login Successfully";
}
return message;
}

SOLUTION
#Override
public String getLoginDetails(VendorLogin vendorlogin) {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
try {
name = (String) jdbcTemplate.queryForObject(
getVendorData,
new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()},
new RowMapper<YourVendorObject>() {
public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException {
// we suppose that your vendor_ID is String in DB
String vendor_ID = rs.getString("vendor_ID");
// if you wanna return the whole object use setters and getters
// from rs.getInt ... rs.getString ...
return vendor_ID;
}
});
return name;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
public class EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException
Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned.
The problem is, Spring throws an EmptyResultDataAccessException, instead of returning a null when record not found :
JdbcTemplate .java
package org.springframework.jdbc.core;
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
//...
public <T> T queryForObject(String sql, Object[] args,
RowMapper<T> rowMapper) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
return DataAccessUtils.requiredSingleResult(results);
}
DataAccessUtils.java
package org.springframework.dao.support;
public abstract class DataAccessUtils {
//...
public static <T> T requiredSingleResult(Collection<T> results)
throws IncorrectResultSizeDataAccessException {
int size = (results != null ? results.size() : 0);
if (size == 0) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, size);
}
return results.iterator().next();
}
check it here : source

try {
String getVendorData = "select vendor_ID from vendor_login where vendor_ID= ? and password=?";
String name =null;
name = (String) jdbcTemplate.queryForObject(getVendorData,new Object[]{vendorlogin.getVendorLoginId(), vendorlogin.getPassWord()}, String.class);
} catch (EmptyResultDataAccessException e) {
return null;
}

Related

BeanUtils.setProperty method sets null a BigDecimal field

I'm having a problem using the BeanUtils.setProperty method.
I'm using this JAR:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
I run a MySQL query that returns one record and I'm mapping the resultset to a JavaBean that I've made.
Here you have the main class.
public class QueryTester {
public static void viewTable(Connection con) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
Statement stmt = null;
String query = "SELECT * FROM Books WHERE code = 'AA00'";
try {
stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMapper<Books> rsMapper = new ResultSetMapper<Books>();
List<Books> list = rsMapper.mapResultSetToObject(rs, Books.class);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost/dbname";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = (Connection) DriverManager.getConnection(url,userName,password);
viewTable(conn);
conn.close();
} catch (Exception e) {
System.out.println("NO CONNECTION");
}
}
}
And this is the method that uses the BeanUtils.setProperty method.
public class ResultSetMapper<T> {
public List<T> mapResultSetToObject(ResultSet rs, Class<T> outputClass) throws InstantiationException, SQLException, IllegalAccessException, InvocationTargetException {
List<T> outputList = new ArrayList<T>();
if (rs == null) {
return outputList;
}
if (!outputClass.isAnnotationPresent(Entity.class)) {
throw new InstantiationException("Entity notation not present.");
}
ResultSetMetaData rsmd = rs.getMetaData();
// retrieve data fields from output class
Field[] fields = outputClass.getDeclaredFields();
while (rs.next()) {
T bean = (T) outputClass.newInstance();
for (int iterator = 0; iterator < rsmd.getColumnCount(); iterator++) {
String columnName = rsmd.getColumnName(iterator + 1);
Object columnValue = rs.getObject(iterator + 1);
for (Field field : fields) {
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
BeanUtils.setProperty(bean, field.getName(), columnValue);
break;
}
}
}
}
outputList.add(bean);
}
return outputList;
}
}
mapResultSetToObject method returns a List with one element that is correct but the bean is set in a wrong way.
The fields code and bookDescription are set right but kPrice field is set null instead of 3.000 that is the value from database.
I run this code in debug mode and "columnValue" variable's value is 3.000 but the setProperty method doesn't set the right value and the value remains null.
Here you have my Java Bean.
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
/* Getters and setters */
...
}
And this is the MySQL table and the record.
CREATE TABLE `Books` (
`code` varchar(4) NOT NULL,
`book_description` varchar(50) NOT NULL DEFAULT '',
`kPrice` decimal(10,4) NOT NULL DEFAULT '1.0000',
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO dbname.Books (code, book_description, kPrice) VALUES('AA00', 'Description example', 3.0000);
Why I get this behaviour? What am I missing?
Thanks in advance
Are you sure which the name of setters/getters is the same of property?
In some case, the problem is that.
See my example below:
#Entity
public class Books {
#Column(name="code")
private String code;
#Column(name="book_description")
private String bookDescription;
#Column(name="kPrice")
private BigDecimal kPrice;
public Books() {}
public Books(String code, String bookDescription, BigDecimal kPrice){
this.code = code;
this.bookDescription = bookDescription;
this.kPrice = kPrice;
}
public void setKPrice ( Bigdecimal kPrice) // and not setkPrice or setPrice..
{
this.kPrice = kPrice;
}
public BigDecimal getKPrice () // and not getkPrice or getPrice..
{
return this.kPrice;
}
}

Why does this REST-service not return while the other does?

SITUATION
In the code below you can see 2 REST services which both should return a MessageVO. The first service (serviceThatDoesWork) returns a MessageVO as excpected, but the second service (serviceThatDoesNotWork) refuses to, it doesn't even give any output at all.
However returning a Response (java.ws.rs.core.Response) with serviceThatDoesNotWork does give an output. Even when I skip the 'doStuff'-methods and create a dummy-MessageVO that is exactly the same for each service, the 2nd one doesn't return anything.
QUESTION
Why does the 2nd service fail to return a MessageVO? It doens't return anything when I try returning a MessageVO, and nothing out of the ordinary appears in the logging.
The two services need to return exactly the same kind of thing but still one of them doesn't want to return anything, what am I not seeing here?
Could it be because of the path (and/or the amount of parameters)?
CODE
MyServices.java:
#Path("/myService")
...
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/myPath/{param1}/{param2}/{param3}")
public MessageVO serviceThatDoesWork(#PathParam("param1") Integer param1_id, #PathParam("param2") Integer param2_id, #PathParam("param2") Integer param2_id)
{
List<SomethingVO> lstO = MyRestServiceBusiness.doStuff(param1_id, param2_id, param3_id);
//return SUCCESS or FAIL message
MessageVO msg = new MessageVO();
if(lstO.size() > 0)
{
List<String> s = new ArrayList<String>();
for(SomethingVO k : lstO)
{
s.add(k.getId().toString());
}
msg.setItem_ids(s);
msg.setMsg("SUCCESS");
}
else
{
msg.setMsg("FAIL");
}
return msg;
}
...
#GET
#Path("/myPath/{param1}/{param2}/{param3}/{param4}/.../{param15}{a:(/a/[^/]+?)?}{b:(/b/[^/]+?)?}")
public Response serviceThatDoesNotWork(#PathParam("param1")Integer param1_id, ..., #PathParam("param15") Integer param15_id,
#PathParam("a") String a_id, #PathParam("b") String b_id)
{
//PUT 'OPTIONAL' PARAMS IN A LIST
List<Integer> lstI = new ArrayList<Integer>();
String aId = a_id != null ? a_id.split("/")[2] : null;
String bId = b_id != null ? b_id.split("/")[2] : null;
if(aId != null)
{
lstI.add(Integer.parseInt(aId ));
}
if(bId != null)
{
lstI.add(Integer.parseInt(bId ));
}
//DO STUFF
String afsId = "";
if(lstI.size() > 0)
{
afsId = MyRestServiceBusiness.doStuff(param1, ..., lstI);
}
//return SUCCESS or FAIL message
MessageVO msg = new MessageVO();
if(afsId != null && !afsId.isEmpty())
{
List<String> s = new ArrayList<String>();
s.add(afsId);
msg.setItem_ids(s);
msg.setMsg("SUCCESS");
}
else
{
List<String> s = new ArrayList<String>();
for(Integer i : lstI)
{
s.add(i.toString());
}
msg.setItem_ids(s);
msg.setMsg("FAIL");
}
//WENT THROUGH ALL ABOVE CODE AS EXPECTED, MESSAGEVO HAS BEEN FILLED PROPERLY
return msg;
}
CODE MessageVO.java:
#XmlRootElement
public class MessageVO
{
private String msg;
private List<String> item_ids;
//GETTERS
#XmlElement(name = "Message")
public String getMsg() {
return msg;
}
#XmlElement(name = "Item ID's")
public List<String> getItem_ids() {
return item_ids;
}
//SETTERS
public void setMsg(String msg) {
this.msg = msg;
}
public void setItem_ids(List<String> item_ids) {
this.item_ids = item_ids;
}
If I need to provide extra information please ask, this is my first attempt at (REST-) services.
As Vaseph mentioned in a comment I just forgot the #Produces annotation in the 2nd service.

Map Object containing an other object using java reflection

I try to map an object in my database.
It works fine for simple type like int, string ect... However i got a problem about a class containing an other object.
For example i got a class order :
public class order
{
int id;
Client c;
public int getId();
public void setId(int id);
}
and a class client :
public class Client
{
int id;
//some stuff like name ect and getter/setter...
}
I would like to map order by getting client id.
The problem is that when i try to get the package name of field Client it return me java.lang (package of field class...)
field.getType().getClass().getPackage().getName().compareTo("fr.javatp.model") == 0
I don't know why it doesn't return the type Client...
Any clue ?
this is code :
public void insertObject(Object instance) throws SQLException,
SecurityException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException
{
Connection connection = null;
PreparedStatement preparedStatement = null;
this.type = instance.getClass();
this.query = createInsertQuery();
try
{
try
{
connection = this.getConnexion();
}
catch (Exception e)
{
e.printStackTrace();
}
preparedStatement = connection.prepareStatement(query);
int i = 0;
Class clazz;
for (Field field : type.getDeclaredFields())
{
System.out.println("PACKAGE NAME : " + field.getType().getClass().getPackage().getName());
if (field.getType().getClass().getPackage().getName().compareTo("fr.javatp.model") == 0)
clazz = field.getType();
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
field.getName(), type);
Method method = propertyDescriptor.getReadMethod();
Object value = method.invoke(instance);
preparedStatement.setObject(++i, value);
}
preparedStatement.addBatch();
preparedStatement.executeBatch();
}
finally
{
connection.close();
preparedStatement.close();
}
}
and create Insert query code :
private String createInsertQuery()
{
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append("(");
sb.append(this.getCol(false));
sb.append(")");
sb.append(" VALUES (");
sb.append(this.getCol(true));
sb.append(")");
System.out.println("QUERY TO SEND : " + sb.toString());
return sb.toString();
}
and get Col code :
private String getCol(boolean usePlaceHolders)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Field f : this.type.getDeclaredFields())
{
// System.out.println("PACKAGE NAME : " + f.getType().getClass().getName());
if (first)
first = false;
else
sb.append(",");
if (usePlaceHolders)
sb.append("?");
else if (f.getType().getClass().getPackage().getName().compareTo("fr") == 0)
{
sb.append(f.getName() + ".id");
}
else
sb.append(f.getName());
}
return sb.toString();
}
The problem is this expression:
field.getType().getClass().getPackage()
Field.getType() returns the Class object of the field you are interested in. By calling getClass() on it, you are getting the class object of Class, which is java.lang.Class.class. So instead just use
field.getType().getPackage()
Have you thought about using an existing ORM instead of reinventing the wheel?

How to intercept and change sql query dynamically in mybatis

I use mybatis to perform sql queries in my project. I need to intercept sql query before executing to apply some changed dynamically. I've read about #Interseptors like this:
#Intercepts({#Signature(type= Executor.class, method = "query", args = {...})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
And it really intercepts executions, but there is no way to change sql query since appropriate field is not writable. Should I build new instance of whole object manually to just replace sql query? Where is the right place to intercept query execution to change it dynamically? Thank.
I hope it will help you:
#Intercepts( { #Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class
})
})
public class SelectCountSqlInterceptor2 implements Interceptor
{
public static String COUNT = "_count";
private static int MAPPED_STATEMENT_INDEX = 0;
private static int PARAMETER_INDEX = 1;
#Override
public Object intercept(Invocation invocation) throws Throwable
{
processCountSql(invocation.getArgs());
return invocation.proceed();
}
#SuppressWarnings("rawtypes")
private void processCountSql(final Object[] queryArgs)
{
if (queryArgs[PARAMETER_INDEX] instanceof Map)
{
Map parameter = (Map) queryArgs[PARAMETER_INDEX];
if (parameter.containsKey(COUNT))
{
MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = ms.getBoundSql(parameter).getSql().trim();
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
getCountSQL(sql), boundSql.getParameterMappings(),
boundSql.getParameterObject());
MappedStatement newMs = copyFromMappedStatement(ms,
new OffsetLimitInterceptor.BoundSqlSqlSource(newBoundSql));
queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
}
}
}
// see: MapperBuilderAssistant
#SuppressWarnings({ "unchecked", "rawtypes" })
private MappedStatement copyFromMappedStatement(MappedStatement ms,
SqlSource newSqlSource)
{
Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms
.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
// setStatementTimeout()
builder.timeout(ms.getTimeout());
// setParameterMap()
builder.parameterMap(ms.getParameterMap());
// setStatementResultMap()
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
String id = "-inline";
if (ms.getResultMaps() != null)
{
id = ms.getResultMaps().get(0).getId() + "-inline";
}
ResultMap resultMap = new ResultMap.Builder(null, id, Long.class,
new ArrayList()).build();
resultMaps.add(resultMap);
builder.resultMaps(resultMaps);
builder.resultSetType(ms.getResultSetType());
// setStatementCache()
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
private String getCountSQL(String sql)
{
String lowerCaseSQL = sql.toLowerCase().replace("\n", " ").replace("\t", " ");
int index = lowerCaseSQL.indexOf(" order ");
if (index != -1)
{
sql = sql.substring(0, index);
}
return "SELECT COUNT(*) from ( select 1 as col_c " + sql.substring(lowerCaseSQL.indexOf(" from ")) + " ) cnt";
}
#Override
public Object plugin(Object target)
{
return Plugin.wrap(target, this);
}
#Override
public void setProperties(Properties properties)
{
}
}
You may consider using a string template library (eg Velocity, Handlebars, Mustache) to help you
As of to date, there is even MyBatis-Velocity (http://mybatis.github.io/velocity-scripting/) to help you to do scripting for the sql.
Depending on the changes you want to make, you may want to use the dynamic sql feature of mybatis 3

How to call Java object from CDI bean

I have a CDI bean with Java object which I use to display profile data from Database:
Parent Bean
#Named("DCProfileTabGeneralController")
#ViewScoped
public class DCProfileTabGeneral implements Serializable
{
public DCObj dc;
public class DCObj
{
private int componentStatsId; // COMPONENTSTATSID NUMBER(38,0)
........
// Default Constructor
public DCObj(){};
public DCObj(int componentStatsId....)
{
this.componentStatsId = componentStatsId;
.......
}
public int getComponentStatsId()
{
return componentStatsId;
}
public void setComponentStatsId(int componentStatsId)
{
this.componentStatsId = componentStatsId;
}
....
}
// Getters ------------------------------------------------------------------------------------
public DCObj getdcData()
{
return dc;
}
#PostConstruct
public void initData() throws SQLException
{
initDBData();
}
// Generate data Object from Oracle
public void initDBData() throws SQLException
{
dc = new DCObj(result.getInt("COMPONENTSTATSID"),
.........
}
}
Validator
#Named("ValidatorDatacenterController")
#ViewScoped
public class ValidatorDatacenter implements Validator, Serializable
{
public ValidatorDatacenter()
{
}
#Inject
private DCProfileTabGeneral profileTabGeneral;
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
int componentStatsId = -1;
if (profileTabGeneral != null)
{
DCObj dcData = profileTabGeneral.dc;
if (dcData != null)
{
componentStatsId = dcData.getComponentStatsId();
}
}
if (componentStatsId == -1)
{
return;
}
String l;
String s;
if (value != null && !(s = value.toString().trim()).isEmpty())
{
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int resComponentStatsId = -1;
try
{
conn = ds.getConnection();
// if componentsstatsid <> edited componentstatsid in jsf -> throw validator exception
ps = conn.prepareStatement("SELECT componentstatsid from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
resComponentStatsId = rs.getInt(1);
}
if (resComponentStatsId != -1 && resComponentStatsId != componentStatsId)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" This field cannot be empty!", null));
}
}
}
I have a custom validator which checks the input values from the profile page into the Database. I tested to get the Java object from the parent page using #Inject and to pass the Ojject to the validator. It turns out that I get empty Java object every time when I use #Inject.
I also tested to get Int using CDI. It works but when I again tested to get the Java Object again I get empty Object.
Can you tell me what is the proper way to call a Java Object from CDI bean? Why I cannot get Java object from CDI bean?
If I recall correctly CDI injection will not work with a validator. Use advanced from Myfaces CODI as the JSF-module from deltaspike is not ready yet. https://cwiki.apache.org/EXTCDI/jsf-usage.html
Or go for deltaspike and use the BeanProvider to get your instance.
BeanProvider.getContextualReference(DCProfileTabGeneral .class, false);

Categories