Fabrizio
Fabrizio

Reputation: 89

Spring Boot repository save does not work (only shows a select)

I'm facing for hours with a strange proceeding in Spring Boot when try to save a mapped entity.

The entity class with a composite key that must all be set by the user is as follows:

package model

import javax.persistence.*

@Entity
@Table(name = 'MY_TABLE')
@IdClass(MyIdClass.class)
class MyClass implements Serializable{

    @Id
    @Column(name = "MY_COLUMN_1")
    Long column1

    @Id
    @Column(name = "MY_COLUMN_2")
    Long column2

    @Id
    @Column(name = "MY_COLUMN_3")
    String column3

    @Id
    @Column(name = "MY_COLUMN_4")
    Date date1

    @Column(name = "MY_COLUMN_5")
    Date date2

    @Column(name = "MY_COLUMN_6")
    BigDecimal column6
}

@Embeddable
class MyIdClass implements Serializable{
    Long column1
    Long column2
    String column3
    Date date1;
}

The corresponding repository is:

package repository

import org.springframework.data.repository.CrudRepository

interface MyRepository extends CrudRepository<MyClass, Long>{
}

My service is:

package service

import model.MyClass
import repository.MyRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class MyService {

    @Autowired
    MyRepository repository

    void save(MyClass myClass) {
        repository.save(myClass)
    }
}

My controller mounts a MyClass object with all data set, including the composite key. When it calls the service save method the object is not inserted in the database. I saw the logs and checked that there is a SELECT in MY_TABLE instead of INSERT. I tried not to inform the composite key in the object and then the save method did an INSERT with error due to null values in the primary key.

I really don't understand why the insertion is not done when the composite key has values. How can I solve it?

I've already tried with @Transactional in service class and didn't work. I didn't do any Transaction configuration in the project since Spring Boot delivers it as default.

Thanks.

Upvotes: 1

Views: 21820

Answers (2)

Sujit
Sujit

Reputation: 476

I take your code sample and tried it on a sample Spring Boot project, where I was able to save to H2 DB (In memory) with @Embeddable & @EmbeddedId annotations. If you would like to verify, you can clone the GitHub repo and run the BootJpaApplication.java as a Java Application. After execution access the H2 console with the below link from local where table details can be verified.

http://localhost:8080/h2-console enter image description here https://github.com/sujittripathy/springboot-sample.git

Hope the detail helps:)

Upvotes: 1

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

It seems you are using MyIdClass as the Id for MyClass. So, the Repository should be:

interface MyRepository extends CrudRepository<MyClass, MyIdClass>{
}

Hope this help.

Upvotes: 4

Related Questions