Reputation: 13
How to add restriction to load only desired fields from entity? My User table having CustomerUser OneToOne mapping and Transaction table having User as OneToOne maping So when i load transaction it load user and respective customer, but i dont want to load password and some other fileds from customeruser table. (Hibernate version 4.2.6)
Upvotes: 0
Views: 596
Reputation: 1294
What you need to do is to write Json annotation and fetch type. e.g:
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JsonIgnore
private CustomerUser customerUser;
FetchType.LAZY
does not load the class automatically. @JsonIgnore
blocks the class to be in the json.
Or,
Lets say you want to load CustomerUser with all its variables except password. What you need to do is to add @JsonIgnore
to password variable .
public class User {
....
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
@JsonManagedReference
private CustomerUser customerUser;
....
}
public class CustomerUser {
@Column(name = "username")
private String username;
@Column(name = "password")
@JsonIgnore
private String password;
......
...getters/setters
}
Upvotes: 1
Reputation: 4678
You could do that with
@Basic(fetch = FetchType.LAZY)
But for that to work on your fields you have to enable Hibernates Bytecode Enhancer (some back story)
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<configuration>
<failOnError>true</failOnError>
<enableLazyInitialization>true</enableLazyInitialization>
<enableDirtyTracking>true</enableDirtyTracking>
</configuration>
<phase>compile</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
Another way is to have two entities mapped to the same table. Like CustomerUser could have mapped all the fields that are always loaded, but the CustomerPassword would have only the id and the password itself. Then you would only load the passwords entity when you need it from your service/repository.
This was a common workaround before they fixed the lazy properties ticket. Took like 3 years :P.
Upvotes: 1