I have to write a method, which is able to find random Vacation in the database. But when I use this part in the test
Random id = new Random();
vacationId = id.nextInt(2500);
I get NullPoiterExeption
. But when i just print
vacationId = 2500;
or some other number, everything is okay.
This is the whole method
public Vacation findRandomVacation() {
Integer vacationId = null;
Query query = entityManager.createQuery("from Vacation v where v.id = :id")
.setParameter("id", vacationId);
if ( query.getResultList().isEmpty()) {
Random id = new Random();
vacationId = id.nextInt(2500);
query = entityManager.createQuery("from Vacation v where v.id = :id")
.setParameter("id", vacationId);
}
return (Vacation) query.getResultList().get(0);
}
And this is the main body of the test:
@Test
public void testVacationApprovalResultDao () {
Vacation testVacation = findRandomVacation();
VacationApproval testVacationApproval = findVacationApprovalDAO(testVacation);
List<VacationApprovalResult> testVacationApprovalResult = getVacationApprovalResultByManager(testVacationApproval);
Set<VacationApprovalResult> setVacationApprovalResult = testVacationApproval.getVacationApprovalResults(); //mistake is here
List<VacationApprovalResult> testVacationApprovalResult2 = new ArrayList<VacationApprovalResult> ();
testVacationApprovalResult2.addAll(setVacationApprovalResult);
assertEquals(testVacationApprovalResult, testVacationApprovalResult2);
}
I suspect this is where you get the NullPointerException
:
Integer vacationId = null;
Query query = entityManager.createQuery("from Vacation v where v.id = :id")
.setParameter("id", vacationId);
This is before you've set it from Random
- you're setting the parameter to a null value.
To be honest though, this isn't a good way of finding a random record from the database unless you know that there are vacations with every ID from 0 to 2499.
Basically you want the random choice to be performed at the database as that's where the data is. An alternative would be to fetch all the vacation IDs, pick a random element of that set, and then load the data for it - but that's not pleasant either.
change
Integer vacationId = null;
to
Integer vacationId = 0;
Why would you do this ?
Integer vacationId = null;
Query query = entityManager.createQuery("from Vacation v where v.id = :id")
.setParameter("id", vacationId);
Is it possible for vacationId to hold a null value ? if not then try with the random at once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.