Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data JPA - mysql - findById() empty unless findAll() called before

I'm struggling with this strange error: the findById() method of a CrudRepository returns Optional.empty, unless findAll() is called before when using mysql.

e.g.

User

@Entity
public class User {

    @Id
    @GeneratedValue
    private UUID id;

    public UUID getId() {
        return id;
    }

}

UserRepository

public interface UserRepository extends CrudRepository<User, UUID> { }

UserService

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional
    public UUID create() {
        final User user = new User();
        userRepository.save(user);
        return user.getId();
    }

    @Transactional
    public User find(@PathVariable UUID userId) {
        // userRepository.findAll(); TODO without this functin call, Optinoal.empty is returned by the repo
        return userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException(String.format("missing user:%s", userId)));
    }
}

UserApp

@SpringBootApplication
public class UserApp {

    private static final Logger LOG = LoggerFactory.getLogger(UserApp.class);

    @Autowired
    private UserService userService;

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        final UUID userId = userService.create();
        final User user = userService.find(userId);
        LOG.info("found user: {}", user.getId());
    }

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }

}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/db_test
spring.datasource.username=springuser
spring.datasource.password=ThePassword

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.database=mysql

Why does the findAll() method call change the result of findById()?

Edit: Hibernate logs with findAll:

Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_ from user user0_

Without:

Hibernate: drop table if exists user
Hibernate: create table user (id binary(255) not null, primary key (id)) engine=MyISAM
Hibernate: insert into user (id) values (?)
Hibernate: select user0_.id as id1_0_0_ from user user0_ where user0_.id=?
like image 259
nagy.zsolt.hun Avatar asked Sep 04 '19 19:09

nagy.zsolt.hun


2 Answers

I was facing the same issue. The root cause was the mismatch between non-nullable @ManyToOne relation and the data persisted in table. I had this:

@ManyToOne(optional = false)
  @JoinColumn(name="batch_id")
  private Batch batch;

which means batch_id can't be null in any row. However, my rows had null value for batch_id foreign key. After removing optional = false (which is the expected business rule), findById started working as expected.

Got indication from this thread: I tired to do something with JpaRepository But Can not find row with findById ,

like image 130
vsingh Avatar answered Nov 15 '22 19:11

vsingh


As already written before (but more generically) after some tests my conclusion is that the issue occurs when there is a discrepancy of mandatory fields and database data in @ManyToOne relations. For example, imagine to have a table without constraints of mandatory fields, but at the same time your Hibernate model class with a @ManyToOne(optional = false) constraint. And imagine to populate the table (say with a SQL script), leaving the indicted field as null. When you will try to perform a findById(), a deleteById or whatever operation that implies a get by Id you will experience this (horrible) side effect.

like image 38
Fabrizio Sibeni Avatar answered Nov 15 '22 20:11

Fabrizio Sibeni