hibernate bug: How to keep Hibernate sql where condition order obey the declared order? - sql

I have a class Student:
#Entity
#Table(name="student")
public class Student{
#EmbeddedId
private Id id;
//other property omit
#Embeddable
public static class Id implements Serializable{
#Column(name="last_name")
private String lastName;
#Column(name="first_name")
private String firstName;
}
}
I used hibernate to find a student by id, but I found that the generated sql where clause is what I don't expect. I want to generate the sql like select * from student where last_name = ? and first_name = ?, but the generated sql looks like select * from student where first_name = ? last_name = ?.
I want the generated sql where clause expression order to obey the proper order. Does anyone know how to generate such sql when I query a entity by composite id?

Related

Delete all records except one in database

I have to delete all the records for matching ID except one. There is no dat column which I can consider. The dtatastruchtur e is like below:
OBJECT_ID - primary key
DOC_ID
FIRST NAME
LAST NAME
I am trying to delete all the doc_ID that match to specific number except one through jpa. Couldn't find any jpa specific function. I am implementing JPARepository. There is delete All, Is there any way I can achieve this?
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
public User save(User user);
public void deleteAllByDocID(String docID);
}
UPDATE: Sorry was unsure of the database: we are using DB2 and I tried to write down these queries:
DELETE FROM USR WHERE OBJ_ID NOT IN (SELECT OBJ_ID FROM USR WHERE DOC_OBJ_ID='91298' FETCH FIRST 1 ROWS ONLY); - this gives me error transaction log is full.
ANd this:
DELETE FROM USR WHERE OBJ_ID NOT IN (SELECT TOP(1) OBJ_ID FROM USR WHERE DOC_OBJ_ID='91298'); - and this give me error TOP is not a function
if you don't want to use a custom query, you can do it like this :
in your repository define these two methods
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findFirstByDocIDOrderByObjectIDAsc(String docID);
void deleteAllByDocIDAndObjectIDNot(String docID, Long objectID);
}
and then in your service layer do this
User user = repository.findFirstByDocIDOrderByObjectIDAsc(docID);
if(user !=null) deleteAllByDocIDAndObjectIDNot(docID, user.objectID);
note that since this solution is using derived delete query, it will delete the records one by one.
You could COUNT matching records first and then delete with LIMIT N-1

Eclipelink #ElementCollection remove all on merge

I have this mapping:
#Entity
#Table(name="CUSTOMER")
class Customer {
#Id
#Column(name="CUSTOMER_ID")
Long id;
...
#ElementCollection
#CollectionTable(name="CUSTOMER_ADDRESS", joinColumns=#JoinColumn(name="CUSTOMER_ID"))
List<CustomerAddress> addresses;
}
#Embeddable
class CustomerAddress {
String street;
String zip;
String ...
String ...
...
}
I have two saved addresses for customer ID : 1. If i update this customer, having a single address on, Eclipselink tries deletes the missing address row using all CustomerAddress fields on DELETE where statement:
DELETE FROM CUSTOMER_ADDRESS WHERE STREET = ?, ..., ZIP = ?, ..., CUSTOMER_ID = ?
The issue is i may have accents and other data that prevents the WHERE statement to match the row using all fields. Is there anyway to force Eclipselink to delete all user addresses and insert again?
DELETE FROM CUSTOMER_ADDRES WHERE CUSTOMER_ID = ?
INSERT ALL FROM COLLECTION
I could not find a way to accomplish what i wanted. It seems Hibernate has the behavior i expect.
Changed ElementCollection to OneToMany and changed the model to have an ID under CustomerAddress.

Linq: Order by parentID

Having this class...
Public Class Employee
Public Property ID As Guid
Public Property ParentID As Nullable(Of Guid)
End Class
It's not a tree, but a list - therefor ParentID is unique and can occur only once.
How do I in Linq (using vb.net) sort it by "ParentID" (empty ParentID first)?
The null Guids sort first by default, so you can just use OrderBy:
employees = employees.OrderBy(Function(e) e.ParentID).ToList()
Or if you prefer query syntax:
employees = (From e In employees Order By e.ParentID).ToList()

select null fields in hibernate

I had made select query in hibernate from employees table that had following columns:
private int id;
private String firstname;
private String lastname;
private String email;
private String phoneno;
private Date hiredate;
private Jobs jobid;
private Integer salary;
private Integer commpct;
private Employee managerid;
private Departments deptid;
On this table,
first record had managerid set to null, and afterwards every record managerid set to first record employeeid;
when i select data from employees table using query: ("FROM EMPLOYEES") using following code:
Query query = session.createQuery("FROM Employee");
List<Employee> employees = query.list();
for(Employee employee:employees){
System.out.println("ID=>"+employee.getId()+"\tFirstName=>"+employee.getFirstname()+"\tLastName=>"+employee.getLastname()
+"\temail=>"+employee.getEmail()+"\tPhoneNO=>"+employee.getPhoneno()+"\tHireDate=>"+employee.getHiredate()
+"\tJob=>"+employee.getJobid().getJobtitle()+"\tMax Salary=>"+employee.getJobid().getMaxsalary()
+"\tPresent Salary=>"+employee.getSalary()+"\tCommission %=>"+employee.getCommpct()+"\tManager=>"+employee.getManagerid().getFirstname()+","+employee.getManagerid().getLastname()
+"\tDepartment ID=>"+employee.getDeptid().getName());
}
Exception throws bcoz first record managerid is null,
Then, i used this query
Query query = session.createQuery("FROM Employee em WHERE em.managerid IS NOT NULL AND em.deptid IS NOT NULL");
I get the record other than first record.
ID is the primarykey and managerid is the foreign key pointing to Employees Table (id) field.
All rows have id present but some rows/one row had managerid set to null.
My Question is how to get all the records even if first record managerid is set to null?
What setting i had to made?
First of all, in hibernate entities it is mandatory to have primary key column in table & it has to be not null. Else hibernate can't handle entities as it handles them using primary key. So null primary key is confusing to hibernate so not allowed.
You can fire native query using hibernate if you want to anyways fetch the data.
Native query Reference: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

NHibernate Mapping : How to map rows based on a field value

I have a [ContactNumbers] table as defined below:
ID (PK) | PersonID (FK) | NumberType | Number
========|===============|============|=======
and a classes defined as:
public class Person
{
ContactNumber homePhone;
ContactNumber workPhone;
}
public class ContactNumber
{
string Number;
}
How would I define my HBM mapping/s for the Person and ContactNumber class so that Person.homePhone is mapped to the corresponding row in the [ContactNumbers] table with the FK observed, and [ContactNumbers].[NumberType] equal to "HOME"? ([NumberType] is "WORK" for Person.workPhone.)
Already spent a good deal of the day just looking into this, and I couldn't find a solution just yet.
You cannot map single entity / instance to multiple rows and vice versa.
What you can do is do this:
class Person
{
public IList<ContactNumber> ContactNumbers { get; set; }
}
And then map the ContactNumbers class as a collection / ony-to-many association. The PersonID column is listed as a foriegn key so I assume there is a person table?