Home > Software design >  Sequence "HIBERNATE_SEQUENCE" not found; SQL statement: select nextval ('hibernate_se
Sequence "HIBERNATE_SEQUENCE" not found; SQL statement: select nextval ('hibernate_se

Time:11-24

I was just testing my UserRepo class untill I got the error specified in the title. Some information: My Primary Key for the User table is Username (Which is a String provided by users that login into the application).

I have a production database with postgresql where all of this works just fine. For my testclasses I'm using an h2 db.

I have a User class:

@Getter
@Setter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "users")
public class User{
    @Id
    @NotBlank(message = "Username is required")
    private String username;
    @NotBlank(message = "Email is required")
    private String email;
    @NotBlank(message = "Password is required")
    private String password;

    @ManyToMany(cascade = CascadeType.ALL)
    private Collection<Role> roles = new ArrayList<>();

    private Instant created;
    private boolean enabled;
}

I have no userId since I wanted the usernames to be unique so I used that as my Id. My Test class:

@DataJpaTest
class UserRepoTest {

    @Autowired
    private UserRepo userRepo;

    @PersistenceContext
    private EntityManager entityManager;

    private static User userWithNameAdministrator;

    @BeforeAll
    static void beforeAll() {
        userWithNameAdministrator = UserBuilder.user("administrator", "[email protected]", "administrator").buildUser();
    }

    @Test
    void itShouldfindByUsername() {
        // given
        User expectedUser = userWithNameAdministrator;
        userRepo.save(expectedUser);
        // when
        String username = expectedUser.getUsername();
        User actualUser = userRepo.findByUsername(username);
        // then
        assertThat(actualUser).usingRecursiveComparison()
                .isEqualTo(expectedUser);
    }

And now my builder method for the user:

public static UserBuilder user(String username, String email, String role) {
        ArrayList<Role> roles = new ArrayList<>();
        roles.add(new Role(null, role));
        return user()
                .withUsername(username)
                .withEmail(email)
                .withEnabled(true)
                .withPassword("t")
                .withCreated(Instant.now())
                .withRoles(roles);
    }

This is another class in the Builder package.

At last my RepoClass:

@Repository
public interface UserRepo extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

After searching the web I've found that Hibernate is searching for a sequence but since I don't have a @GeneratedValue annotation it will use a default one. There is multiple questions about this but I didn't seem to find one with a custom Id (String) instead of long id

CodePudding user response:

Please create the sequence using SQL.

create sequence hibernate_sequence;

  • Related