Ronny Giezen
Ronny Giezen

Reputation: 645

Insert data in H2 database with Spring Boot JPA on post

I want to save data on a registration form from my Angular app to an H2 database using JPA spring boot. But when I do the post to Spring boot to save the user data I get a NullPointerException on the line that calls the save method. When I just return the user data back without saving the data it works fine, but not when saving the data.

The table that is created:

Hibernate: 
    
    create table user (
       id integer not null,
        email varchar(255),
        first_name varchar(255),
        last_name varchar(255),
        password varchar(255),
        primary key (id)
    )

My entity:

@Entity
public class User {

    @javax.persistence.Id
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    
    // getters, setters, and constructor, etc.

My repository:

@Repository
@Transactional
public class JPAUserRepository implements UserRepository {

    @Autowired
    private EntityManager em;

    @Override
    @Transactional
    public void save(User user) {
        em.createNativeQuery("INSERT INTO user (id, first_name, email, last_name, password)" +
                "VALUES (?,?,?,?,?)")
                .setParameter(1, user.getId())
                .setParameter(2, user.getFirstName())
                .setParameter(3, user.getEmail())
                .setParameter(4, user.getLastName())
                .setParameter(5, user.getPassword())
                .executeUpdate();
    }

The controller where I handle the post:

@RestController
public class Register {

private JPAUserRepository jpaUserRepository;

    @PostMapping(path = "/api/register", consumes = "application/json")
    public String addUser(@RequestBody User user) {

        jpaUserRepository.save(user);
        return "succesfull add";
    }

In the repository I have also tried em.persist(user) but that gave the same error.

Upvotes: 0

Views: 4991

Answers (3)

Aman
Aman

Reputation: 1754

There are three things I think might be the problem.

  1. You are generating the the id(@GeneratedValue), and again setting it manually and
  2. the use of @javax.persistence.Id and @Id.
  3. EntityManger should be injected as @PersistenceContext

So,

@Override
@Transactional
public void save(User user) {
    em.createNativeQuery("INSERT INTO user (first_name, email, last_name, password)" +
            "VALUES (?,?,?,?)")
            .setParameter(1, user.getFirstName())
            .setParameter(2, user.getEmail())
            .setParameter(3, user.getLastName())
            .setParameter(4, user.getPassword())
            .executeUpdate();
}

OR much convenient using jpa repos directly as stated by Thomas.

Upvotes: 1

Christian Desserich
Christian Desserich

Reputation: 592

Doesn't look like you're injecting the repo into your Register REST controller?

@Autowired private JPAUserRepository jpaUserRepository;

Upvotes: 1

Thomas
Thomas

Reputation: 471

Not sure where you error exactly comes from. But what I notices: You are inserting your user with the id provided, however it states @Generated at the Entity - so the ID should be generated and not provided. With Spring Boot you would usually have a Repository like this:

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

You don't need any extra Methods - with calling userRepository.save(..) a User will be persisted. I would recommend to look at https://bootify.io and create a running app, so you can check what is missing also config-wise.

Upvotes: 3

Related Questions