Spring boot (data jpa ) i am not able to save eumn value in database

时间:2019-01-07 13:05:47

标签: spring spring-data-jpa spring-data

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.

1 个答案:

答案 0 :(得分:1)

@Enumerated的行为符合预期。它会返回枚举的名称,这就是持久化的原因。请记住,即使您重写了toString(),JPA也会使用枚举的name()而不是toString()。我建议使用AttributeConverter(JPA 2.1+)来控制枚举的持久性。根据您的情况,创建转换器以使用您已经在枚举中定义的getText()方法。

@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);
}

}

注意:@Converter(autoApply = true),告诉JPA提供者使用它来映射所有AccountRole枚举。

现在,您只需要确保从帐户实体中删除@Enumerated:

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

成为

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

好的,您可能会问如何使用转换器。好吧,这是很不错的部分,您无需执行任何操作。持久性提供程序会将其用于所有读取和写入操作。我希望这会有所帮助。