Kotlin @Transient not working

I have a spring-boot-data and mongodb app I’m working on. I have a user document with a handful of fields.

class User(
    var id: ObjectId?,
    var username: String,
    var active: Boolean,
    var created: LocalDateTime,
    var from: String,
    var attributes: Map<String, Any?>? = null

The user.attributes get populated after I’ve pulled the user from the DB and authenticated the user. Any time I repo.save(user) the attributes should not persist with @Transient if I understand this right. However, any time I save the user after the attributes have been added those same attributes are saved in the mongo DB. Unless I manually drop them from the user class. Am I missing something?
Using springboot 2.7.0 and kotlin 1.6.21

Kotlin has nothing to do with this fundamentally, ask Spring maintainers maybe.

The only thing I can think of is, are you using the right Transient annotation? (Ie from the right package?)
Kotlin has one which changes Java serialization behavior which is not what you want here.

1 Like

You could also try switching this one class to a Java class to determine if it’s related to Kotlin or something else.
If you get it working in Java you can leave it or copy past it into a Kotlin file and let Intellij convert it to Kotlin code.

@al3c, Why is kotlin Transient not the right one in this situation? I do not want it deserialized into the object that is getting pushed into Mongo. Seems like the right one to me. I have tried the JPA Transient instead, putting it on the field with @field:Transient but it was throwing some other error that I can’t remember at the moment.

@arocnies That’s a good suggestion. If I have some time I will try to do this and see if it changes anything.

In the end, I ended up redesigning my User object to not need these things so that I could continue on other things. Will have to revisit this when I have more time.

See Transient - Kotlin Programming Language for kotlin.jvm.Transient

It adds the Java keyword transient to the field - that’s it.

Does that do what you want? It depends on Spring on whatever framework you use.

I never used spring, but from a random Google search:
@Transient exists in org.springframework.data.annotation

Ah yes, that makes more sense now. Thanks for pointing that out! I’ll have to do more testing with the JPA annotation and kotlin. I didn’t get any of them to work.

One tip I find helpful in these situations is using the Intellij tools: You can always click on any token/function/class/etc in your code and read the documentation on it in a small popup without leaving the IDE. You can also get quick info on what type is returned from a statement by highlighting the statement (or partial statement) and pressing the correct keyboard shortcut–helpful if you are wondering if you have the right type being used or returned at any given point.