使用通用生成器时出现错误

时间:2019-11-22 11:47:18

标签: hibernate spring-boot jpa h2

使用Spring Boot 2.1.1和H2数据库测试JPA。

错误

发生意外错误(类型=内部服务器错误,状态= 500)。 无法通过反射设置字段值[ST30790]的值:com.example.demo.model.Student.id的[class com.example.demo.model.Student.id]设置程序;嵌套异常是org.hibernate.PropertyAccessException:无法通过反射设置字段值[ST30790]值:com.example.demo.model.Student.id的[class com.example.demo.model.Student.id]设置程序

学生班

package com.example.demo.model;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(generator = "Student_id")
    @GenericGenerator(name = "Student_id", strategy = "com.example.demo.model.StudentGenerator")
    private int id;
    private String email;
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

我的发电机

package com.example.demo.model;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.enhanced.SequenceStyleGenerator;

import java.io.Serializable;
import java.util.Random;

public class StudentGenerator extends SequenceStyleGenerator {

    private static final String STUDENT_ID_PREFIX = "ST";

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return STUDENT_ID_PREFIX + String.valueOf(generateID());
    }

    public static char[] generateID() {

        //Creating object of Random class
        Random obj = new Random();

        char[] otp = new char[5];

        for (int i = 0; i < 5; i++) {
            otp[i] = (char) (obj.nextInt(10) + 48);
        }
        System.out.print("Your OTP is : " + otp.toString());
        return otp;
    }
}

请帮助

1 个答案:

答案 0 :(得分:1)

您的生成器输出是字符串,但是您的学生实体ID是int。在学生int属性中将string更改为id,它应该可以工作。