Search code examples
springdatabasehibernatespring-data-jpa

SQL Insert statement doesn't generate Id automatically


I'm currently learning Hibernate, and I plan to use a PreparedStatement to insert a record into the database. However, it seems that the insert query won't automatically generate a UUID for my record.

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user_details")
@SuperBuilder(toBuilder = true)
public class User extends Base {

    @NonNull
    @Column(unique = true)
    private String userName;
@Data
@MappedSuperclass
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
public class Base {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
}

DaoImplementation

    private static final String SAVE_USER = "INSERT INTO user_details(user_name) VALUES(?)";


@Override
    public UserDto saveUser(User user) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            connection = source.getConnection();
            ps = connection.prepareStatement(SAVE_USER);
            ps.setString(1, user.getUserName());

            try {
                ps.execute();
            }
            catch (Exception e) {
                log.error("Failed to save user to db");
            }
            return findUserByName(user.getUserName());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                closeAll(resultSet, ps, connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

Trying to understand why it doesn't not automatically generate id


Solution

  • You are mixing technologies here in a bad way.

    This configuration

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    

    Will cause JPA to generate a new UUID and set the id of your entity to it when persisting an entity using JPA.

    But you are not using JPA to persist your entity. You are using JDBC, which knows nothing about JPA annotations.

    If you use EntityManager.persist with your entity or (since you tagged the question ) CrudRepository.save, the id of the entity should get set as expected.