Get unique entity id from bean - java

I have 2 entities:
#Entity
#Table(name = "wpf_payment_attributes")
public class WpfPaymentAttributes implements Serializable {
private static final long serialVersionUID = -2629784870868584850L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 32)
private Integer wpf_payment_id;
#Column(length = 255)
private String name;
....
}
Second entity:
#Entity
#Table(name = "wpf_payments")
public class WpfPayments implements Serializable {
private static final long serialVersionUID = -5740164339503774805L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 4)
private Integer merchant_id;
.....
}
id is generated by the DB. I use this code to insert some data:
WpfPayments obj = new WpfPayments();
obj.setReference_transaction_id(12345678);
obj.setContract_id(contract.getId());
obj.setMerchant_id(merchant.getId());
wpfPaymentsService.saveOrUpdate(obj);
WpfPaymentAttributes attibutes = new WpfPaymentAttributes();
attibutes.setName("usage");
attibutes.setValue("Test Usage");
attibutes.setWpf_payment_id(...get here some how WpfPayments table id...id);
wpfPaymentAttributesService.saveOrUpdate(attibutes);
Do you know how I can get the id from the WpfPayments object and save it using attibutes.setWpf_payment_id(...)?

You should use JoinTable attributes with a setter to the entity instead of the id of WpfPayments.
The Id of WpfPayments is generated once you call the save method on the repository of this entity, just use the result of it.

Related

Hibernate One-to-One, When inserting, Why FK is null

When I run this code, it is running with out error. But When I check the values, as you can see, In the "Tbl_InstructorDetail" table the parentId is null
can anyone help.
thank you.
This is my Entities and my main class with table relation
enter image description here
this is my tables from my database
create table Tbl_Instructor
(
uuid int identity
constraint Pk_Tbl_Instructor_uuid
primary key,
Title nvarchar(50)
)
create table Tbl_InstructorDetail
(
uuid int identity
constraint Pk_Tbl_InstructorDetail_uuid
primary key,
Created_By nvarchar(50),
parentId int
constraint Fk_Tbl_InstructorDetail_Tbl_Instructor
references Tbl_Instructor
)
#Entity
#Table(name = "Tbl_InstructorDetail", schema = "dbo", catalog = "OJT_2021_KST")
public class TblInstructorDetailEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "uuid", nullable = false)
private int uuid;
#Basic
#Column(name = "Created_By", nullable = true, length = 50)
private String createdBy;
#Basic
#Column(name = "parentId", nullable = true,insertable = false,updatable = false)
private Integer parentId;
#OneToOne
#JoinColumn(name = "parentId",referencedColumnName="uuid")
private TblInstructorEntity instructorEntity;
#Entity
#Table(name = "Tbl_Instructor", schema = "dbo", catalog = "OJT_2021_KST")
public class TblInstructorEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "uuid", nullable = false)
private int uuid;
#Basic
#Column(name = "Title", nullable = true, length = 50)
private String title;
#OneToOne(mappedBy="instructorEntity",cascade = CascadeType.ALL)
private TblInstructorDetailEntity detailEntity;
Main class
TblInstructorEntity instructor = new TblInstructorEntity();
instructor.setTitle("This is a Test");
TblInstructorDetailEntity detail = new TblInstructorDetailEntity();
detail.setCreatedBy("Kyle");
instructor.setDetailEntity(detail);
session.getTransaction().begin();
session.save(instructor);
session.getTransaction().commit();
You don't need to add parentId in TblInstructorDetailEntity because it's referenced from TblInstructorEntity. In main class foreign key pass null because you can take a reference to the parent table before save parent table.
Here down is modified code:
Entity
#Entity
#Table(name = "Tbl_InstructorDetail", schema = "dbo", catalog = "OJT_2021_KST")
public class TblInstructorDetailEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "uuid", nullable = false)
private int uuid;
#Basic
#Column(name = "Created_By", nullable = true, length = 50)
private String createdBy;
// remove parentId column because it is foreign key
#OneToOne
#JoinColumn(name = "parentId",referencedColumnName="uuid")
private TblInstructorEntity instructorEntity;
// getter setter
}
#Entity
#Table(name = "Tbl_Instructor", schema = "dbo", catalog = "OJT_2021_KST")
public class TblInstructorEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "uuid", nullable = false)
private int uuid;
#Basic
#Column(name = "Title", nullable = true, length = 50)
private String title;
#OneToOne(mappedBy="instructorEntity",cascade = CascadeType.ALL)
private TblInstructorDetailEntity detailEntity;
// getter setter
}
Main
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
TblInstructorEntity instructor = new TblInstructorEntity();
instructor.setTitle("This is a Test");
TblInstructorDetailEntity detail = new TblInstructorDetailEntity();
detail.setCreatedBy("Kyle");
session.save(instructor); // Save parent entity
detail.setInstructorEntity(instructor); // Reference from parent entity
session.save(detail); // Save child entity
session.getTransaction().commit();
HibernateUtil.shutdown();

Entity with #EmbeddedId , #GeneratedValue and #ManyToOne

I worked with postgres database, I have a Conventionnement entity with ManyToOne relationship with convention and organization, I want to create 3 primary keys convention_id, organization_id and the GeneratedValue id, i used #Embeddable like the below example, but I had the below error
Caused by: org.hibernate.annotations.common.AssertionFailure:
Declaring class is not found in the inheritance state hierarchy:
ConventionnementIdentity
and when I moved the id in Conventionnement class i had this error
ConventionnementIdentity must not have #Id properties when used as an
#EmbeddedId
#Entity
#Table(name = "conventionnement")
public class Conventionnement implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ConventionnementIdentity conventionnementIdentity;
#MapsId("convention_id")
#ManyToOne
private Convention convention;
#MapsId("organization_id")
#ManyToOne
private Organization organization;
//getter and setter
}
#Embeddable
public class ConventionnementIdentity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "convention_id", insertable = false, updatable = false)
private Long conventionId;
#Column(name = "organization_id", insertable = false, updatable = false)
private Long organizationId;
//getter and setter
}
You have defined an #EmbeddedId, but inside it you declare another #Id, thus the error. Make the generated id point to the correct id column in your table (below I've assumed "id" as column name):
#Embeddable
public class ConventionnementIdentity implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator", sequenceName="YOUR_DB_SEQ", allocationSize=1)
private Long id;
#Column(name = "convention_id", insertable = false, updatable = false)
private Long conventionId;
#Column(name = "organization_id", insertable = false, updatable = false)
private Long organizationId;
//getter and setter
}

JPA - wrong number of column. should be 2

A Foreign key refering br.com.copagaz.inova.mobile.persistencia.entidade.viagem.nf.NFeProtocolo from br.com.copagaz.inova.mobile.persistencia.entidade.viagem.nf.NfCabeca has the wrong number of column. should be 2
My problem is in one column reference, if i remove #ManyToOne and #JoinColumn(name = "protocolo"), the system works but the selects does not.
i tried to use hibernate.hbm2ddl.auto to auto create the FKs but with no success.
I think the nfe_operacao use a composed PK, and nf_cabeca reference's ii, but did not work.
Any one could help?
#Entity
#Table(name = "nf_cabeca", schema = "mobile", uniqueConstraints =
{#UniqueConstraint(columnNames =
{"NUMERO_FILIAL","serie_nota","numero_nota"})})
public class NfCabeca implements java.io.Serializable {
private static final long serialVersionUID = -921687831233770627L;
#Id
#SequenceGenerator(name = "nf_cabeca_sequencial_seq", sequenceName = "nf_cabeca_sequencial_seq", schema = "mobile", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "nf_cabeca_sequencial_seq")
#Column(name = "sequencial", insertable = false, updatable = false)
private long sequencial;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "data_hora", nullable = false, length = 29)
private Date dataHora;
#Column(name = "valor_total", nullable = false, precision = 17, scale = 17)
private Double valorTotal;
#Column(name = "cancelada")
private Integer cancelada;
#Temporal(TemporalType.DATE)
#Column(name = "data_vencimento", length = 13)
private Date dataVencimento;
#Column(name = "boleto", length = 17)
private String boleto;
#ManyToOne
#JoinColumn(name = "protocolo")
private NFeProtocolo protocolo;
#Column(name = "chave")
private String chave;
#Column(name = "status_nf")
private Integer statusNf;
#Column(name = "status_danfe")
private Integer statusDanfe;
#Column(name = "modelo", length = 3)
private String modelo;
#Column(name = "reconciliada")
private boolean reconciliada = false;
#OneToMany(mappedBy = "nfCabeca", cascade = CascadeType.MERGE)
private List<NfObservacao> nfObservacao;
#OneToMany(mappedBy = "nfCabeca", cascade = CascadeType.ALL)
private List<NfItens> nfItens;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "nf_cabeca")
private List<NFeProtocolo> protocolos = new ArrayList<NFeProtocolo>();
}
This references this table:
#Entity
#IdClass(NFeProtocoloId.class)
#Table(name = "nfe_protocolo", schema = "mobile")
public class NFeProtocolo implements Serializable {
private static final long serialVersionUID = 2092981840170296102L;
#Id
#Column(name = "nf_cabeca", length = 100, insertable = false, updatable = false)
private long nf_cabeca_id;
#Id
#Column(name = "protocolo", length = 100)
private String protocolo;
#Column(name = "operacao", length = 15, nullable = false)
#Enumerated(EnumType.STRING)
private NFeProtocoloOperacao operacao;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "data_hora", length = 29, nullable = false)
private Date dataHora;
#Column(name = "status", length = 10)
private String status;
}
I think the problem is that your #ManyToOne mapping is not correctly declared. As the the entity NFeProtocolo has a composite primary key, you should use #JoinColumns annotation that consists of an array of #JoinColumn annotations:
#ManyToOne
#JoinColumns({#JoinColumn(name = "nf_cabeca_id", referncedColumnName="nf_cabeca_id"),
#JoinColumn(name= "protocolo", referencedColumnName="protocolo")})
private NFeProtocolo protocolo;
You can choose an appropriate name as a foreign key column name.
A Foreign key refering br.com.copagaz.inova.mobile.persistencia.entidade.viagem.nf.NFeProtocolo from br.com.copagaz.inova.mobile.persistencia.entidade.viagem.nf.NfCabeca has the wrong number of column. should be 2
Your problem is simple: Your Entity NFeProtocolo has a composite Id with two columns:
public class NFeProtocolo implements Serializable {
#Id
#Column(name = "nf_cabeca", length = 100, insertable = false, updatable = false)
private long nf_cabeca_id;
#Id
#Column(name = "protocolo", length = 100)
private String protocolo;
But your class NfCabeca is referencing it through only one column:
public class NfCabeca implements java.io.Serializable {
#ManyToOne
#JoinColumn(name = "protocolo")
private NFeProtocolo protocolo;
The solution:
A composite primary key is usually made up of two or more primitive or JDK object types.
As you have a composite key, you should use an Embeddable key, there are many examples about it like this, this and this.

Hibernate reverse one to one undirectional mapping

I have two classes Cards and CardBalance. In my DB sсhema table card_balance has foreign key on table cards. But in ORM I want that entity Cards has properties CardBalance, and entity CardBalance does't have propertie Cards.
I try do this in next way:
#Entity
#Table(name = "CARD_BALANCE")
public class CardBalance {
#Id
#Column(name = "BALANCE_ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CARD_BALANCE_SEQ")
#SequenceGenerator(name = "CARD_BALANCE_SEQ", sequenceName = "CARD_BALANCE_SEQ")
private Long balanceId;
#Column(name="CARD_ID")
private Long cardId;
}
#Entity
#Table(name = "CARDS")
public class Cards implements Serializable {
#Id
#Column(name = "CARD_ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CARDS_SEQ")
#SequenceGenerator(name = "CARDS_SEQ", sequenceName = "CARDS_SEQ")
private Long cardId;
#Column(name = "CARD_NAME", length = 30, unique = true)
private String cardName;
#Column(name="PERSON_ID")
private Long personId;
#Column(name = "CARD_KEY", nullable = false)
private long cardKey;
#OneToOne
#JoinColumn(name="TYPE_ID", nullable = false)
private TypeCard typeCard;
#OneToOne
#JoinColumn(name="CARD_ID", nullable = false)
private CardBalance cardBalance;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="CARD_ID")
public Set<BalanceHist> balanceHists = new HashSet<>();
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="CARD_ID")
public Set<Events> events = new HashSet<>();
}
but it does't work. How I can solve this problem?
First of all, you have a mistake in your #JoinColumn, it should be:
#OneToOne
#JoinColumn(name="BALANCE_ID", nullable = false)
private CardBalance cardBalance;

JPA, MappedSuperclass, Column ID cannot accept NULL

I had tables like Customer, Request and so on and each had ID field;
I have now an abstract
#MappedSuperclass instead that have
#Id
#GeneratedValue
private Long id
field, and all tables extends it with
#AttributeOverride(name="id", column=#Column(name="ID_CUSTOMER"). but now, when I'm trying to add customer to a table, I'm getting exception: Column ID_Customer cannot accept Null value.
when each table had it's own id fields, all works fine.
what's wrong?
Thanks
#MappedSuperclass
public abstract class GeneralEntity implements Serializable,Cloneable{
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "CREATED",nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Column(name = "MODIFIED")
#Temporal(TemporalType.TIMESTAMP)
private Date modified;
//getters,setters
#Entity
#Table(name = "CUSTOMER")
#AttributeOverrides({
#AttributeOverride(name = "id", column = #Column(name="ID_CUSTOMER")),
#AttributeOverride(name="created", column=#Column(name="CUSTOMER_REGISTERED",nullable = false))
})
public class Customer extends GeneralEntity{
// #Column(name = "ID_CUSTOMER")
// #Id
// #GeneratedValue
// private Long id;
#Column(name = "CUSTOMER_EMAIL", nullable = false, length = 25, unique = true, updatable = true)
private String email;
#Column(name="CUSTOMER_PASSWORD", nullable = false)
private String password;
//getters setters

Categories