0

enter image description here

package com.kk.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan(basePackages="com.kk")
@EnableJpaRepositories(basePackages="com.kk.respositry")
@EntityScan(basePackages="com.kk.entity")
@SpringBootApplication
public class SpringBootEnumExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootEnumExampleApplication.class, args);
    }

}


package com.kk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kk.entity.Account;
import com.kk.service.AccountService;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value="create",method=RequestMethod.POST)
    private @ResponseBody String createAccout(@RequestBody Account account) {
        Long l=accountService.save(account);

        return "{\"accountId\":l}";

    }
}



package com.kk.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.kk.enums.AccountRole;

@Entity
@Table(name = "account_tab")
public class Account {

    @Id
    @GeneratedValue
    private Long id;
    private String accountHolderName;
    private String mobile;
    private Integer age;

    @Enumerated(EnumType.STRING)
    @Column(name = "account_role", length = 40)
    private AccountRole accountRole;

    public Long getId() {
        return id;
    }

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

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public AccountRole getAccountRole() {

        return accountRole;
    }

    public void setAccountRole(AccountRole accountRole) {
        this.accountRole = accountRole;
    }

}


package com.kk.enums;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kk.enums.utils.AccountRoleDeserializer;

@JsonDeserialize(using = AccountRoleDeserializer.class)
public enum AccountRole {
    EMPLOYEE_CUSTOMER("Employee customer"),
    JOINTER_ACSCOUNT("Jointer customer"),
    PRIMARY_ACCOUNT("Primary customer"),
    TENANT_ACCOUNT("Tenant customer");

    private final String text;

    AccountRole(final String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
    public String getText() {
        return this.text;
    }

    public static AccountRole fromText(String text) {
        for (AccountRole r : AccountRole.values()) {
            if (r.getText().equals(text)) {
                return r;
            }
        }
        throw new RuntimeException("Your AccountRole not valied: "+text );
    }
}



package com.kk.enums.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kk.enums.AccountRole;

public class AccountRoleDeserializer extends JsonDeserializer<AccountRole> {

    @Override
    public AccountRole deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);

        if (node == null) {
            return null;
        }
        String text = node.textValue(); // gives "A" from the request

        if (text == null) {
            return null;
        }
        return AccountRole.fromText(text);

    }
}



package com.kk.respositry;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.kk.entity.Account;

@Repository
public interface AccountRespositry extends JpaRepository<Account, Long> {

}



package com.kk.service;

import com.kk.entity.Account;

public interface AccountService {

    Long save(Account account);

}


package com.kk.service;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kk.entity.Account;
import com.kk.respositry.AccountRespositry;

@Service
@Transactional
public class AccountServiceImpl implements AccountService{

    @Autowired
    private AccountRespositry accountRespositry;

    @Override
    public Long save(Account account) {
        account=accountRespositry.save(account);
        return account.getId();
    }
}



server.port=8088
server.servlet.context-path=/SpringBootEnum/

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/Account?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

I am using spring boot (data jpa ) but am getting the wrong value in the database.

Graham
  • 7,431
  • 18
  • 59
  • 84
kaushal kumar
  • 11
  • 1
  • 2
  • Welcome! You question contains [images of output](http://idownvotedbecau.se/imageofanexception/) and accidentially repeated sentences. Maybe you should [edit] it and fix it. – akraf Jan 07 '19 at 13:42

1 Answers1

1

The @Enumerated is behaving as expected. It's going to return the name of the enum and that's what gets persisted. Remember JPA uses the name() of the enum and not the toString() even if you have overridden the toString(). I would recommend using an AttributeConverter (JPA 2.1+) to control the persistence of your enum. In your case, create the converter to use the getText() method you already have defined in your Enum.

@Converter(autoApply = true)
public class AccountRoleConverter implements AttributeConverter<AccountRole, String> {

@Override
public String convertToDatabaseColumn(AccountRole role) {
    return role.getText();
}

@Override
public AccountRole convertToEntityAttribute(String dbData) {
    return AccountRole.fromText(dbData);
}

}

Note: @Converter(autoApply = true), tells JPA provider to use it to map all AccountRole enums.

Now you just need to make sure you remove the @Enumerated from your Account Entity:

@Enumerated(EnumType.STRING)
@Column(name = "account_role", length = 40)
private AccountRole accountRole;

becomes

@Column(name = "account_role", length = 40)
private AccountRole accountRole;

Ok you may ask how you use the converter. Well that is the nice part, you don't have to do anything. The persistence provider will use it for all read and write operations. I hope this helps.

M. Rizzo
  • 1,611
  • 12
  • 24
  • When i fetching record in data base that time coming response enum key like { "id": 4, "accountHolderName": "kk", "mobile": "+9100000222", "age": 22, "accountRole": "PRIMARY_ACCOUNT" } how to solve find record into database , ex- when i findall record in Database its coming PRIMARY_ACCOUNT but i need like Primary customer, Please help me one again – kaushal kumar Jan 08 '19 at 10:05
  • Ok i got answer this one in here :- https://stackoverflow.com/questions/7766791/serializing-enums-with-jackson – kaushal kumar Jan 08 '19 at 10:30