Gustav
Gustav

Reputation: 177

How to insert data into JPA Entity table using a setters method from class?

Heres how I created the table and defined a set method:

@Entity
@Table(name = "Book")
public class Book extends AbstractPersistable<Long> {

@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;

public void setContent (String name) {
    this.name = name;
}
}

From the controller this is how I am trying to set the content:`

@RequestMapping("/addBook")
@ResponseBody
public String addBook(@RequestParam("name") String name) {
    Book book = new Book();
    book.setContent(name);
    return name;        
}

When I set a new content from addBook page using the name parameter value, the content shows up on the same page. Now what I am trying to do is to insert more content to the table but I am not sure if the content is inserted to the table or not. I need to add more contents to the table. Is the setContent method updating or inserting content? And how am I supposed to see the table if it has contents?

Upvotes: 1

Views: 4729

Answers (2)

Subhasish Sahu
Subhasish Sahu

Reputation: 1339

@Gustav - Are you also looking for something like --> what is the sql getting generated along with parameter passed ?

Then you can use something

  @Bean
  public Map<String, String> jpaProperties() {
    Map<String, String> props = new HashMap<>();
    props.put("eclipselink.logging.level.sql", "FINE");
    props.put("eclipselink.logging.parameters", "true");
    return props;
}

Upvotes: 0

A Sdi
A Sdi

Reputation: 665

I assume that you have a spring repository to perform CRUD operations something like

public interface BookRepository extends JpaRepository<Book ,Long> {

}

Then in your controller class you have

@Autowired
private BookRepository repo;

now in your addBook method you can save book objects this ways

@RequestMapping("/addBook")
@ResponseBody
public String addBook(@RequestParam("name") String name) {
    Book book = new Book();
    book.setContent(name);
    repo.save(book);
    return name;        
}

your book object now will be added to your DB

Upvotes: 1

Related Questions