Spring Data JPA persistent object not updating - jpa

I have an issue with updating persistent objects. I have two objects "Admission" and "Location" as follows:
#Entity
#Table(name = "Admissions")
public class Admission implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(optional=false)
#JoinColumn(name="DemographicId", unique = true, nullable=false)
private Demographic demographic;
#OneToOne(optional=false)
#JoinColumn(name="VisitId", unique = true, nullable=false)
private Visit visit;
#OneToOne(optional=false)
#JoinColumn(name="LocationId", nullable=false)
private Location location;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "Updated", unique = false, nullable = false)
private Date updated;
#Entity
#Table(name = "Locations")
public class Location implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JoinColumn(name="FacilityId", nullable=true)
private Facility facility;
#JoinColumn(name="WardId", nullable=true)
private Ward ward;
#JoinColumn(name="RoomId", nullable=true)
private Room room;
#JoinColumn(name="BedId", nullable=true)
private Bed bed;
If I create an Admission and save it, all is well. If I then retrieve the Admission Update the Location to a new Location object the Admission does not save/update. The code I am using to save is:
public void transfer(MSH msh, PV1 pv1, PV2 pv2) {
String visitNumber = pv1.getVisitNumber().getIDNumber().getValue();
Visit myVisit = visitService.findByVisitNumber(visitNumber);
if (myVisit == null) {
log.debug("Unable to transfer if we have no Visit");
return;
}
Admission myAdmission = admissionService.findByVisit(myVisit);
myAdmission.setLocation(getLocation(msh, pv1));
}
I have tried doing a final save and flush (which does not seem to work), but understand that this should not be necessary.
An example of my service class
#Service
public class LocationServiceImpl implements LocationService {
#Resource
private LocationRepository repository;
#Transactional
public Location create(Location location) {
Location created = location;
return unique(created);
}
#Transactional
public Location findByLocation(Location location) {
return repository.findByLocation(location.getFacility(),
location.getWard(), location.getRoom(), location.getBed());
}
#Transactional
private Location unique(Location location) {
Location found = findByLocation(location);
if (found == null) {
return repository.save(location);
}
return found;
}
}

It seems that
public void transfer(MSH msh, PV1 pv1, PV2 pv2) {
Is not being executed within a transaction, please add #Transactional to your service class.

Related

How to find the specified field in spring-data-jpa

I want to find the specified field with the interface which extends JpaSpecificationExecutor.but i have not idea.
for example,i just need to find id,nickname in the user entity,what shall I do?
#Service
public class UserService {
public Page<User> findAll(User user, Pageable pageable) {
List<Predicate> predicates = new ArrayList<>();
if (user != null) {
//some condition
}
query.where(predicates.toArray(new Predicate[predicates.size()]));
return query.getRestriction();
}
}
#Repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
#Data
#Entity
#Table(name = "sys_user")
public class Note implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, unique = true)
private String email;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String nickname;
}
Here is answer on your question: https://www.baeldung.com/spring-data-jpa-projections .

org.springframework.dao.InvalidDataAccessResourceUsageException in spring data jpa

i have (one to many) and (many to one) bi-directional mappings while i am querying with #Query with spring- data-jpa using repository using foreign key iam getting InvalidDataAccessApiUsageException
#Entity(name="docket")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Docket implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="docket_Id")
private long Id;
#Column(name="docket_name")
private String docket_name;
#Column(name="area_in_kms")
private long area_in_kms;
#Column(name="number_of_connections")
private long number_of_connections;
#Column(name="number_of_sewer_connections")
private long number_of_sewer_connections;
#Column(name="number_of_manholes")
private long number_of_manholes;
#Column(name="deep_manholes")
private long deep_manholes;
#Column(name="contour_low")
private long contour_low;
#Column(name="contour_high")
private long contour_high;
#Column(name="length_of_sewermain_kms")
private long length_sewer_in_kms;
#JsonBackReference(value="section-details")
#ManyToOne(cascade= CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "section_Id")
private Section section;
#Entity(name="section")
#JsonIgnoreProperties(ignoreUnknown = true)
public class Section implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name="section_Id")
private long Id;
#Column(name="section_name")
private String section_name;
#Column(name="area_in_kms")
private long area_in_kms;
#Column(name="calculated_length")
private long calculated_length;
#Column(name="area_geometry")
private long area_geometry;
//#JsonManagedReference
#OneToMany(mappedBy = "section", cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private Set<Docket> docket;
#Repository
#Transactional(readOnly = true)
public interface DocketRepository extends JpaRepository<Docket, Long> {
#Modifying(clearAutomatically = true)
#Query(nativeQuery=true,value= "select d from docket d where d.section_id = :section_id" )
List<Docket> findAlldocketsforsection(#Param("section_id") long id);
need help!! on this i need to query more custom queries in this api please suggest me from where i am getting error

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

Spring Data JPA Specification Manyto One relationship

I have two entities in Spring Data JPA:
User--->* TaxPayment
The goal is to get the all the taxpayments related to user_id:
User.java
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
..........
}
TaxPayment.jva
public class TaxPayment implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name = "payment_date", nullable = false)
private LocalDate paymentDate;
#NotNull
#Column(name = "amount", precision=10, scale=2, nullable = false)
private BigDecimal amount;
#Column(name = "reference")
private String reference;
#ManyToOne
private User user;
public Long getId() {
return id;
}..
}
I dont wan't to have oneTOMany Annotation from User.java and the column mapped in the Taxpayment as user_id.
Specification class as follows:
final class TaxPaymentSpecification {
private TaxPaymentSpecification(){
}
static Specification<TaxPayment> hasUser(Long userId){
return new Specification<TaxPayment>() {
#Override
public Predicate toPredicate(Root<TaxPayment> arg0, CriteriaQuery<?> arg1,
CriteriaBuilder arg2) {
// TODO Auto-generated method stub
Root<TaxPayment> root = arg0;
Subquery<Long> subqry = arg1.subquery(Long.class);
Root<User> user = subqry.from(User.class);
final Join<User,TaxPayment> taxpays = root.join("user");
subqry.select(taxpays.<Long> get("user_id"));
subqry.where(arg2.equal(user.<Long> get("id"),userId));
return arg2.in(arg0.get("user_id")).value(subqry);
}
};
}
}
Is specification is correct or wrong as per my goal to get all the TaxPayment related to user_id?
There is no need to use subquery if you already know the userId, which will be the value of user_id in TaxPayment table:
#Override
public Predicate toPredicate(Root<TaxPayment> arg0, CriteriaQuery<?> arg1,
CriteriaBuilder arg2) {
return arg2.equal(arg0.get("user_id"), userId);
}

JPA Entity Mappings between two tables

I keep getting the following error with my Entity mappings.
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: edu.indstate.ics.transcript.web.dao.entity.Swrhxml.swbhxml in edu.indstate.ics.transcript.web.dao.entity.Swbhxml.swrhxmls
I am not sure what I am doing wrong. Could use some insight and help on what I am missing here.
My Entity classes are as follows:
#Entity
#Table(name = "SWBHXML" )
public class Swbhxml implements DatabaseObject, Serializable {
private List<Swrhxml> swrhxmls;
private static final long serialVersionUID = 1L;
private Long swbhxmlTransId;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SWBHXML_TRANS_ID", nullable = false)
public Long getSwbhxmlTransId() {
return swbhxmlTransId;
}
public void setSwbhxmlTransId(Long swbhxmlTransId) {
this.swbhxmlTransId = swbhxmlTransId;
}
#OneToMany(mappedBy = "swbhxml", cascade = CascadeType.ALL)
public List<Swrhxml> getSwrhxmls() {
return swrhxmls;
}
public void setSwrhxmls(List<Swrhxml> swrhxmls) {
this.swrhxmls = swrhxmls;
}
}
#Entity
#Table(name = "SWRHXML" )
public class Swrhxml implements DatabaseObject, Serializable {
private Swbhxml swbhxml;
private static final long serialVersionUID = 1L;
private Long SwrhxmlTransId;
private String SwrhxmlHxpsCode;
private Date SwrhxmlTimeStamp;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="SWBHXML_TRANS_ID")
public Swbhxml getSwrhxml() {
return swbhxml;
}
public void setSwrhxml(Swbhxml swbhxml) {
this.swbhxml = swbhxml;
}
#Column(name = "SWRHXML_HXPS_CODE", length = 15)
public String getSwrhxmlHxpsCode() {
return SwrhxmlHxpsCode;
}
public void setSwrhxmlHxpsCode(String SwrhxmlHxpsCode) {
this.SwrhxmlHxpsCode = SwrhxmlHxpsCode;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SWRHXML_TIMESTAMP", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getSwrhxmlTimeStamp() {
return SwrhxmlTimeStamp;
}
public void setSwrhxmlTimeStamp(Date SwrhxmlTimeStamp) {
this.SwrhxmlTimeStamp = SwrhxmlTimeStamp;
}
}
You use
`mappedBy = "swbhxml"`
^
|___ b here
, but the annotated association is
Swbhxml getSwrhxml()
^
|___ r here
Your getter and setter are named incorrectly. And frankly, with such cryptic and close entity names, you'll probably have many such bugs.