Insert data into the existing table of PostgreSQL 9 with Hibernate 5, JPA in Maven Project in Netbeans 8

You have table people created in mydb in PostgreSQL(id as serial and primary key and name columns). We create it in post:
Create table in pgAdmin 4 with autoincrement column
You have either Maven Project with Hibernate and JPA. We create this project in post:
Maven Project in Netbeans 8 with JPA 2, Hibernate 5 and PostgreSQL 9.6 database
So you may begin with create new entity with People name – the same name as table in database. Right click the name of project and choose New->Entity Class.

In Class Name write People and in Package field write your package.

Click the Finish button. You can see new class in package.

Open this file. Write new field – name. Generate set and get method for it in the same way as in last project for Department entity.

Save file. Open persistence.xml file. Check if the Table Generation Strategy is check as None. Why? because we have table so we not need to create or drop this table.

Save this file. Go to file and  change content for it in below.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class AddedData {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("net.doraprojects_AppMaven_jar_5.2.6.FinalPU");
EntityManager entityManager = entityManagerFactory.createEntityManager();

    People p = new People();


Run application. You see errors. It is a piece of output:
Why? Because we have in table serial id field but not sequence definition for autogenerate value of id. So we must change it.
Go to the entity class: and change generate from auto to IDENTITY:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class People implements Serializable {
    private static final long serialVersionUID = 1L;
  @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;
    private String name;

And run application and get data from database:

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.