-1

I created an entity. I want to write a RestController to save this entity and an image in MySQL. I use Java8, SpringBoot, Hibernate, Rest API, JSON. How can I do it? Can I save it together?

public class Client{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

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

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

    @Column(name = "photo")
    private String photo;
}

Controller

@PostMapping(value = "/save/client")
    public ResponseEntity saveClient(@RequestBody @Valid Client client){
        ResponseEntity responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
        if(Objects.nonNull(client)){
            this.clientService.saveClient(client);
            responseEntity = new ResponseEntity<>(HttpStatus.OK);
        }
        return responseEntity;
    }

2 Answers 2

0

You can achieve that using JPA/Hibernate.

  1. Create a repository interface which extends either CrudRepository or JpaRepository.
  2. Autowire an instance of the repository interface
  3. Save/store entity in the database by making a call to the save() method of the repository interface.

Take a look at the following article on how to use JPA/Hibernate: https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/

Sign up to request clarification or add additional context in comments.

Comments

0

Since you are using Hibernate, you can do something like this below, let me know if you have any problems.

@Lob
@Column(name = "content")
private byte[] content;

@JsonSetter("content")
public void setContent(String content) {
  this.content = Base64.decode(content.getBytes("UTF-8"));
}

public byte[] getContent() {
  return content;
}

6 Comments

Thank you! I corrected my entity. I am trying to send post by the postman. { "firstName": "Four", "lastName": "Borov" } Also, I added an image file in form-data. But I see "rg.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"
I solved it. But My entity saved without the image. In DB i see null
You need to serialise your entity and also have the @JsonSetter("content") on top of the setter, can you try that?
I added this annotation and implements Serializable. But it didn't help. Or I need to serialise my entity another way?
Can you please update your answer to reflect your changes? Also what is your table structure? Where does it fall through, did you try debugging to see where the problem is?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.