0

I've been trying to create a new Student field that could be added into my MySQL database.

I'm using Spring Boot, MySQL Workbench and from my understanding everything is just as it should be - yet - it's still not working correctly.

This is how my Student class look like:

@Entity
@Table(name = "studenttab")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "sname")
    private String name;
    @Column(name = "scourse")
    private String course;
    @Column(name = "sfee")
    private Double fee;

And this is how my test method looks like:

 @Test
    void testCreateStudent() {
        Student student = new Student();
        student.setName("Łukasz");
        student.setCourse("WoW-Best-Gold-Guide");
        student.setFee(100.00);
        studentRepository.save(student);
    }

StudentRepository is just extending a CrudRepository.

It seems like Hibernate is not able to create Ids automatically, which should be done by @GeneratedValue annotation. Not sure what's wrong and what I can do to repair it.

¯_( ツ )_/¯

PaulNUK
  • 4,774
  • 2
  • 30
  • 58
Vinci
  • 341
  • 1
  • 5
  • 18

1 Answers1

0

You have choosen @GeneratedValue(strategy = GenerationType.IDENTITY) - which means that you leave id-generation to database identity column (i.e. auto-incremented column in the database). So you can:

  1. Update database: make id field in the studenttab table auto-incremented on database level.

  2. Or update Hibernate id-generation strategy to AUTO or remove it at all which is the same (as AUTO is the default strategy). In that case Hibernate will create id's on its own based on the id java-type.

    @Id @GeneratedValue private Long id;

Note: since Hibernate 5.x in AUTO-mode, by default, uses db-sequences to generate the new ids, the 2nd approach will work only in the databases which support sequences.

If DB does not support sequences, Hibernate will use Table-generator for id-generation. So it will look for hibernate_sequence table, which you should either create by yourself or Hibernate can create it for you, if you set spring.jpa.hibernate.ddl-auto property to update or create.

If you are using Hibernate earlier than 5.x, or using 5.x and spring.jpa.hibernate.use-new-id-generator-mappings= false, it will use again IDENTITY by default and you will see the same error.

For more details read here (all answers, not the accepted one): Table 'DBNAME.hibernate_sequence' doesn't exist

Sve Kamenska
  • 371
  • 3
  • 6
  • I did try changing GeneratioType to AUTO, didn't help, same error – Vinci May 20 '22 at 13:49
  • @Vinci, so you need to try the 1st approach. Hibernate uses sequences for id-generation and MySQL does not support them. There are workarounds for that (using additional tables as a sequence), so the easiest way is to make id column auto-incremented. – Sve Kamenska May 20 '22 at 15:03
  • Please, see the updated answer – Sve Kamenska May 20 '22 at 15:55