Gustav Gustav - 1 year ago 75
Java Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download