Carrie
Carrie

Reputation: 41

How to store a List<String> from spring JPA to text[] array in database

I am trying to write an Java- Array List into postgres database. But i am not able to DO, i don't get error as well. I am trying to post data

"skill":["java,dotnet"]

using postman tool but on Post nothing happens and i don't see any data in db.I also don't get any error in my console.please help me out on this i m wondering how to do this

I am able to read Array data from database but cannot write

    /*
     * Spring Entity:
     */
    @Column(name="skill" , columnDefinition = "text[]")
    @Convert(converter =ListToStringConverter.class)
        private List<String> skill=new ArrayList<>();       
        ublic List<String> getSkill() {
            return skill;
        }
        public void setSkill(List<String> skill) {
            this.skill= skill;
        }

    @Converter
    public class ListToStringConverter implements AttributeConverter<List<String>, String> { 

        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            if (attribute == null || attribute.isEmpty()) {
                return "";
            }
            return StringUtils.join(attribute, ",");
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            if (dbData == null || dbData.trim().length() == 0) {
                return new ArrayList<String>();
            }

            String[] data = dbData.split(",");
            return Arrays.asList(data);
        }
    }



Controller Code:

This is my Controller code to create a object in database and i use a interface service that is call from controller to Save to db-Postgres which is a JPA repo

    @RequestMapping(value = "/reqCreate", method = RequestMethod.POST)
    public ResponseEntity<Requirement> addRequirement(@RequestBody Requirement requirement) {
        reqService.save(requirement);               
        return new ResponseEntity<Requirement>(requirement, HttpStatus.CREATED);
    }

Service:
    public void save(Requirement r) {           
        reqRepo.save(r);
    }

Upvotes: 4

Views: 6074

Answers (1)

Sasha Shpota
Sasha Shpota

Reputation: 10320

The columnDefinition seems to be wrong.

You want to convert Collection into String, but you still declare column of array type.

Replace "text[]" with "text" and check if it works?

Upvotes: 4

Related Questions