@Transient annotation, @org.springframework.data.annotation.Transient annotation, transient keyword and password storing

你说的曾经没有我的故事 提交于 2019-12-03 02:05:27
Shivam Sinha

Within the Spring Framework you can use Mapping Framework to convert from one form to another. Say for example your spring java server side application needs send to user information to a client (webpage,mobile app) in JSON format.

@Entity
public class User {

@Id
private long id;

@Column(name = "username")
private String username;

@Column(name = "email")
private String email;

@Column(name = "password")
private String password;

}

Now to map this java entity object to JSON format you can either use a mapping framework (e.g jackson: com.fasterxml.jackson.databind.ObjectMapper) or do it manually.

The JSON format output that you would get when to convert user 2 object to JSON is:

{
   "id": 2,
   "email": "test03@gmail.com",
   "username": "test03",
   "password": "$2a$10$UbvmdhfcKxSNr/I4CjOLtOkKGX/j4/xQfFrv3FizxwEVk6D9sAoO"
}

Now if you added :

@org.springframework.data.annotation.Transient
@Column(name = "password")
private String password;

and then used the Mapping Framwwork to again generate the JSON for the user 2 entity you would get:

{
   "id": 2,
   "email": "test03@gmail.com",
   "username": "test03",
}

Note the password field is missing from you JSON output. Thats because @org.springframework.data.annotation.Transient specifically states to the spring framework that the Object Mapper you are using should not include this value when converting from Java Object to JSON.

Also note if you attempted to persist the above entity into the database, it would still save it to the database because @org.springframework.data.annotation.Transient only applys to Object mapping frameworks not JPA.

So to recap:

transient is for all serializations (over the wire, saving to disk, saving to db)
javax.persistence.Transient is specifically for JPA DB serialization @org.springframework.data.annotation.Transient is for ObjectMapping Framework serializations used within Spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!