简体   繁体   中英

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)
@Entity

@Table(name="Person") public class Person {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="person_id")
private long personId;

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

public Person() {
}

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

// getters and setters

}

You need to add some more annotations to this entity as mentioned in the above code. 1) @Column So that hibernate understands which column is mapped to which property in the entity ( This is not required if the column names and property names are same ) . The table column name needs to be mentioned as mentioned above.

All I wanted to do here was persist the data between starting and stopping the server, and be able to access the data via an SQL database. I solved the issue without using @Transactional or the Session interface, by just specifying the database you want Hibernate to use. Found here - thank you to @Master Slave.

Steps:

  1. Spin up a my SQL server and create a database
  2. Add an application.properties file to configure Spring to use that database
  3. The first time you run the app, set spring.jpa.hibernate.ddl-auto = to create . The next time, set it to update . This will persist that data across sessions.

application.properties: - use this for the first run only:

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

After bootRun , my_db will be populated with data. Stop your Spring server and restart it, but this time with spring.jpa.hibernate.ddl-auto=update in your application.properties .

Hope this helps somebody else who runs into similar issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM