@thatmaniscool

Почему hibernate не сохраняет в базу данных?

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)
  • Вопрос задан
  • 239 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы