SpringBoot (6) Spring Data JPA (1)
1. application.yml
This file is in the folder src/main/resources
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | spring: #--JPA datasource: #--Connection Pool hiraki: connectionTimeout: 20000 maximumPoolSize: 5 # PostgreSQL url: jdbc:postgresql://localhost:5432/mydb driver-class-name: org.postgresql.Driver username: user password: password jpa: hibernate: ddl-auto: update show-sql: true |
This will create or update tables
2. Defining Entities to persist
There are many entries where defining entities but an Entity needs:
- The @Entity annotation
- The@Audited annotation if you want a control version
- The @Table (name="table_name", schema = "myschema", uniqueConstraints..., indexes ..)
- All the related entities ( referenced in @OneToMany, @ManyToMany and ManyToOne) must be annotated with @Entity and @Audited (if any of the has the @Audited, then all classes should have this annotation also)
Common errors:
- One of the entities has no @Entity annotation
- One of the entities has no @Audited annotation and at least one of the related classes has this annotation
- The REVINFO table is in another schema and causes duplicity of unique constraints when being interfered with another schema. In this case, you should see Thorben Janssen and create these 2 classes:
This class adds "username" to the REVINFO table and has been got from Spring SecurityContextHolder
1 2 3 4 5 6 7 8 9 10 11 12 13 | package ximo.xotherapps.model.rrhh; import org.hibernate.envers.RevisionListener; import org.springframework.security.core.context.SecurityContextHolder; public class MyRevisionListener implements RevisionListener { @Override public void newRevision(Object revisionEntity) { MyRevInfoEnvers rev = (MyRevInfoEnvers) revisionEntity; rev.setUserName(SecurityContextHolder.getContext().getAuthentication().getName()); } } |
and this entity is for controlling the REVINFO table and having it in the same schema.
NOTE: When creating other schemas, the REVINFO table will be shared SO TAKE CARE !!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package ximo.xotherapps.model.rrhh; import org.hibernate.envers.DefaultRevisionEntity; import org.hibernate.envers.RevisionEntity; import jakarta.persistence.Entity; import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Table(name = "RevInfoEnvers", schema = "rrhh" ) @RevisionEntity(MyRevisionListener.class) public class MyRevInfoEnvers extends DefaultRevisionEntity { @Getter @Setter private String userName; } |
3. Using Repositories
If you are going to use only a few entities, you can use the default JPA repository, If you will you many Entities then you can use your own customized repository.
Comentarios
Publicar un comentario