[英]Why doesn't random work?
I have to write a method, which is able to find random Vacation in the database. 我必须编写一个方法,该方法能够在数据库中找到随机的Vacation。 But when I use this part in the test
但是当我在测试中使用这部分时
Random id = new Random();
vacationId = id.nextInt(2500);
I get NullPoiterExeption
. 我得到
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
: 我怀疑这是您获取
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. 这是在您从
Random
设置之前 -将参数设置为null值。
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. 不过,老实说,这不是从数据库中查找随机记录的好方法,除非您知道每个ID从0到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.
一种替代方法是获取所有休假ID,从该集合中选择一个随机元素,然后为其加载数据-但这也不令人满意。
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 ? VacationId是否可以保留null值? if not then try with the random at once.
如果没有,则立即尝试随机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.