abishkar bhattarai
abishkar bhattarai

Reputation: 7651

Returning returned model object to json String using spring data jpa with hibernate

I am using spring data jpa with hibernate This is my dao interface

@Repository
public interface IUserDAO extends JpaRepository<User, Integer>{
    User findByUsername( final String username );
}

This is my User class

Entity
@Table(name="USER")
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name="ID", nullable = false)
  private int id;

  @Column(name="USERNAME", nullable = false)
  private String username;

  @Column(name="NAME", nullable = false)
  private String name;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}

This is my UserImplClass

This is my UserImplClass{
@Autowired
    private IUserDAO iUserDAO;

public String findUserByUserName(String username) {

        User user =iUserDAO.findByUsername(username);
        Convert user to json object from framework level automatically
        // i can add my one implemenation of converting user to  json here ,but i want to achieve it from  framework so that my code is not scattered on every service level
        return "jsonStringOfUserObject" 
    }

Is it possible with spring data jpa with hibernate so that i do not have to write code for converting java object to json string in every service level?

I am using spring ,therefore i want to achieve it from spring .

Upvotes: 0

Views: 6257

Answers (1)

Shay Elkayam
Shay Elkayam

Reputation: 4158

You have two options to do what you want:

1) If you plan on returning this Object as an HTTP Response, and you use Spring MVC with Controllers you can annotate your controller method as follows:

public @ResponseBody User getUser(){
   return userImplClass.findUserByUserName("yourusername");
}

2) If you want the UserImplClass itself to return a JSON String (which I do't recommend, but I leave you the decision), you can use Jackson Object Mapper to do it for you (you can inject it if you declare it as a bean on your configuration xml, or create a new instance of it, I personally prefer injecting it with @Autowired)

public String findUserByUserName(String username) {

    User user =iUserDAO.findByUsername(username);


    ObjectMapper mapper = new ObjectMapper(); // no need to do this if you inject via @Autowired


    return  mapper.writeValueAsString(user);
}

Upvotes: 3

Related Questions