The 'duplicate entry... for key...' error message would be self-explanatory, were it not occurring during a SELECT statement rather than an INSERT.
Here is the statement: SELECT DISTINCT e FROM EmailAddress e WHERE e.email = :email
Here is the full code block:
TypedQuery<EmailAddress> query = this.getEntityManager().createQuery(
"SELECT DISTINCT e FROM EmailAddress e WHERE e.email = :email", EmailAddress.class);
query.setParameter("email", email);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
I'm using Hibernate with Spring. My guess is that it's something to do with the way Hibernate handles transactions. There must be something going on that I'm unaware of, because I don't think that this query alone should throw this error. However the error is definitely thrown when this query is executed.
Am I right in thinking that this must only occur during an INSERT?
If I remove this query from the path of execution, everything works fine until an insert is attempted. Then the same error is thrown.
Perhaps there is something wrong with my entities before the SELECT is executed?
If it's any help, the key in this case is a non-primary composite key residing in a join table between users and email address tables.
Related
I am trying to update a field on a table the query needs to get the value from a 2nd table and use that to get the data from a 3rd table. I keep getting the "ORA-01427: single-row subquery returns more than one row" Any help is appreciated.
update ord_detail set cuser1 = (select c.email from contact c,ord_detail m join orders o on o.ID = m.orders_ID where c.email is not null)
where EXISTS (select email from contact,orders where orders.contact_id2 = contact.id)
Since you did not provide further information like the results of your sub selects, it's not 100% clear what exactly is your problem. You should check those results and if this does not answer your question, please provide the details.
My guess is that this sub query will give multiple rows because you are missing a join from the table "contact" to one of the other tables:
select c.email from contact c,ord_detail m
join orders o on o.ID = m.orders_ID where c.email is not null
Therefore, this sub query will always lead to many rows as result unless the table "contact" contains one row only whose column email is not null.
Below query works fine for Oracle database, but for Db2 it throws error sqlcode -417.
I have looked up similar problems but did not get any definitive answer:
#Query(value = "select * from tableName f where (aC is null or f.a_c = aC)", nativeQuery = true)
Page<tablename> findByFilters(String aC, Pageable pageable);
On execution the error code is -417
One way to solve this problem would be to rewrite the query as the following:
select * from tableName f where f.a_c = coalesce(aC, f.a_c)
The form of query above is likely to be accepted. In order to find out the exact reason of the error you get, it is necessary to trace the actual SQL statement passed to Db2.
Another option of solving the problem may be to add the CAST operator, which would define the data type of your parameter:
select * from tableName f where (cast(aC as integer) is null or f.a_c = aC)
This is suggested in the description of the error you get
I have the following named query
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query = "SELECT new com.foobar.UserFlightDetails(uf.flight.divertedAirport, uf.flight.number) " +
"FROM UserFlight uf WHERE uf.user.id=?1 AND uf.flight.id=?2")
The UserFlightDetails constructor is as follows
public UserFlightDetails(Airport airport, String flightNumber) {
this.setDivertedAirport(airport);
this.setFlightNumber(flightNumber);
}
divertedAirport is a foreign key in the flight table, path=(uf.flight.divertedAirport)
My problem is when divertedAirport is null (it's a nullable foreign key), my HQL query returns null as the result (The code doesn't even trigger the constructor above), so I don't get the flightNumber which is never null.
If the divertedAirport isn't null, I get both the airport and the flight number fine (and the above constructor gets executed just fine).
What could be causing this and how could I resolve it? I tried some null functions like nullif and coalesce but nothing helped.
I'm using spring boot 1.2.7, hibernate-core 4.3.11.Final
Probably, the problem is the uf.flight.divertedAirport. This expression do a JOIN between flight and divertedAirport but, as you say, divertedAirport is a fk and can be null.
So, you need to use the LEFT JOIN.
I would rewrite your query like this:
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query =
"SELECT new com.foobar.UserFlightDetails(divertedAirport, flight.number)
FROM UserFlight uf
JOIN uf.flight flight
LEFT JOIN flight.divertedAirport divertedAirport
JOIN uf.user user
WHERE user.id = ?1 AND flight.id = ?2 ")
I remove the references like uf.user.id for a explicit JOIN (JOIN uf.user user plus user.id), because is more legible and this kind of problem that generated your question is more easy to find using this way to write JPQL queries.
Using entity framwork with lazy loading - Have the following question on loading related entities when the entities
are null.
Say I have two tables employee and employeedetails. Assume in the above case not all employee entries have an entry in the employeedetails table.
If I want to look up a list of Employees
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails.Address
}).ToList();
EmployeeEntity is the data class into which we stuff the results.
The above code breaks if even one employee in the returned list
does not have a entry in table employeedetails. This is obvious since e.employeedetails will be null for those customers who do not have a details entry
What is the best way to rewrite the above query?
Would something like this be acceptable ?
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails == null ? "" : e.employeedetails.Address,
}).ToList();
I am not clear on the efficiency of this above query - Would this statment do the null check at DB level?
Should I instead do an explicit include like
objectcontext.include("employeedetails")...
And then loop through the results to check for null?
Yes, this statement would indeed perform a null check in the SQL query that is generated. Most likely, it will simply be a NVL or COALESCE.
That's the way you should be doing it.
I am trying to implement a "if exists, update, otherwise, insert" data access method in NHibernate. My database is Oracle 10g.
I am getting this "could not execute native bulk manipulation query" error when try to run this code, if I run the insert or update individualy, it works just fine.
Thanks!
string sql = #"DECLARE
CntOfRow Number(10,0);
BEGIN
SELECT count(*)
INTO CntOfRow
FROM Table1
WHERE
QueID=:QueID
IF CntOfRow=0 THEN
INSERT INTO Table1 ...;
ELSE
UPDATE Table1 ... ;
END IF;
END;";
INHibernateSession session = NHibernateSessionManager.Instance.Session;
try
{
session.BeginTransaction();
ISQLQuery query = session.GetISession().CreateSQLQuery(sql.Replace(System.Environment.NewLine, " "));
query.SetParameter("QueID", queID);
query.ExecuteUpdate();
session.CommitTransaction();
}
catch (Exception ex)
{
session.RollbackTransaction();
throw;
}
I don't know why you get that error, but you could try this simpler PL/SQL block instead:
BEGIN
INSERT INTO Table1 ...;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE Table1 ... ;
END;";
You seem to be missing an ; after the SELECT
This link might also be of interest to you.
As about inserting/updating, see MERGE statement. It works like this:
MERGE INTO t1 dest
USING (SELECT 1 pk, 11 i FROM dual) src
ON (dest.pk = src.pk)
WHEN NOT MATCHED THEN INSERT (dest.pk, dest.i) VALUES (src.pk, src.i)
WHEN MATCHED THEN UPDATE SET dest.i = src.i;
Also see this topic
Go to an Oracle client like Toad or SQL Editor and try to execute the procedure with the same parameters that you send through Hibernate.
In my case, Oracle was throwing an error like:
11:50:57 ORA-01403: no data found
The cause was a select inside of procedure/function. Then improve the procedure/function to catch these exceptions.