1

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)
Shadow
  • 33,525
  • 10
  • 51
  • 64
  • Use Spring Boot, which will configure Hibernate for you automatically (you just need to provide the database connection address), use `@Transactional`, and don't touch the obsolete `Session` interface. – chrylis -cautiouslyoptimistic- Nov 11 '18 at 18:47
  • @chrylis how might that look when I'm actually saving the entry? I've added the `@Transactional` annotation to the Person class. – Harry Brown Nov 11 '18 at 18:52
  • All you do is `personRepository.save(person);`. – chrylis -cautiouslyoptimistic- Nov 11 '18 at 19:28
  • And while you can remove 80% of the code and make your life simpler, also check specifically which Hibernate version you're using: https://hibernate.atlassian.net/browse/HHH-10618 – chrylis -cautiouslyoptimistic- Nov 11 '18 at 19:29
  • Thanks @chrylis - I've done that and the person does appear in the JSON. How does that data make it to the SQL database? When I used Session, it created the table but now, it doesn't. It seems like it's now not interacting with the SQL database at all. – Harry Brown Nov 11 '18 at 19:34

2 Answers2

0
@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.

CodeMaster
  • 171
  • 15
  • Thanks, but that didn't work either unfortunately. _Exactly_ the same exceptions. – Harry Brown Nov 11 '18 at 18:35
  • Can you please paste your database table details? Column names , table name etc as well ? It will be easier for us to trouble shoot. – CodeMaster Nov 11 '18 at 18:39
  • Primarily it appears that there is some trouble with your entity class. – CodeMaster Nov 11 '18 at 18:41
  • All I have done is create an empty database with no tables, letting the hibernate.cfg.xml create the tables? When I run the program, it creates a Person table but with no data. See edit – Harry Brown Nov 11 '18 at 18:45
0

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.