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 AddedData.java
file and change content for it in below.
package doraprojects.net; 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(); entityManager.getTransaction().begin(); People p = new People(); p.setName("John"); entityManager.persist(p); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close(); } }
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: People.java
and change generate from auto to IDENTITY:
package doraprojects.net; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class People implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; ...