问题
I have a method that looks like this:
static UserEvent get(long userId, long eventId) {
UserEvent.find 'from UserEvent where user.id=:userId and event.id=:eventId',
[userId: userId, eventId: eventId]
}
I'm calling it two times with some test data:
println UserEvent.get(1, 1) //I know this has value
println UserEvent.get(1,2) //I know this does not
The above two statements result in:
scheduler.UserEvent : null
null
Question
What is the difference? How can I write an If condition for when something is present or not..
Update
I'm creating the object like this:
def event = Events.findById(params.eventid)
def user = User.findById(params.userid)
UserEvent.create(user, event, true)
回答1:
@tim_yates is right, the object that is retrieved doesn't have an id property. Looks like an M to M relationship.
So in the first case an instance is being returned but it's ID is null. In the second case the object isn't found.
You can use something like:
def ue = UserEvent.get(userId, eventId)
if (ue && ue instanceof UserEvent) { //do something }
else { //do something else }
Hope this helps.
回答2:
The first case returns an instance of UserEvent, which inside of an if statement, should return true. The second case returns null, which inside of an if statement, should return false.
来源:https://stackoverflow.com/questions/15091570/different-types-of-null-in-groovy