java ConstraintViolationException:在持久化期间,类 [....entities.WalletInfo] 的验证失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45778365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:53:56  来源:igfitidea点击:

ConstraintViolationException: Validation failed for classes [....entities.WalletInfo] during persist

javahibernatespring-mvc

提问by Chaklader Asfak Arefe

I work with Spring MVC RESTfulapp and get the ConstraintViolationExceptionwhile persisting. The error message provided below,

我使用Spring MVC RESTful应用程序并ConstraintViolationException坚持下去。下面提供的错误消息,

Exception in thread " STARTING" javax.validation.ConstraintViolationException: Validation failed for classes [mobi.puut.entities.WalletInfo] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=id, rootBeanClass=class mobi.puut.entities.WalletInfo, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=currency, rootBeanClass=class mobi.puut.entities.WalletInfo, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140)
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:197)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:75)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at mobi.puut.database.WalletInfoDao.create(WalletInfoDao.java:62)
    at mobi.puut.database.WalletInfoDao$$FastClassBySpringCGLIB$4213d.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at mobi.puut.database.WalletInfoDao$$EnhancerBySpringCGLIB$$a84b41b3.create(<generated>)
    at mobi.puut.services.WalletService.createWalletInfo(WalletService.java:273)
    at mobi.puut.services.WalletService.lambda$generateAddress
@Transactional(rollbackFor = Exception.class)
    public WalletInfo create(String name, String address) {

        // create the WalletInfo entity with provided name and address
        WalletInfo walletInfo = new WalletInfo();
        walletInfo.setAddress(address);
        walletInfo.setName(name);

        // persist the created instance into the database
        sessionFactory.getCurrentSession().persist(walletInfo);
        return walletInfo;
    }


protected WalletInfo createWalletInfo(final String walletName, final String address) {
        return walletInfoDao.create(walletName, address);
    }


public synchronized WalletInfo generateAddress(final String walletName, String currencyName) {

        // get the WalletInfo entity from the database with the wallet and the currency name
        WalletInfo walletInfo = walletInfoDao.getWalletInfoWithWalletNameAndCurrency(walletName, currencyName);

        // generate wallet, if the wallet is not
        // generated previously
        if (walletInfo == null) {

            if (genWalletMap.get(walletName) == null) {

                logger.info("Wallet name that we are workign on {}", walletName);

                final WalletManager walletManager = WalletManager.setupWallet(walletName);

                walletManager.addWalletSetupCompletedListener((wallet) -> {

                    Address address = wallet.currentReceiveAddress();
         /*at mobi.puut.services.WalletService.lambda$generateAddress
@Entity
@Table(name = "wallet_info")
public class WalletInfo {

    @Id
    @Column(name = "id")
//    @NotNull
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @NotNull
    @Column(name = "address")
    private String address;

    @NotNull
    @Column(name = "currency")
    private String currency;

    public Long getId() {
        return id;
    }

    public WalletInfo(@NotNull String name, @NotNull String address, @NotNull String currency) {
        this.name = name;
        this.address = address;
        this.currency = currency;
    }

    public WalletInfo(@NotNull String name, @NotNull String address) {
        this.name = name;
        this.address = address;
    }

    public WalletInfo() {
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }
}
(WalletService.java:97) */ WalletInfo newWallet = createWalletInfo(walletName, address.toString()); walletMangersMap.put(newWallet.getId(), walletManager); genWalletMap.remove(walletName); }); genWalletMap.put(walletName, walletManager); } return walletInfo; } return null; } private void setupWalletKit(final String walletId) { File directory = getWalletDirectory(walletId); // if the seed is not null, that means we are restoring from the backup bitcoin = new WalletAppKit(networkParameters, directory, WALLET_FILE_NAME) { @Override protected void onSetupCompleted() { // Don't make the user wait for confirmations // they're sending their own money anyway!! bitcoin.wallet().allowSpendingUnconfirmedTransactions(); Wallet wallet = bitcoin.wallet(); model.setWallet(wallet); /* lambda$onSetupCompleted
@Entity
@Table(name = "wallet_info")
public class WalletInfo {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @NotNull
    @Column(name = "address")
    private String address;

    @NotNull
    @Column(name = "currency")
    private String currency;

    // getters and setters 


   // constructors 

public WalletInfo(@NotNull String name, @NotNull String address, @NotNull String currency) {
        this.name = name;
        this.address = address;
        this.currency = currency;
    }

    public WalletInfo(@NotNull String name, @NotNull String address) {
        this.name = name;
        this.address = address;
    }

    public WalletInfo() {
    }
}
(WalletManager.java:109) */ setupCompletedListeners.forEach(listener -> listener.onSetupCompleted(wallet)); } }; // some code }
(WalletService.java:97) at mobi.puut.controllers.WalletManager.lambda$onSetupCompleted
@Transactional(rollbackFor = Exception.class)
public WalletInfo create(String name, String currency, String address) {

    // create the WalletInfo entity with provided name and address
    WalletInfo walletInfo = new WalletInfo();
    walletInfo.setAddress(address);
    walletInfo.setName(name);
    walletInfo.setCurrency(currency);

    // persist the created instance into the database
    sessionFactory.getCurrentSession().persist(walletInfo);
    return walletInfo;
}
(WalletManager.java:109) at java.lang.Iterable.forEach(Iterable.java:75) at java.util.Collections$SynchronizedCollection.forEach(Collections.java:2062) at mobi.puut.controllers.WalletManager.onSetupCompleted(WalletManager.java:109) at org.bitcoinj.kits.WalletAppKit.startUp(WalletAppKit.java:325) at com.google.common.util.concurrent.AbstractIdleService.run(AbstractIdleService.java:54) at com.google.common.util.concurrent.Callables.run(Callables.java:95)

The project structure is provided below,

项目结构如下,

enter image description here

在此处输入图片说明

The sample code directed to the error proviced below,

针对下面提供的错误的示例代码,

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

The WalletInfoentity provided,

WalletInfo提供的实体,

##代码##

What is the issue here and how to solve it?

这里有什么问题以及如何解决?

采纳答案by Chaklader Asfak Arefe

The solution provided in the comment is correct, I just want to write it elaborately to help others, especially, who are using the Hibernatenewly. The WalletInfoentity matches with the wallet_infotable in the MySQL,

评论中提供的解决方案是正确的,我只是想精心编写它以帮助其他人,尤其是Hibernate新使用的人。该WalletInfo实体与 中的wallet_info表匹配MySQL

enter image description here

在此处输入图片说明

Notice that every entity is provided as non-null NNand hence, needs to be matched while persistingin the database.

请注意,每个实体都以非空形式提供NN,因此需要persisting在数据库中进行匹配。

The walletInfoentity class after the modification,

walletInfo修改后的实体类,

##代码##

In the database layer, this was the method I was using to persist,

在数据库层,这是我使用的方法persist

##代码##

I just added the currecnycolumn and hence, forget to add the walletInfo.setCurrency(currency)line which made the currencyas nullearlier and creates the error. I still can make the idnull as the this is not an element in the constructor with @NotNullannotation and the entity parameter definition it was also not annotated with @NotNull

我刚刚添加的currecny列,因此,忘记添加 walletInfo.setCurrency(currency)这使得线currency作为null较早,创建错误。我仍然可以使idnull 因为 this 不是带有@NotNull注释的构造函数中的元素,并且实体参数定义也没有注释@NotNull

##代码##

I hope this will help some people.

我希望这会帮助一些人。