How does Spring Data's findBy decide which database record to return if there are multiple matches?
I realised if I have more than one entry in my Elastic Search database with the same attribute code (ie: "123"), Spring only returns one entry when I call a 'findByAttributeCode'.
If I use a findById, its self explanatory as Id's are unique, however with other findBys, there can be many matches. Note: attributeCode is NOT unique.
How does Spring decide which one to return?
My call would be something like this:
Attribute attribute = findByAttribute(attributeCode);
The repo would look like this:
public interface AttributeRepository extends ElasticsearchRepository<Attribute, String> {
Attribute findByAttributeCode(String attributeCode);
}
This is taken from the return type that you define for your function. If you specify a collection, all matching documents are returned for your query.
If you define a single object as return type, the first entry returned from the underlying store - here Elasticsearch - is returned. What this first entry is, depends on your query criteria, sort parameters - whatever Elasticsearch returns first, is returned to the caller.
What you should be doing, if there are more than one possibility is creating the method stub like this:
<Iterable>Attribute findByAttributeCode(String attributeCode);
This way you return them all. If you don't do that, you are beholden to the RDBMS in how it builds it swap to return a single entry from the multiple tuples it will return from the query it builds, which should be something like:
select * from table where attributeCode = ?;
I'm using Spring JPA named querys in my repository. My problem is, that I can't find anywhere information what would be returned value for a query that wouldn't match any results. I assume it'll be null for findOne() but I have no idea what would it be for findAllByName() function.
Does anyone know from his/her experience or know a place in documentation?
From my little and personal experience, if you search for an object on your repo, for example by Id or Name the named query method returns an object of type T, but if no results are found from your repo, it will return null.
Methods that can return more than one element, will produce an empty collection List<T>(not null).
Some documentation here:
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
Appendix D: Repository query return types
Supported query return types
Query return types:
T An unique entity. Expects the query method to
return one result at most. In case no result is found null is
returned. More than one result will trigger an
IncorrectResultSizeDataAccessException.
Iterator An Iterator.
Seems like only when return type is of type T is the only one that specify a null is returned if no matches.
If there is only one record matching the query ,then query.list() will only return one record.Then what is the use of query.uniqueResult()? because in case there are more than one record matching the query it would throw NonUniqueResultException.What is use of this method?
As documentation states:
Convenience method to return a single instance that matches the query, or null if the query returns no results.
Returns:
the single result or null
Throws:
NonUniqueResultException - if there is more than one matching result
So if you are sure that only one result is going to be returned, then you can use this convenience method to obtain directly the result instead of a list (and so avoiding the verbose use of result.get(0)). If you failed in your suposition of uniqueness then the exception is thrown.
You can use query.uniqueResult() if you are sure you get only one record. For instance when you search for a unique identifier.
If you do something like
select * from person where id =1
you can use query.uniqueResult() because you get only one or zero records.
If you do somethink like
select * from person where name = 'Jens'
you have to use query.list() because you can get more than one record.
i have below code snippet in dao
String GET_CUSTOMER="SELECT * from customer where custName=:custName"
Session session = getHibernateUtil().getSession();
SQLQuery query = session.createSQLQuery(GET_CUSTOMER);
query.setParameter("custName", custName);
query.setResultTransformer(Transformers
.aliasToBean(Customer.class));
Customer custData = (Customer) query
.uniqueResult();//line
Customer table has some int columns for which some values as null. Now at line1 i get error
Null value was assigned to a property of primitive type setter of Customer.Address
Is there a way in hibernate/query/Transformer to convert the null values to 0 automatically?
I have just mentioned one table i.e customer but there are various joined table which contains int value as null in various columns so i do
not want to handle in query for each table.
UPDATE:- Customer is not Hibernate entity. It pojo with instance fields of int type
Customer table has some int columns for which some values as null.
In that case I'd recommend making them Integer fields instead. While you could probably get Hibernate to coalesce NULL to 0 (although possibly not in an easy global manner), it's not really mapping your data effectively - why would you want to lose information like that?
I don't know about Hibernate transformers, but I have a different idea. Can you change the database? You could make the column not nullable and with default value 0. That way all possible values you can store in the database can be mapped to the int primitive.
What is the datatype for NULL when passing that value for no data into a database?
There is NO data type of NULL. NULL itself means ABSENCE of data. When there is no data, how can it have type?
Null does not have a specific data type in SQL. Any nullable column or variable can contain null. Null is never equal or unequal to anything. You can cast a variable holding null to another variable and get null, for example:
declare #a integer
set #a = null
select convert (float, #a)
----------------------
NULL
(1 row(s) affected)
Usually NULL is its own datatype - the type of 1 is "INTEGER", the type of the type of NULL is "NULL"
Datatype for NULL is as meaningless as datatype for 0: it can be INTEGER, FLOAT or a VARCHAR. You cannot tell it just from the value.
NULL is legitimate value in almost every datatype domain, which means the absence of actual value.
It's also meaningless to discuss datatypes out of context of certain RDBMS.
In SQLite, for instance, datatypes are value-bound, not column-bound, and NULL is a first-class datatype per se.
In Oracle, the datatypes are more strictly defined. For instance, this query works:
SELECT COALESCE(dt, i)
FROM (
SELECT CAST(NULL AS DATE) AS dt, CAST(NULL AS DATE) i
FROM dual
) q
and this does not:
SELECT COALESCE(dt, i)
FROM (
SELECT CAST(NULL AS DATE) AS dt, CAST(NULL AS NUMBER) i
FROM dual
) q
, because the latter query returns two columns of different datatypes, both of them having values of NULL, and COALESCE requires both arguments to have same datatype.
It's better to say that a NULL of any datatype can be implicitly converted to a NULL on another datatype.
For instance, a VARCHAR can be implicitly converted to a INTEGER if it has value of 0, but cannot if it has value of 'some_string'.
For NULL's, any datatype can be implicitly converted to any other datatype, if the implicit conversion between them is allowed at all.
In SQL a NULL is a "mark" (something other than a value) that can apply to any SQL type. So it is orthogonal to type.
NULL is the value for 'undefined'. So any type in a database can be 'undefined', as it's a property of the column: a value of a row for the specific column can be 'undefined' which means it's 'NULL', no matter what the type is. As long as the column is nullable.
I think DBNULL or NULL is a special type.
I think the question defeats itself. If NULL had a datatype, wouldn't you be forced to change it with every instantiation outside of its default. For example, when you create it as a character, but then force it into an object's value?
NULL==NULL
That is all.
Actually, in PowerShell comparing $null -eq $null gives False.
Also, -not $null will give you True, so here it seems to be reprezented as False. I know, PowerShell might not be a good example, but still :)
Usually SQL NULL does not have a type associated with it. However there are exceptions. Database engines postgresql and derby (javadb) require that null has a type. In other words they do not support untyped null. So query conditions like NULL IS NULL may fail. Here, NULL must be given a type, the expected type of the target that processes the NULL value. In this case this appears silly because there is no target and this can be counterproductive.
See CAST function: -- you must cast NULL as a data type to use it
See Queries with guarded null Parameter fail and Add support for setObject(arg, null)
Please vote for these issues so that the odd database engines change their ways.
Prabhahar, each type of database driver has its own way of handling NULL. You will have to examine the driver API for the specific database.
For example if you are using the Java Derby database, simply pass in the Java native type, null as shown in Ian Bjorhovde's answer to "Derby's Handling of NULL Values":
insert into T_AUTHOR (
ID, FIRST_NAME, LAST_NAME,
DATE_OF_BIRTH, YEAR_OF_BIRTH, ADDRESS)
VALUES (
1000, 'Lukas', 'Eder',
'1981-07-10', null, null
);
Here is another null example of JDBC:Inserting null to Integer column:
pst.setNull(4, java.sql.Types.INTEGER);
http://en.wikipedia.org/wiki/Null_(SQL)
NULL can be cast (converted) to any data type yet data type comparisons with NULL always return FALSE.