I saw several similar questions but non with an answer that worked for me. I am working on converting an existing project over to use Hibernate. I am using Mysql for the database. I have a class like this:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long userId;
@ManyToOne
@JoinColumn(name = "group_id_user")
private Group group;
@Column(name = "name")
private String name;
...
// getters and setters....
}
and a class like this:
@Entity
@Table(name = "group")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "group_id")
private Long groupId;
@Column(name="group_name")
private String groupName;
...
// getters and setters....
}
When I fetch a User
item from the database I convert it to JSON and end up with a result in this format:
{
"user": {
"userId": 1,
"group": {
"groupId": 3,
"groupName": "Group Three",
},
"name": "John Doe",
}
}
In my case, the Group
object is actually quite a bit bigger than in this example and also contains references to another table as well (i.e. Group
has a SomeOtherClass
object). I want to end up with something that looks like the following:
{
"user": {
"userId": 1,
"groupId": 3,
"name": "John Doe",
}
}
Is there a way to just get the groupId in my JSON response instead of the entire Group
object?
I have tried adding FetchType.Lazy to my User class
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "group_id_user")
private Group group;
but when I try to convert the User
object to Json I get the following error:
error: Errorjava.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
I found this answer which gets rid of the error, but then the JSON object is exactly the same as it was before I added the FetchType.LAZY
. It looks like somehow converting to JSON adds in the values that the FetchType.LAZY
was ignoring.
I am using converting to JSON as follows:
GsonBuilder b = new GsonBuilder();
Gson gson = b.create();
//b.registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);
com.google.gson.JsonArray jsonArray = gson.toJsonTree(out).getAsJsonArray();