1

How can i insert JSON data to postgres using JPA without using the named query?

If i send PGObject to insert (using Converter) it gives error-> Coulmn "column_name" is type JSON but getting byte type

@Entity
@Table(name="users")
data class User{
   @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") val identifier: Int? = null,
   @Convertor(JSONConvertor::class.java)
   @Column(name = "user_detial") var userDetail: UserDetail? = null,
}


@Convertor
class JSONConvertor : AttributeConverter<UserDetail, PGObject> {
  override fun convertToDatabaseColumn(UserDetail attribute) {
   try {
      val userDetail = mapper.writeValueAsString(attribute);
      var pgObject = PGObject()
      pgObject.type = "json"
      pgObject.value = userDeatail
      return pgObject
   } catch (JsonProcessingException e) {
      throw new RuntimeException("Cannot serialize", e);
   }
  }
}

data class UserDetail(
   val name: String,
   val address: String? = null 
)

and calling from service using JPA repository->

val userDetail = UserDetail(name= "abc" address="some address") jpaRepo.save(userDetail)

What i am doing wrong into it?

4
  • Perhaps this answer will be useful: stackoverflow.com/a/39885334/2788 Commented May 31, 2018 at 7:11
  • Tried out din't work and that is the same approach which is in above code snippet. Commented May 31, 2018 at 8:25
  • user_detial is spelled wrong. Commented Mar 20, 2019 at 12:11
  • @Convertor also it's @Converter Commented Mar 20, 2019 at 12:16

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.