JPA method for mapped column - java

I am trying to get how to write the JPA method for the class by using its foreign key instead of the primary key. Like, here I can't use findById() method, as it finds records according to primary key defined in the class. Below are the two classes for #ManyToOne and #OneToMany.
PARENT CLASS :
#Entity
#Getter
#Setter
//#Data
#NoArgsConstructor
#Table(name = "financial_plan_details", schema = "financialplanadmin")
public class FinancialPlanDao {
// This internalId is the primary key of the table.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "internal_plan_id")
private int internalId;
// This stores the plan status into the database table.
#Column(name = "plan_status")
#Size(max = 10)
private String planStatus;
#Column(name = "presentation_file_key")
#Size(max = 500)
private String presentationFileKey;
#Column(name = "create_timestamp")
#NotNull
private Timestamp createdTimestamp;
#OneToMany(mappedBy = "financialPlan")
private List<FinancialSubPlan> subPlans;
}
CHILD CLASS:
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "financial_plan_subplan", schema = "financialplanadmin")
#JsonInclude(Include.NON_NULL)
public class FinancialSubPlan {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "subplan_id")
private int subPlanId;
#Column(name = "external_subplan_id")
private String externalSubplanId;
#Column(name = "is_chosen")
private Boolean subPlanIsChosen;
#ManyToOne
#JoinColumn(name = "internal_plan_id")
private FinancialPlanDao financialPlan;
}
The table generated for FinancialSubPlan will consist of the primary key column "subplan_id" and foreign key column "Internal_plan_id". So is there any way to write the JPA method to get records of FinancialSubPlan by "internal_plan_id". Also how to get this using #Query ?

It would be something like this. IDE auto-suggest would help as you type, just in case.
findFinancialSubPlanByFinancialPlanDaoId(int internalId)
or
findFinancialSubPlanByFinancialPlanDao(int internalId)

Related

JPA null value in column "header_id" of relation "invoice" violates not-null constraint with PostgresSQL

Getting below Error while saving data
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "header_id" of relation "invoice" violates not-null constraint
Detail: Failing row contains (...null).
Header
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "header")
public class Header implements Serializable {
private static final long serialVersionUID = 3363186434410305269L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "header_id")
private Long headerId;
#Column(name = "submitted_by", length = 17)
private String submittedBy;
#OneToMany(mappedBy = "header", cascade = CascadeType.ALL)
#Builder.Default
private List<Invoice> invoices = new ArrayList<>();
}
Invoice
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "invoice")
public class Invoice implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "invoice_id")
private Long invoiceId;
#Column(name = "serial_no")
private Integer serialNo;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "header_id", nullable = false)
private Header header;
}
Please help me to solve the error.
I think this is because your headerId can be null because you use "Long" as type, wich is a good practice, but you should remove nullable = false inside Invoice.java.
Put nullable = false inside your database rules
If this problem does not come from there, check that the headerId of your Header class is not null when you create the object that you want to save in the database

How to retrieve ONE column from another table with Foreign key using Hibernate / JPA

I would like to use the Foreign key "MODEL_ID" to retrieve just one column "MODEL_NAME" from the TT_CARS table,
I tried the following code, that works but it returns the whole CARS object.
#JoinColumn(name = "MODEL_ID", referencedColumnName = "ID")
#ManyToOne(fetch = FetchType.EAGER)
private CARS cars;
Also I tried the code below, its also not working
#SecondaryTable(name = "TT_CARS", pkJoinColumns = #PrimaryKeyJoinColumn(name = "ID", referencedColumnName="MODEL_ID"))
Is there other way to retieve just the column (MODEL_NAME) using hibernate and JPA??
remarks: The modelName should be part of the Options class.
my code
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "TT_OPTIONS")
public class Options {
#Id
#Column(name = "ID")
private String id;
#NotNull
#Column(name = "DESCRIPTION", nullable = false)
private String description;
#Column(name = "MODEL_ID") // Foreign key
private Long modelId;
#Column(name = "MODEL_NAME", table = "TT_CARS") // this is the column name I would like to retrieve from the TT_CARS table
private String modelName;
// getters and setters
}
You can use #Formula. It is read-only calculated column that can be retrieved by the custom subquery. It does not present in the target table.
Defines a formula (derived value) which is a SQL fragment that acts as
a #Column alternative in most cases. Represents read-only state.
Example:
#Entity
#Table(name = "TT_OPTIONS")
public class Options {
#Id
#Column(name = "ID")
private Long id;
#Column(name = "DESCRIPTION", nullable = false)
private String description;
#Column(name = "MODEL_ID")
private Long modelId;
#Formula("(select TT_CARS.MODEL_NAME from TT_CARS where TT_CARS.ID = MODEL_ID)")
private String modelNameFormula;
}
#Entity
#Table(name = "TT_CARS")
public class Cars {
#Id
#Column(name = "ID")
private Long id;
#Column(name = "MODEL_NAME")
private String modelName;
}
Hibernate generated native query:
select
options0_.id as id1_4_0_,
options0_.description as descript2_4_0_,
options0_.model_id as model_id3_4_0_,
(select
TT_CARS.MODEL_NAME
from
TT_CARS
where
TT_CARS.ID = options0_.MODEL_ID) as formula1_0_
from
tt_options options0_
where
options0_.id=?
#SecondaryTable designed for #OneToOne relationship to map multiple tables to the same entity. It will not work for the #ManyToOne relationship.

PSQLException: ERROR: column does not exist

I have following entities:
#Entity
#Getter
#Setter
#Table(name = "nomenclature", schema = "public")
public class Nomenclature implements Serializable {
#Id
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#OneToMany
#JoinTable(name="nomenclature_versions",
joinColumns= #JoinColumn(name="nomenclature_id", referencedColumnName="id"))
private List<NomenclatureVersion> version;
}
and
#Entity
#Setter
#Getter
#Table(name = "nomenclature_versions", schema = "public")
#NoArgsConstructor
public class NomenclatureVersion implements Serializable {
#Id
#Generated(GenerationTime.INSERT)
#Column(name = "id")
private Long id;
#Column(name = "nomenclature_id")
private Long nomenclatureId;
#Column(name = "user_id")
private Long userId;
#Column(name = "creation_date")
private LocalDateTime creationDate;
#Column(name = "puls_code")
private String pulsCode;
#Column(name = "pic_url")
private String picUrl;
#Column(name = "current")
private boolean current;
}
When im trying to get Nomenclature with JPARepository getById(id) method im getting org.postgresql.util.PSQLException: ERROR: column version0_.version_id does not exist
It feels like the problem is around Hibernate Naming Strategies but i cant solve it.
Is there any other way to let Hibernate know which column should it use to join tables?
Don't use #JoinTable, the table is the same as the entity you are referencing. You just have to specify the #JoinColumn, hibernate will look for the column in the table referenced by the entity you are mapping the list to, NomenclatureVersion :
#OneToMany
#JoinColumn(name="nomenclature_id")
private List<NomenclatureVersion> version;

Hibernate "mappedby" doesn't finding the foreign key

I'm using hibernate to read my database datas but i'm having a issue with the relationship of the tables. My problems looks like that: mappedBy reference an unknown target entity property
and I read all the answers but I keep don't knowing where is the problem with my code.
Thats the class:
#Getter
#Setter
#Entity
#Table(name = "grupo_estudo_usuario")
public class EntidadeGrupoEstudoUsuario {
#Id
#Column(name = "id_grupo_estudo_usuario")
private int idGrupoEstudoUsuario;
#ManyToOne
#JoinColumn(name = "id_grupo_estudo")
private EntidadeGrupoDeEstudos idGrupoDeEstudos;
#ManyToOne
#JoinColumn(name = "id_usuario")
private EntidadeUsuario usuario;
#Column(name = "administrador")
private boolean administrador;
}
#Getter
#Setter
#Table(name = "grupo_estudo")
#Entity
public class EntidadeGrupoDeEstudos {
#Id
#Column(name = "id_grupo_estudo")
private int idGrupo;
#Column(name = "dt_atz")
private Date data;
#Column(name = "nm_grupo")
private String nomeDoGrupo;
#Column(name = "descricao")
private String descricao;
#Column(name = "privado")
private Boolean privado;
#OneToMany(mappedBy = "idGrupoDeEstudos")
private List<EntidadeGrupoDeEstudos> grupoEstudoUsuario;
}
The error message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: br.com.agrupauffs.grupo.EntidadeGrupoDeEstudos.idGrupoDeEstudos in br.com.agrupauffs.grupo.EntidadeGrupoDeEstudos.grupoEstudoUsuario
And the sql script:
CREATE TABLE public.grupo_estudo (
id_grupo_estudo bigint DEFAULT nextval('public.grupo_estudo_id_seq'::regclass) NOT NULL,
dt_atz timestamp(0) without time zone,
nm_grupo character varying,
descricao character varying,
privado boolean DEFAULT true NOT NULL
);
ALTER TABLE ONLY public.grupo_estudo
ADD CONSTRAINT grupo_estudo_pk PRIMARY KEY (id_grupo_estudo);
CREATE TABLE public.grupo_estudo_usuario (
id_grupo_estudo bigint NOT NULL,
id_usuario bigint NOT NULL,
administrador boolean,
dt_atz timestamp(0) without time zone,
id_grupo_estudo_usuario bigint DEFAULT nextval('public.grupo_estudo_usuario_id_seq'::regclass) NOT NULL );
ALTER TABLE ONLY public.grupo_estudo_usuario ADD CONSTRAINT grupo_estudo_usuario_pk PRIMARY KEY (id_grupo_estudo_usuario);
ALTER TABLE ONLY public.grupo_estudo_usuario ADD CONSTRAINT grupo_estudo_usuario_fk FOREIGN KEY (id_usuario) REFERENCES public.usuario(id_usuario);
ALTER TABLE ONLY public.grupo_estudo_usuario ADD CONSTRAINT grupo_estudo_usuario_fk_1 FOREIGN KEY (id_grupo_estudo) REFERENCES public.grupo_estudo(id_grupo_estudo);
Your mappedBy should be List<EntidadeGrupoEstudoUsuario> instead of List<EntidadeGrupoDeEstudos>
#OneToMany(mappedBy = "idGrupoDeEstudos")
private List<EntidadeGrupoEstudoUsuario> grupoEstudoUsuario;
So your Entities will look like
EntidadeGrupoEstudoUsuario Entity
#Getter
#Setter
#Entity
#Table(name = "grupo_estudo_usuario")
public class EntidadeGrupoEstudoUsuario {
#Id
#Column(name = "id_grupo_estudo_usuario")
private int idGrupoEstudoUsuario;
#ManyToOne
#JoinColumn(name = "id_grupo_estudo")
private EntidadeGrupoDeEstudos idGrupoDeEstudos;
#ManyToOne
#JoinColumn(name = "id_usuario")
private EntidadeUsuario usuario;
#Column(name = "administrador")
private boolean administrador;
}
EntidadeGrupoDeEstudos Entity
#Getter
#Setter
#Table(name = "grupo_estudo")
#Entity
public class EntidadeGrupoDeEstudos {
#Id
#Column(name = "id_grupo_estudo")
private int idGrupo;
#Column(name = "dt_atz")
private Date data;
#Column(name = "nm_grupo")
private String nomeDoGrupo;
#Column(name = "descricao")
private String descricao;
#Column(name = "privado")
private Boolean privado;
#OneToMany(mappedBy = "idGrupoDeEstudos")
private List<EntidadeGrupoEstudoUsuario> grupoEstudoUsuario;
}

Define hibernate entity from 3 tables

I'm working on a legacy application and I was asked to integrate Hibernate (this is my first time working with it). This app has 3 tables (among others) as follows:
Table SITE Table PARAMS Table TRANS
========== ============== ===============
pk: id (INT) pk: p_id (INT) pk: t_id (INT)
lang_id (INT) name (CHAR) fk: p_id (INT)
value (INT) fk: lang_id (INT)
text (CHAR)
Then I need to get the parameters from PARAMS along with their translations, stored in TRANS, according to the language defined for the application, which is stored in SITE.
I've been struggling trying to understand how to make a join of the tables to get the data for the entity. I tried using #JoinTable, but I couldn't figure out how to make a 3-way join, so I started trying with #SecondaryTables without luck.
I defined this entity to map the requested data (I know this won't work as it is now) and I'm trying to figure out the proper way to make the join.
#Entity
#Table(name = "params")
#SecondaryTables(
{
#SecondaryTable(name = "trans", pkJoinColumns = #PrimaryKeyJoinColumn(name = "p_id")),
})
public class Tparam implements Serializable
{
#Id
#GeneratedValue
#Column(name = "p_id")
private int id;
#Column(name = "name")
private String Name;
#Column(name = "text")
private String visibleText
...
}
Any help is appreciated!
For reference, this SQL query gives me what I want:
SELECT * FROM params, lang, site WHERE params.p_id = lang.p_id AND lang.lang_id = site.lang_id;
You need to define 3 entities :
1-Param
2-Lang
3-Site
#Entity
#Table(name = "params")
public class Tparam implements Serializable
{
#Id
#GeneratedValue
#Column(name = "p_id")
private int id;
#Column(name = "name")
private String Name;
#Column(name = "text")
private String visibleText
...
}
#Entity
#Table(name = "lang")
public class Lang implements Serializable
{
#Id
#GeneratedValue
#Column(name = "lang_id")
private int id;
#ManyToOne
#JoinColumn(name = "p_id")
private Tparam param;
...
}
#Entity
#Table(name = "site")
public class Site implements Serializable
{
#Id
#GeneratedValue
#Column(name = "site_id")
private int id;
#ManyToOne
#JoinColumn(name = "lang_id")
private Lang lang
...
}
Then, when you need the data you can use Criteria (or Query) on Site entity to fetch data. Each record of site contains one Lang and each of them contains one Tparam.

Categories

Resources