How to represent java object as return type of service in .thrift file

1.4k views Asked by At

I'm developing a service using apache thrift. I have a service named getUser which returns User object. I couldn't find any way to define user-defined data type as a return type for my service defined in .thrift file.

user.thrift file looks like:

service UserService
{
        User getUser(1:i32 userId),
}

When I am compiling the user.thrift to generate java source code, I am getting "Type "User" has not been defined" error. Can anyone please help me, how to represent this user-defined java object as a data type in thrift.

The getUser method code in service implementation class:

@Override
public User getUser(int user id) throws TException {
    // here is the code that fetch the user object from database
    return user;
}

This is my User class, whose object is being returned by service getUser:

public class User {

    private int userId;
    private String name;
    private String city;
    private String country;
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

}
1

There are 1 answers

0
JensG On

The relevant IDL could look like this:

struct User {
   1 : i32 userId
   2 : string name
   3 : string city
   4 : string country
}

So that's pretty straightforward. With that, you have two options:

  • use the Thrift-generated class as the data object, replacing your existing class
  • write some code that converts the data back and forth.

Both options have their pros and cons. With the first approach, you will lose the getter-only for the Id, because the field must be read/writable. But you don't have to convert any data.

The second approach leaves you with the getter/setter structure you have right now, with some minor modifications (the factory pattern could be worth a look). You pay that with the burden of additional data conversion from Thrift into your class and back.

It depends on the exact requirements, which option is the better one for your case.