Hibernate error accessing field by reflection for persistent property

Hibernate Community Forums

I want to make a query that I can find notes on the user ID (database DDL is at the very bottom), but I have issue: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private long ru.mrchebik.model.User.USER_ID] by reflection for persistent property [ru.mrchebik.model.User#USER_ID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private long ru.mrchebik.model.User.USER_ID] by reflection for persistent property [ru.mrchebik.model.User#USER_ID] : 1

Full stack of issue:

http://pastebin.com/Av8uirGh

How can you see, I have and this exception: IllegalArgumentException: Can not set long field ru.mrchebik.model.User.USER_ID to java.lang.Long

And this, a class of Note, User and method Spring Data:

Note:

Code:

package ru.mrchebik.model;

import javax.persistence.*;

/**
* Created by mrchebik on 23.07.16.
*/
@Entity
@Table(name = «Notes»)
public class Note {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = «USER_ID», nullable = false)
    private User user;

    @Column(nullable = false, length = 25)
    private String title;

    @Column(nullable = false)
    private String text;

    public Note() {

    }

    public Note(final long id, final String title, final String text) {
        this.id = id;
        this.title = title;
        this.text = text;
    }

    public Note(final User user, final String title, final String text) {
        this.user = user;
        this.title = title;
        this.text = text;
    }

    public User getUser() {
        return user;
    }

    public void setUser(final User user) {
        this.user = user;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(final String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(final String text) {
        this.text = text;
    }

    public long getId() {
        return id;
    }

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

}

User:

Code:

package ru.mrchebik.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
* Created by mrchebik on 22.07.16.
*/
@Entity
@Table(name = «Users»)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true, nullable = false)
    private long USER_ID;

    @Column(unique = true, nullable = false, length = 12)
    private String username;

    @Column(nullable = false, length = 16)
    private String password;

    @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Note> notes = new HashSet<Note>(0);

    public User() {

    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(final String name) {
        this.username = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(final String password) {
        this.password = password;
    }

    public long getUSER_ID() {
        return USER_ID;
    }

    public void setUSER_ID(final long id) {
        this.USER_ID = id;
    }

    public Set<Note> getNotes() {
        return this.notes;
    }

    public void setNotes(Set<Note> notes) {
        this.notes = notes;
    }
}

NoteRepository:

Code:

package ru.mrchebik.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import ru.mrchebik.model.Note;

import java.util.List;

/**
* Created by mrchebik on 07.08.16.
*/
public interface NoteRepository extends JpaRepository<Note, Long> {
    List<Note> findByUser(@Param(«USER_ID») long id);
}

Database DDL:

Code:

CREATE TABLE Users
(
    USER_ID BIGINT(20) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    username VARCHAR(12) NOT NULL,
    password VARCHAR(16) NOT NULL
);
CREATE UNIQUE INDEX username ON Users (username);
CREATE TABLE Notes
(
    id BIGINT(20) PRIMARY KEY NOT NULL AUTO_INCREMENT,
    USER_ID BIGINT(20) NOT NULL,
    title VARCHAR(25) NOT NULL,
    text VARCHAR(255) NOT NULL,
    CONSTRAINT FK47F5EA160804239 FOREIGN KEY (USER_ID) REFERENCES Users (USER_ID)
);
CREATE INDEX FK47F5EA160804239 ON Notes (USER_ID);

Thanks.

I’ve been experiencing problems implementing the Authorities on my spring boot application, and after digging a little I realised that maybe the association between my Credentials and Authorities tables, was wrong.

In fact it come to my attention that Spring allowed every type of user, (regardless their authority) to access ever method, even the ones I though have been secured. At that point, I implemented a .findAll() method to actually see if there was some kind of problem on the association, and indeed there was.

Let me show first the MySQL tables:

CREATE TABLE credentials (
  credential_id bigint UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  email varchar(50) NOT NULL UNIQUE,
  password varchar(255) NOT NULL,
  enabled BOOLEAN NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


CREATE TABLE authorities (
  email varchar(50) NOT NULL,
  authority varchar(50) NOT NULL,
  PRIMARY KEY (email, authority),
  CONSTRAINT fk_authorities_credentials FOREIGN KEY(email) REFERENCES credentials(email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Before jumping onto the associations in the entities, it’s worth noting that the authorities entity has and embedded key reflecting the design of the table. So the email column its a foreign key and a primary at the same time:

@Embeddable
public class AuthoritiesKey implements Serializable {
  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "email", nullable = false
          ,referencedColumnName = "email")
  private Credentials credentials;

  @JoinColumn(name = "authority", nullable = false)
  private String authority;

//getters setters omitted
}

Credentials class:

@Entity
@Table(name = "credentials")
public class Credentials implements Serializable {

  @OneToOne(cascade = CascadeType.ALL,
          fetch = FetchType.LAZY,
          mappedBy = "ak.credentials")
  private Authorities authorities;

//other fields and getters/setters omitted
}

Removing the bilateral association (thus leaving it just on the AuthoritiesKey class), hibernate successfully returns all the credentials (without their authorities of course), and all the authorities (this time preceded by the credentials).

I cannot wrap my head around it.

The complete meaningful stack trace i get when I leave the bilateral association is the following:

Error accessing field [private java.lang.String com.server.model.Credentials.email] by reflection for persistent property [com.servermodel.Credentials#email] : 64; 
nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String com.server.model.Credentials.email] by reflection for persistent property [com.server.model.Credentials#email] : 64

Where 64 is the id of the (last, but get called first) row in the Credential table.

=== UPDATE ===

public class CredentialsService implements UserDetailsService {

  @Autowired
  private CredentialsRepository cr;

   @Override
  public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Credentials user = cr.findByEmail(email);
    if (user == null){
      throw new UsernameNotFoundException(email);
    }
    return new UserPrincipal(user);
  }
}

Advertisement

Answer

It looks like you can not use @OneToOne here due to the hibernate bug. (See HHH-3824) It’s reproduced even with Hibernate 5.4.28.Final

As workaround, I would suggest you to correct your mapping in this way:

@Entity
@Table(name = "authorities")
public class Authorities {
   
   @EmbeddedId
   private AuthoritiesKey pk;

   // ...
}

@Embeddable
public class AuthoritiesKey implements Serializable {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "email", referencedColumnName = "email", nullable = false)
  private Credentials credentials;

  @Column(name = "authority", nullable = false)
  private String authority;

  public AuthoritiesKey(Credentials credentials, String authority) {
    this.credentials = credentials;
    this.authority = authority;
  }

  public AuthoritiesKey() {
  }

  // getters setters omitted
  
  @Override
  public boolean equals(Object o) {
    if ( this == o ) return true;
    if ( o == null || getClass() != o.getClass() ) return false;

    AuthoritiesKey pk = (AuthoritiesKey) o;
    return Objects.equals( credentials, pk.credentials ) &&
            Objects.equals( authority, pk.authority );
  }

  @Override
  public int hashCode() {
    return Objects.hash( credentials, authority );
  }
}

@Entity
@Table(name = "credentials")
public class Credentials implements Serializable {
   
   @Id
   @Column(name = "credential_id")
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        mappedBy = "pk.credentials")
   private List<Authorities> authorities;

   @NaturalId
   @Column(name = "email")
   private String email;

   @Transient
   public Authorities getAuthority()
   {
      return this.authorities != null && this.authorities.size() > 0
          ? this.authorities.get(0) : null;
   }
 
   // ...
}

8 People found this is helpful

I have strange issue when I try to get entities property:

Hibernate:
    select
        tarifklsk0_.ID as ID1_12_0_,
        tarifklsk0_.FK_TARIF as FK_TARIF2_12_0_,
        tarifservp1_.FK_TARIF as FK_TARIF2_11_1_,
        tarifservp1_.ID as ID1_11_1_,
        tarifservp1_.ID as ID1_11_2_,
        tarifservp1_.FK_TARIF as FK_TARIF2_11_2_,
        tarifservp1_.N1 as N3_11_2_
    from
        TR.TARIFXKLSK tarifklsk0_
    left outer join
        TR.TARIF_SERV_PROP tarifservp1_
            on tarifklsk0_.FK_TARIF=tarifservp1_.FK_TARIF
    where
        tarifklsk0_.ID=?
Jun 13, 2016 7:38:26 AM org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer TarifKlsk.fkTarif] by reflection for persistent property [TarifKlsk#fkTarif] : 1027303
Exception in thread "main" org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer TarifKlsk.fkTarif] by reflection for persistent property [TarifKlsk#fkTarif] : 1027303
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
    ....skipped...
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field TarifKlsk.fkTarif to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)

My entities:

TarifKlsk

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.BatchSize;

@SuppressWarnings("serial")
@Entity
@Table(name = "TARIFXKLSK", schema="TR")
public class TarifKlsk implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", updatable = false, nullable = false)
    private Integer id;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name="FK_TARIF", referencedColumnName="FK_TARIF")
    @BatchSize(size = 50)
    private Set<TarifServProp> tarifservprop = new HashSet<TarifServProp>(0);

    @Column(name = "FK_TARIF", updatable = false, nullable = false)
    private Integer fkTarif;

    public Integer getId() {
        return id;
    }

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

    public Set<TarifServProp> getTarifservprop() {
        return tarifservprop;
    }

    public void setTarifservprop(Set<TarifServProp> tarifservprop) {
        this.tarifservprop = tarifservprop;
    }

    public Integer getFkTarif() {
        return fkTarif;
    }

    public void setFkTarif(Integer fkTarif) {
        this.fkTarif = fkTarif;
    }

}

TarifServProp

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name = "TARIF_SERV_PROP", schema="TR")
public class TarifServProp implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", updatable = false, nullable = false)
    private Integer id;

    @Column(name = "FK_TARIF", updatable = false, nullable = false)
    private Integer fkTarif;

    public Integer getId() {
        return id;
    }

    @Column(name = "N1", updatable = false, nullable = false)
    private Integer n1;

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

    public Integer getFkTarif() {
        return fkTarif;
    }

    public void setFkTarif(Integer fkTarif) {
        this.fkTarif = fkTarif;
    }

    public Integer getN1() {
        return n1;
    }

    public void setN1(Integer n1) {
        this.n1 = n1;
    }

}

My test module:

    public static void main(String[] args) {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session sess = sf.openSession();
        sess.beginTransaction();

        TarifKlsk k2=sess.get(TarifKlsk.class, 1027303);
        for (TarifServProp t : k2.getTarifservprop()) {
             System.out.println("Tar="+t.getN1());
        }

        System.out.println("End init");

What am I doing wrong? I’ve checked all fields of these entities and all of them named properly….

Updt My POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.journaldev.hibernate</groupId>
    <artifactId>HibernateEHCacheExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <description>Hibernate Secondary Level Cache Example using EHCache implementation</description>

    <dependencies>
        <!-- Hibernate Core API -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <!-- EHCache Core APIs -->
        <!-- http://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.11</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>5.2.0.Final</version>
        </dependency>

        <!-- EHCache uses slf4j for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>
    </dependencies>
</project>

Upd2

I’ve found out that my child entity doesn’t contain records with fk_tarif corresponding to the fk_tarif from master… but I think it doesn’t matter, why is error exists?


It is bug in version 5.0 and 5.1.0 https://hibernate.atlassian.net/browse/HHH-10618

Issue

I want to have the relationship OneToMany between two entity but I have this error when I try to save object into database:

on console

java.lang.IllegalArgumentException: Can not set java.lang.Long field com.pi.MinuteBrico.models.Category.idCtegory to java.util.LinkedHashMap
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
    at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
    at java.base/java.lang.reflect.Field.get(Field.java:419) ~[na:na]

on psotman

org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Long com.pi.MinuteBrico.models.Category.idCtegory] by reflection for persistent property [com.pi.MinuteBrico.models.Category#idCtegory] : {name=Mecanique}; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long com.pi.MinuteBrico.models.Category.idCtegory] by reflection for persistent property [com.pi.MinuteBrico.models.Category#idCtegory] : {name=Mecanique}rntat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331)rntat org.springframework.orm.jpa.vendor.

my entities classes:

1: Bricoleur.java

    package com.pi.MinuteBrico.models;

import java.util.Map;
import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;




@Entity
@Table(name = "Bricoleur")
public class Bricoleur implements Serializable  {

    /**
     *@author iliass Alilou
     */
    private static final long serialVersionUID = 1L;
    /*@SequenceGenerator(
            name = "Bricoleur_sequence",
            sequenceName = "Bricoleur_sequence",
            allocationSize = 1
    )
    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "Bricoleur_sequence"
    )*/
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; 
    private String photo;
    private String firstName;
    private String lastName;
    private String email;
    private String phone;
    private String birthDate;
    private String adresse;
    
    @OneToMany(/*fetch = FetchType.LAZY , targetEntity = Category.class,*/ cascade = CascadeType.ALL)
    @JoinColumn(name = "BricoCategory_Bricoleur",referencedColumnName = "id")
    private List<Category> category ;
    

    public Bricoleur() {
        
    }
    public Bricoleur(String photo,
                     String firstName, 
                     String lastName, 
                     String email, 
                     String phone, 
                     String birthDate,
                     String adresse
                     ) {
        super();
        this.photo = photo;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.phone = phone;
        this.birthDate = birthDate;
        this.adresse = adresse;
    }
   // setters and getters
   ... ..
    
}

2:Category

    package com.pi.MinuteBrico.models;
import java.io.Serializable;

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

@Entity
@Table(name="Category")
public class Category implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idCtegory;    
    private String name;
    
    public Category() {
        
    }
    
    

    public Category(String name) {
        super();
        this.name = name;
    }

    // Stters and getters

    
}

JSON file to save

    {
    "photo":"test",
    "firstName":"iliass",
    "lastName":"alilou",
    "email":"[email protected]",
    "phone":"0654248574",
    "birthDate":"18/08/1999",
    "adresse":"xxxxxxxxxxxx",
     "category" : [
         {
             "name" : "Mecanique"
         },
         {
             "name" : "Plombie"
         }
     ] 
}

In my Controller

@CrossOrigin()
@PostMapping("/bricoleur")
public String create(@RequestBody Map<String, Object> bricoleurMap) {
    System.out.println(bricoleurMap);
    Bricoleur bricoleur = new Bricoleur(bricoleurMap);
    bricoleurService.saveBricoleur(bricoleur);
    return "Bricoleur ajouté";

}

Service

public Bricoleur saveBricoleur(Bricoleur bricoleur) {
    return bricoleurRepository.save(bricoleur);
}

Solution

The field category is of type List:

List<Category> category 

but it seems you are trying to assign a LinkedHashMap, that’s a Map.

Didn’t you mean to use a LinkedList?
We need to see how you are assigning the field category to help you more.

Answered By — Davide

1. Создаю таблицу в базе данных.

CREATE TABLE `Vendor` (
	`id` TINYINT(3) NOT NULL AUTO_INCREMENT COMMENT 'Счетчик записей',
	`vendorName` VARCHAR(100) NOT NULL DEFAULT '0' COMMENT 'Наименование производителя' COLLATE 'utf8mb4_0900_ai_ci',
	PRIMARY KEY (`id`) USING BTREE,
	INDEX `vendorName` (`vendorName`) USING BTREE
)
COMMENT='Таблица содержит информацию о наименовании производителя'
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB;

2. Создаю entity сущность

import lombok.*;
import javax.persistence.*;

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class Vendor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String vendorName;
}

3. Создаю hibernate.cfg.xml файл.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.url">jdbc:mysql://192.168.99.100:3306/NSH?allowPublicKeyRetrieval=true&amp;useSSL=false</property>
    <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="connection.username">root</property>
    <property name="connection.password">88224148</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping class="entity.Vendor"/>
  </session-factory>
</hibernate-configuration>

4. создаю класс HibernateUtil.

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();
                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);
                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();
                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }
    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

5. тест работает

@Test
    public void saveObjectToDatabase (){
        Vendor vendor = Vendor.builder().vendorName("Canon").build();
        Session session = HibernateUtil.getSessionFactory().openSession();
        if (session.isConnected()){
            try{
                session.beginTransaction();
                session.save(vendor);
                session.getTransaction().commit();
            } catch (HibernateException hibernateException){
                hibernateException.printStackTrace();
            } finally {
                session.clear();
                session.close();
                System.out.println("Save to database success!");
            }
        }
    }

6. сервис класс.

@Service
public class PrinterService {
    /**
     * This method save Vendor class to database.
     * @return 0 - if success, 2 - if database connection fails, 3 - if any error occur.
     */
    public int saveVendor(){
        Vendor vendor = Vendor.builder().vendorName("Canon").build();
        Session session = HibernateUtil.getSessionFactory().openSession();
        if (session.isConnected()){
            try{
                session.beginTransaction();
                session.save(vendor);
                session.getTransaction().commit();
            } catch (HibernateException hibernateException){
                hibernateException.printStackTrace();
                return 2;
            } finally {
                session.clear();
                session.close();
                System.out.println("Save to database success!");
            }
        } else {
            return 1;
        }
        return 0;
    }
}

Ошибка

org.hibernate.property.access.spi.PropertyAccessException:
Error accessing field [private java.lang.String entity.Vendor.vendorName] 
by reflection for persistent property [entity.Vendor#vendorName] : 
Vendor(id=0, vendorName=Canon)


  • Вопрос задан

    19 июл. 2022

  • 97 просмотров

Amadara

21 / 21 / 5

Регистрация: 17.12.2014

Сообщений: 322

1

13.07.2019, 14:32. Показов 5993. Ответов 5

Метки нет (Все метки)


Не понимаю в чем ошибка.
Идея в том что бы просто что бы взаимодействовать с базой данных.
JAVA+BootSpring+hibernate+PostGreSQL
РПосто тестовый проект JAVA
проект для IJ Idea

Bash
1
2
3
4
5
6
7
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String net.ttr43.ttr43.entity.setname.dataname] by reflection for persistent property [net.ttr43.ttr43.entity.setname#dataname] : net.ttr43.ttr43.entity.setname@1c2f7c2e
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75)
    at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert(GetterFieldImpl.java:90)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert(AbstractEntityTuplizer.java:559)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert(PojoEntityTuplizer.java:225)
    at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert(AbstractEntityPersister.java:5007)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:268)

Миниатюры

Ошибка org.hibernate.property.access.spi.PropertyAccessException: Error accessing field
 

Вложения

Тип файла: 7z ttr43.7z (309.5 Кб, 0 просмотров)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

13.07.2019, 14:53

2

возможно где-то надо геттеры/сеттеры добавить



0



21 / 21 / 5

Регистрация: 17.12.2014

Сообщений: 322

13.07.2019, 14:54

 [ТС]

3

Цитата
Сообщение от xoraxax
Посмотреть сообщение

возможно где-то надо геттеры/сеттеры добавить

не думаю, пробовал и в ручную и lombok

к тому же там 2 поля всего, просто тестовая база



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

13.07.2019, 15:34

4

Ну я понимаю, что ты не думаешь, но исключение то прочитай. Можешь загуглить заодно



0



21 / 21 / 5

Регистрация: 17.12.2014

Сообщений: 322

13.07.2019, 15:37

 [ТС]

5

Цитата
Сообщение от xoraxax
Посмотреть сообщение

Ну я понимаю, что ты не думаешь, но исключение то прочитай. Можешь загуглить заодно

я как бы просто офигеваю………. с одной строны, конечно спасибо, что что-то пишете..
но с другой стороны, нафига вообще писать посты типа «загугли»……..
зачем тратить на это время….

типо и так не ясно.почитай загугли…………

читал и гуглил, я х.з. что там не так, и х.з., что за ошибка



0



Amadara

21 / 21 / 5

Регистрация: 17.12.2014

Сообщений: 322

15.07.2019, 10:59

 [ТС]

6

Нашел.
в скрипте build.gradle было лишнее runtimeClasspath

Java
1
2
3
4
5
6
configurations {
    developmentOnly
//    runtimeClasspath {
//        extendsFrom developmentOnly
//    }
}



0



Like this post? Please share to your friends:
  • Hi9h ошибка домофона
  • Hi press ошибка кариер что делать 1300
  • Hi press ошибка кариер 750
  • Hi press ошибка кариер 1300 причина
  • Hi press ошибка кариер 1200