使用 JPA 访问字段时出现错误。我该如何解决这个问题?

尝试将值插入表中时,出现此错误


org.hibernate.property.access.spi.PropertyAccessException: Error accessing 

field [private int com.app.demo.model.Customer.id] by reflection for 

persistent property [com.app.demo.model.Customer#id] : 

com.app.demo.model.Customer@6d1c6e1e

javax.persistence.PersistenceException: 

org.hibernate.property.access.spi.PropertyAccessException: Error accessing 

field [private int com.app.demo.model.Customer.id] by reflection for 

persistent property [com.app.demo.model.Customer#id] : com.app.demo.model.Customer@6d1c6e1e

这是我的客户表。我正在使用 MySql Workbench,我正在尝试将我的值插入到这里。

http://img1.mukewang.com/62e13b62000127ef06130056.jpg

我正在使用此类将值插入表中


@Entity

@Table(name="customer")

public class Customer {


@Id

@GeneratedValue

@Column(name = "customer_id", unique = true, nullable = false)

private int id;

@Column(name="first_name")

private String firstName;

@Column(name="last_name")

private String lastName;

@Column(name="street_address")

private String address;

@Column(name="city")

private String city;

@Column(name="state")

private String state;

@Column(name="zip_code")

private String zipcode;

@Column(name="email")

private String email;

@Column(name="paypal_email")

private String paypalEmail;



// getters and setters

这就是我将值插入表中的方式


// Set customer values

Customer valuedCustomer = new Customer();


valuedCustomer.setFirstName(firstName);

valuedCustomer.setLastName(lastName);

valuedCustomer.setAddress(address);

valuedCustomer.setCity(city);

valuedCustomer.setState(state);

valuedCustomer.setZipcode(zip);

valuedCustomer.setEmail(email);


// insert customer info into the customer table

EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");


EntityManager em = emf.createEntityManager();


em.getTransaction().begin();

em.persist(valuedCustomer);

em.getTransaction().commit();


墨色风雨
浏览 188回答 2
2回答

慕村225694

尝试使用 AUTO 或 IDENTITY 策略。喜欢:@GeneratedValue(strategy = GenerationType.IDENTITY)

偶然的你

这是您的实体类中的 ID 字段定义@Id@GeneratedValue@Column(name = "customer_id", unique = true, nullable = false)private int id;这里 ID 字段是唯一的,而不是 null。因此,您必须在插入过程中提供 ID 字段上的数据。首先,使用注解作为我们的配置方法只是一种方便的方法,而不是应付无穷无尽的 XML 配置文件。@Id注解继承自,表示下面javax.persistence.Id的成员字段是当前实体的主键。因此,您的 Hibernate 和 spring 框架以及您可以reflect基于此注释做一些工作。有关详细信息,请检查javadoc 的 Id@GeneratedValue注解是配置指定列(字段)的递增方式。例如使用时Mysql,可以auto_increment在表的定义中指定使其自增,然后使用@GeneratedValue(strategy = GenerationType.IDENTITY)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java