首页 > 解决方案 > Spring - How to save Hibernate data to SQL server?

问题描述

I'm working on a Spring application with Hibernate. I'd like to save the data so that it persists even when starting and stopping the server. When attempting to save data to an SQL database, I run into a ton of exceptions so I stripped everything back and put together a simple, hello world style example by attempting to save an instance of a Person to the SQL database.

I've been through every thread I can find but they're all relating to relationships - this is just a single entity with no relationships. Any advice greatly appreciated!

Here's my attempt at saving an entry:

Person person = new Person("Some Person");
personRepository.save(person);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(person);
session.getTransaction().commit();

Exception:

Caused by: org.hibernate.property.access.spi.PropertyAccessException:
Error accessing field [private java.lang.String com.wdw.core.Person.name] by reflection for persistent property [com.wdw.core.Person#name] : com.wdw.core.Person@4a232870
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field com.wdw.core.Person.name to com.wdw.core.Person

Model:

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long personId;
    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    // getters and setters
}

Repository:

public interface PersonRepository  extends CrudRepository<Person, Long> {}

hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">true</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:8889/the_sideline</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="use_sql_comments">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.wdw.core.Person"/>
    </session-factory>
</hibernate-configuration>

EDIT: When I create an empty database with no tables and run the program, it creates the table Person with no entries:

mysql> use test_1
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------------+
| Tables_in_test_1
+---------------------------+
| Person                    |
+---------------------------+
1 row in set (0.00 sec)

mysql> select * from Person;
Empty set (0.00 sec)

标签: javahibernatespring-boot

解决方案


我在这里要做的就是在启动和停止服务器之间保留数据,并能够通过 SQL 数据库访问数据。我通过指定您希望 Hibernate 使用的数据库,在没有使用@Transactional或接口的情况下解决了这个问题。在这里Session找到- 感谢@Master Slave。

脚步:

  1. 启动我的 SQL 服务器并创建数据库
  2. 添加一个application.properties文件来配置 Spring 以使用该数据库
  3. 第一次运行应用程序时,设置spring.jpa.hibernate.ddl-auto =create. 下一次,将其设置为update. 这将在会话中保留该数据。

application.properties: -仅在第一次运行时使用:

spring.datasource.url=jdbc:mysql://localhost:8889/my_db
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

之后bootRunmy_db将填充数据。停止您的 Spring 服务器并重新启动它,但这次spring.jpa.hibernate.ddl-auto=update在您的application.properties.

希望这可以帮助遇到类似问题的其他人。


推荐阅读