Spring Data JPA How to update data in table - spring-data-jpa

In spring data jpa ,I am trying to update data into account table.for update json data is coming from Angular Application.that json data is not present in one table. for example sdepname column not present is account table,sdepname column is in department table. I want to update respective sdepname primary key into account table.
For that I created new class for receiving data.I am passing receive data object to save method of Account repository.but i am getting error.
AccountModel
#Entity
#Table(name="account")
public class AccountModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_generator")
#SequenceGenerator(name="account_seq_generator", sequenceName = "account_seq")
public Integer naccountid;
public String namount;
public String sacctdesc;
public Integer naccountcpcmappingid;
public Integer nindirectcostrate;
public Integer nagencyid ;
public Integer ndeptid ;
public String sgrantnum;
public Timestamp dstartdate;
public Timestamp denddate;
public String slocation;
public String sclientacctid;
public Integer ninvestigatorid;
public Integer ninstid;
public Integer ntempaccountid;
#ManyToOne(optional = true,cascade = {CascadeType.MERGE})
#JoinColumn(name="ndeptid",insertable = false, updatable = false)
public DepartmentModel department;
#ManyToOne(optional = true,cascade = {CascadeType.ALL})
#JoinColumn(name="ninvestigatorid",insertable = false, updatable = false)
public InvestigatorModel investigator;
#ManyToOne(optional = true,cascade = {CascadeType.ALL})
#JoinColumn(name="naccountcpcmappingid",insertable = false, updatable = false)
public AccountCPCMappingModel accountCPC;
DepartmentModel
#Entity
#Table(name = "department")
public class DepartmentModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "department_seq_generator")
#SequenceGenerator(name="department_seq_generator", sequenceName = "department_seq")
public Integer ndeptid;
public String sdeptname ;
public Integer ninstid ;
public Boolean bislocked;
public String sclientdeptid;
public Integer nsurveymethodid;
public Boolean bisjointuse;
public Integer ntempdeptid;
public Boolean balternatejointusepercentage;
public Integer ndivid;
AccountCPCMappingModel
#Entity
#Table(name="accountcpcmapping")
public class AccountCPCMappingModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "accountcpcmapping_seq_generator")
#SequenceGenerator(name="accountcpcmapping_seq_generator", sequenceName = "accountcpcmapping_seq")
//#GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer naccountcpcmappingid;
public String sccpcode;
public Integer nmastercpcid;
public Integer ninstid;
public String sccpcname;
InvestigatorModel
#Entity
#Table(name="investigator")
public class InvestigatorModel implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "investigator_seq_generator")
#SequenceGenerator(name="investigator_seq_generator", sequenceName = "investigator_seq")
//#GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer ninvestigatorid;
public String sinvestigatorname;
public Integer ninstid ;
public String stitle;
public Integer ntempinvestigatorid;
public Integer nempid;
AccountMainSave
package com.demo.model;
public class AccountMainSave {
public Integer naccountid;
public String sclientacctid;
public String sacctdesc;
public String slocation;
public Integer ndeptid;
public String sdepname;
public Integer naccountcpcmappingid;
public String sccpcode;
public Integer ninvestigatorid;
public String sinvestigat
AccountController
#RestController
#RequestMapping("/SpaceStudy/SpaceAdmin")
public class AccountController
{
#Autowired
AccountRepository accRepo;
#CrossOrigin(origins="*")
#PutMapping("/AccountMaintenance/Save")
public List<AccountModel> btnSaveClick(#RequestBody AccountMainSave s)
{
List<AccountModel> objAcct=accRepo.findByNaccountid(s.naccountid);
if(objAcct!=null)
{
accRepo.save(s);
}
return objAcct;
}
}
AccountRepository
#Repository
public interface AccountRepository extends JpaRepository<AccountModel, Integer>{
List<AccountModel> findByNaccountid(Integer naccountid);
void save(AccountMainSave s);
}
I am getting This error in console
org.hibernate.MappingException: Unknown entity: com.demo.model.AccountMainSave
can any one help me what i am doing wrong in my application

AccountMainSave is not an Entity.
It is a simple POJO. If you want to save the whole Object you would have to make it an Entity and create a Repository like AccountRepository, say AccountMainSaveRepository for that Entity.
#Repository
public interface AccountMainSaveRepository extends JpaRepository<AccountMainSave, Integer>{
}
If you just want to update the Data that is already present in the Database then you should load the Entity which you want to update, set the new values and then save the updated entity with the save-Methode of the JPA-Repository

Related

#Transactional in spring JPA

I have a spring boot application where I need to update a migratedCustomer db table based on userId and phoneNumber.
Since I have to use for loop in the service layer for every update, it is creating a
new transaction and performance is hampered.
how could I make sure only one transaction is created and hence to improve the performance. code is like below
#Entity
#Table(name = "MigratedCustomer")
public class MigratedCustomer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String phoneNumber;
#Temporal(TemporalType.TIMESTAMP)
private Date createdTimestamp;
private int batchNumber;
private String comment;
}
public class MigratedCustomerService {
#Autowired
private UserRepository userRepository;
public void updateMsisdn(List<MigratedCustomer> savedCustomers) {
for (MigratedCustomer savedCustomer : savedCustomers) {
userRepository.updateStatus(savedCustomer.getUserId(),
savedCustomer.getPhoneNumber());
}
}
}
public interface MsisdnRepository extends JpaRepository<Msisdn, Long> {
#Modifying
#Query(value = "UPDATE Msisdn SET status=INACTIVE where userId=:userId and phoneNumber=:phoneNumber",
nativeQuery = true)
void updateStatus(#Param("userId") String userId, #Param("phoneNumber") String phoneNumber);
}

JPA composite Foreign Key part of composite Primary Key unable to find ID

We have tables,
'Lin_Code_Groups' with fields,
Project_ID (PK),
CG_ID(PK),
CG_Name
Corresponding entity class,
public class Lin_Code_Groups implements Serializable {
#EmbeddedId
private LinCodeGroupPK pk;
private String CG_name;
#Embeddable
public static class LinCodeGroupPK implements Serializable {
private Integer Project_ID;
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer CG_ID;
}
#OneToMany(mappedBy = "lin_Code_Groups")
private List<Lin_CG_Params> lin_CG_Params;
}
table Lin_CG_Params with fields,
Project_ID (PK)..FK to Lin_Code_Groups,
CG_ID(PK)...FK to Lin_Code_Groups,
Param_name(PK),
Param_value
Corresponding entity class,
public class Lin_CG_Params implements Serializable {
#EmbeddedId
private LinCodeGroupParamPK pk;
private String Param_value;
#Embeddable
public static class LinCodeGroupParamPK implements Serializable {
private String Param_name;
private LinCodeGroupPK linCodeGroupPK;
}
#MapsId("linCodeGroupPK")
#ManyToOne
#JoinColumns( {
#JoinColumn(name = "Project_ID",referencedColumnName= "Project_ID"),
#JoinColumn(name = "CG_ID",referencedColumnName= "CG_ID")
})
private Lin_Code_Groups lin_Code_Groups;
}
in controller class, i am using JPA's .Save method to save the data in to the tables.
#PostMapping(value = {"/hello"}, consumes = "application/json", produces = "application/json")
public ResponseEntity<Object> saveNewCodeGroupsDetails(#RequestBody Lin_Code_Groups objLin_Code_Groups ) {
respository.save(objLin_Code_Groups);
}
but getting an error 'Unable to find Lin_CG_Params with id Lin_CG_Params.LinCodeGroupParamPK'
Can anyone is please help ?

java.lang.NullPointerException: while filtering data using QueryDsl

I am using Spring data jpa for creating service. In following code I am using Querydsl for implementing search filter on grid. But for building name I am not able to filter the grid. I am getting
java.lang.NullPointerException: null.
For grid data is coming from multiple tables. I am not using joining for that. I mapped models classes with each other
#Service
public class RoomTransferService {
#Autowired
RoomTransferRepository roomTransferRepo;
#PersistenceContext
EntityManager em;
public List<RoomTransfer> findRoomTransfer(String sStatus, String sBuildName, String deptFrom, String deptTo) {
QRoomTransfer roomTransfer = QRoomTransfer.roomTransfer;
JPAQuery<RoomTransfer> query = new JPAQuery<RoomTransfer>(em);
query.from(roomTransfer);
// filter the details
if (sStatus != null) {
query.where(roomTransfer.sStatus.eq(sStatus));
}
// not filtering
if(sBuildName !=null) {
query.where(roomTransfer.roomDeptMap.room.building.sBuildName.eq(sBuildName));
}
List<RoomTransfer> QueryResultRoomTramsfer=query.fetch();
Return QueryResultRoomTramsfer;
Room class
#Entity
#Table(name = "room")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "room_seq_generator")
#SequenceGenerator(name = "room_seq_generator", sequenceName = "room_seq")
#Column(name = "nroom_id")
public Integer nRoomId;
#Column(name = "ncampus_id")
public Integer nCampusId;
#Column(name = "nbuild_id")
public Integer nBuildId;
#Column(name = "ninst_id")
public Integer nInstId;
#Column(name = "sfloor")
public String sFloor;
#Column(name = "sroom_number")
public String sRoomNumber;
#Column(name = "sroom_desc")
public String sRoomDesc;
#Column(name = "scomments")
public String sComments;
#Column(name = "daccepted_date")
public Timestamp dAcceptedDate;
#Column(name = "ssurveyor")
public String sSurveyor;
#Column(name = "narea")
public Integer nArea;
#Column(name = "ncrt_code_id")
public Integer nCRTCodeId;
#Column(name = "ncmn_room_bln")
public Integer nCMNRoomBln;
#Column(name = "nunvalidated_bln")
public Integer nUnvalidatedBln;
#Column(name = "sbfr_field")
public String sBfrField;
#Column(name = "ntemp_room_id")
public Integer nTempRoomId;
#Column(name = "bis_active")
public Boolean bIsActive;
#Column(name = "bis_jointuse")
public Boolean bIsJointuse;
#Column(name = "sstations_desc")
public String sStationsDesc;
#Column(name = "ddeleted_on")
public Timestamp dDeletedOn;
#Column(name = "ndeleted_by")
public Integer nDeletedBy;
#Column(name = "bis_incluster")
public Boolean bIsIncluster;
#Column(name = "bis_service_center_activity")
public Boolean bisServiceCenterActivity;
#Column(name = "service_center_comments")
public String serviceCenterComments;
#ManyToOne(optional = true)
#JoinColumn(name = "nbuild_id", insertable = false, updatable = false)
public Building building;
The NPE that you get is probably related to the limitation of QueryDsl where you cannot exceed four levels.
Your code exceeds four levels.
roomTransfer.roomDeptMap.room.building.sBuildName
You can read more on official documentation or related stackoverflow's question.
In the first link there is a solution to overcome this issue using QueryInit annotation.
If you do not want to alter your entity class you can perform a join (if possible) with an alias for the first 2 or 3 levels and then use this alias to complete the query.

Jpa Auditing dont save data in table auditing

I have to implementes Auditing in my aplication.. i inserting this data correctly
but i want to save all atributter from my Entity ,
Exemple, name, epigrafe, .. and olthers.
I implemented the mothod but dosent work, just dont save the atributte..
lets see..
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "logradouros_historico", schema = "aud")
public class LogradourosHistorico {
#Id
#GeneratedValue
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_logradouro")
private Logradouros logradouro;
#CreatedBy
private String modificadoPor;
#CreatedDate
#Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate = new Date();
#Enumerated(EnumType.STRING)
private Acoes acao;
#Column(name = "nome")
private String nome; //nome do logradouro
public LogradourosHistorico() {
super();
}
public LogradourosHistorico(Logradouros logradouro, String modificadoPor,
Acoes acao) {
super();
this.logradouro = logradouro;
this.modificadoPor = modificadoPor;
this.acao = acao;
}
//getters and setters
my class entityListner
public class LogradourosEntityListener {
#PostPersist
public void prePersist(Logradouros target) {
perform(target, Acoes.INSERTED);
}
#PreUpdate
public void preUpdate(Logradouros target) {
perform(target, Acoes.UPDATED);
}
#PreRemove
public void preRemove(Logradouros target) {
perform(target, Acoes.DELETED);
}
#Transactional()
private void perform(Logradouros target, Acoes acao) {
target.getNome();
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new LogradourosHistorico(target, acao));
}
}
my class Logradouros
#Entity
#EntityListeners(LogradourosEntityListener.class)
#Table(name = "logradouros", schema = "glb", uniqueConstraints= #UniqueConstraint(columnNames={"id_entidade", "idLogradouro"}))
public class Logradouros extends Auditable<String> implements Serializable {
private static final long serialVersionUID = 3703309412387185484L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idLogradouro;
#Column(name = "cep_geral")
private String cepGeral;
#Column(name = "epigrafe")
private String epigrafe;
#NotNull
#Column(name = "nome")
private String nome;
#Column(name = "nome_exibicao")
private String nomeExibicao;
#JoinColumn(name = "id_entidade")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Entidades entidade;
#NotNull
#JoinColumn(name = "id_municipio")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Municipios municipio;
// gettrs and settrs
so what i did wrong because i cant get the nome of entity Logradouros

How to correctly do a manytomany join table in JPA?

I need 3 entities: User, Contract (which are a many to many relation) and a middle entity: UserContract (this is needed to store some fields).
What I want to know is the correct way to define the relationships between these entities in JPA/EJB 3.0 so that the operations (persist, delete, etc) are OK.
For example, I want to create a User and its contracts and persist them in a easy way.
Currently what I have is this:
In User.java:
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private List<UserContract> userContract;
In Contract.java:
#OneToMany(mappedBy = "contract", fetch = FetchType.LAZY)
private Collection<UserContract> userContract;
And my UserContract.java:
#Entity
public class UserContract {
#EmbeddedId
private UserContractPK userContractPK;
#ManyToOne(optional = false)
private User user;
#ManyToOne(optional = false)
private Contract contract;
And my UserContractPK:
#Embeddable
public class UserContractPK implements Serializable {
#Column(nullable = false)
private long idContract;
#Column(nullable = false)
private String email;
Is this the best way to achieve my goals?
Everything looks right. My advice is to use #MappedSuperclass on top of #EmbeddedId:
#MappedSuperclass
public abstract class ModelBaseRelationship implements Serializable {
#Embeddable
public static class Id implements Serializable {
public Long entityId1;
public Long entityId2;
#Column(name = "ENTITY1_ID")
public Long getEntityId1() {
return entityId1;
}
#Column(name = "ENTITY2_ID")
public Long getEntityId2() {
return entityId2;
}
public Id() {
}
public Id(Long entityId1, Long entityId2) {
this.entityId1 = entityId1;
this.entityId2 = entityId2;
}
}
protected Id id = new Id();
#EmbeddedId
public Id getId() {
return id;
}
protected void setId(Id theId) {
id = theId;
}
}
I omitted obvious constructors/setters for readability. Then you can define UserContract as
#Entity
#AttributeOverrides( {
#AttributeOverride(name = "entityId1", column = #Column(name = "user_id")),
#AttributeOverride(name = "entityId2", column = #Column(name = "contract_id"))
})
public class UserContract extends ModelBaseRelationship {
That way you can share primary key implementation for other many-to-many join entities like UserContract.