Spring mapping using hibernate - spring

I am joining two table using one to many relationship
my first table is role and second is roleCompany. where role_id is reference key in roleCompany table.
But when I am writting query to get all companies for specific id it showing me following error
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/myproject] threw exception [Request processing failed; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.test.myproject.domain.entity.RoleEntity.id] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Long field com.test.myproject.domain.entity.RoleEntity.id to java.lang.Long
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
My RoleEntity Class is :
#Entity
#Table(name = "roles")
public class RoleEntity {
#Id
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private Long id;
#Getter
#Setter
#Column(name = "role", nullable = false)
private String role;
#Getter
#Setter
#OneToMany(mappedBy = "roles")
List<RoleCompanyEntity> companyentities;
}
and my RoleCompanyEntity is
#NamedQueries({
#NamedQuery(name = RoleCompanyEntity.FIND_ROLE_COMPANY_BY_ROLE_ID, query = "select r.companyId, r.companyName from RoleCompanyEntity r where r.roles =:roleId")
})
#Entity
#Table(name = "role_company")
public class RoleCompanyEntity {
public static final String FIND_ROLE_COMPANY_BY_ROLE_ID = "findRoleCompanyByRoleId";
#Id
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "company_id", unique = true, nullable = false)
private Long companyId;
#Getter
#Setter
#Column(name = "company_name", unique = true, nullable = false)
private String companyName;
#Getter
#Setter
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="role_id", nullable=false)
private RoleEntity roles;
}

Related

#ManyToOne and #OneToMany ends up in unlimited loop when retrieved through profileRepository.getByProfileId(id);

Class Jobs has Many to One relationship with Profile.
When I retrieve through profileRepository.getByProfileId(id) the response returns recursive data.
Also if you notice Profile has Login object. I don't want to return that as well.
#Entity
#Table(name = "tbl_profile")
#Builder(toBuilder = true)
#NoArgsConstructor
#AllArgsConstructor
#Getter
public class Profile {
#Id
#Column(name = "profile_id")
#GeneratedValue(strategy = GenerationType.AUTO)
long profileId;
#NonNull
#Column(name = "name")
String name;
#Column(name = "description", nullable = false)
String description;
#OneToOne
#JoinColumn(name = "login_id",
referencedColumnName = "login_id")
Login login;
#OneToMany(
mappedBy = "profile"
)
List<Jobs> job;
Class Jobs
#Entity
#Table(name = "tbl_job")
#Builder(toBuilder = true)
#NoArgsConstructor
#AllArgsConstructor
#Getter
public class Jobs {
#Id
#Column(name = "job_id")
#GeneratedValue(strategy = GenerationType.AUTO)
long jobId;
#NonNull
#Column(name = "job_role", nullable = false)
String joRole;
#Column(name = "description", nullable = false)
String description;
#ManyToOne
#JoinColumn(name = "profile_id",
referencedColumnName = "profile_id")
Profile profile;
}
Use #JsonIgnore to the property to ignore the output on JSON. Also according to your business logic, recheck if you need bidirectional association. You could maybe add only unidirectional association.

JPA Repository.findByKeyEquals() returns not present value, but the value is exist on db

I'm developing an application that queries a database.
There are a few issues right now.
history.isPresent() == false when calling Optional<History> findByKeyEquals() intermittently. but value is exist on database
This is the information I got while tracking the issue.
All child entities are non-null.
In most cases, if the same function is re-executed, it is searched.
But sometimes it doesn't happen intermittently.
i think that i use incorrectly table relationship annotation (#OneToMany,#ManyToOne options..)
I want to solve this issue.
this is my code
History (Parent)
#Table(
indexes = {
#Index(columnList = "key", unique = true),
})
#Entity
#Getter
#ToString
#Audited
public class History implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(updatable = false, nullable = false, columnDefinition = "BIGINT UNSIGNED")
private Long id;
#Setter
#Column(nullable = false, columnDefinition = "CHAR(36)")
private String key = UUID.randomUUID().toString();
#Setter
#Temporal(TemporalType.TIMESTAMP)
#NotAudited
private Date started = new Date();
#Setter
#Temporal(TemporalType.TIMESTAMP)
#NotAudited
private Date finished;
#Setter
#OneToMany(
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "history",
orphanRemoval = true)
#NotAudited
private List<Content> contents = new ArrayList<>();
...
}
Content (Child)
#Table
#Entity
#Getter
#Audited
public class Content implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(updatable = false, nullable = false, columnDefinition = "BIGINT UNSIGNED")
private Long id;
#Setter
#Column(columnDefinition = "LONGTEXT")
#NotAudited
private String content;
#Setter
#ManyToOne(targetEntity = History.class, fetch = FetchType.Lazy, optional = false)
#Audited
private History history;
...
}
Repository
public interface HistoryRepository
extends JpaRepository<History, Long>, RevisionRepository<History, Long, Integer> {
Optional<History> findByKeyEquals(final String key);
}

Repeated column in mapping for entity #OneToOne should be mapped with insert="false" update="false"

Hi I am trying below Entity classes for JPA Operations . I am getting an error Repeated column in mapping for entity #OneToOne should be mapped with insert="false" update="false" for column LOAN_ID . I tried some options and tried to follow some suggestions in other posts but nothing seems work , every try its giving some error . What is the mistake i am doing .
LOAN_UNDERWRITING - PK is LOAN_ID
LOAN_UNDERWRITING_STATUS - PK is LOAN_ID and UWS_ADD_DATE
Loans - PK is LOAN_ID
Root Entity Class
public class Loans {
#OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name = "LOAN_ID")
private LoanUnderWriting loanUnderWriting;
}
LOAN_UNDERWRITING - Entity Class
#DynamicUpdate
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Table(name = "LOAN_UNDERWRITING")
#Entity
public class LoanUnderWriting {
#Id
#Column(name = "LOAN_ID")
private Long loanId;
#OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumns({
#JoinColumn(name = "UW_ADD_DATE"),
#JoinColumn(name = "LOAN_ID") })
private LoanUnderWritingStatus loanUnderWritingStatus;
}
LOAN_UNDERWRITING_STATUS-Entity Class
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Table(name = "LOAN_UNDERWRITING_STATUS")
#Entity
public class LoanUnderWritingStatus {
#EmbeddedId
private LoanUnderWritingStatusId loanUnderWritingStatusId;
}
LoanUnderWritingStatusId Class
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Embeddable
public class LoanUnderWritingStatusId implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "LOAN_ID")
private Long loanId;
#Column(name = "UWS_ADD_DATE")
private String uwsAddDate;
}
Your mapping should have insertable = false, updatable = false in LoanUnderWriting Entity for LoanUnderWritingStatus as showun below.
#DynamicUpdate
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Table(name = "LOAN_UNDERWRITING")
#Entity
public class LoanUnderWriting {
#Id
#Column(name = "LOAN_ID")
private Long loanId;
#OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumns({
#JoinColumn(name = "UW_ADD_DATE", referencedColumnName = "UW_ADD_DATE", insertable = false, updatable = false),
#JoinColumn(name = "LOAN_ID", referencedColumnName = "LOAN_ID", insertable = false, updatable = false) })
private LoanUnderWritingStatus loanUnderWritingStatus;
}

QueryDsl BooleanExpression - nested field is NULL

I want to create a predicate with QueryDSL and I don't know why but some nested field is NULL:
BooleanExpression emailSender = qFreight.message.account.user.id.eq(userId);
user is NULL.
qFreight.message.account.user gives me NPE error
And then in logs I have
.180 ERROR 7316 --- [nio-9090-exec-3] p.a.m.s.filter.JwtAuthorizationFilter : Request processing failed; nested exception is java.lang.NullPointerException
Of course I have generated QFreight, QMessage, QAccount, QUser... Where can bet the problem? I don't have any idea
UPDATE
My entities (the question is how to set #QueryInit properly):
#Entity
#Table(name = "freight")
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Freight {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
#QueryInit("*")
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "message_id")
private Message message;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
#Entity
#Table(name="message")
#Getter
#Setter
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "email_account_id", foreignKey = #ForeignKey(name = "FK_account_to_message"))
private Account account;
}
#Entity
#Table(name="account")
#Getter
#Setter
#NoArgsConstructor
#SuperBuilder(builderMethodName = "of")
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private User user;
}
qFreight.message.account.user.id is not a valid JPQL expression. You'd have to create the joins between the entities explicitly: JOIN qFreight.message message JOIN message.account account JOIN account.user user. In QueryDSL this would be: .join(qFreight.message, QMessage.message).join(QMessage.message.account, QAccount.account).join(QAccount.account.user, QUser.user).where(QUser.user.id.eq(...)).
Furthermore, the QueryDSL metamodel by default is only initialized one level deep. This is a performance decision. If you need the metamodel to be initialized deeper (even though usecases are rare, because JPQL lacks support for implicit joins), you have to use #QueryInits: http://www.querydsl.com/static/querydsl/4.4.0/reference/html_single/#d0e2265

Request processing failed; nested exception is java.lang.ClassCastException: Cannot cast java.lang.String to java.time.LocalDateTime] with root cause

I am using Java 1.8 & SpringBoot 2.3.4.RELEASE. I am trying to use the AuditingEntityListener and #MappedSuperclass features to populate the created_date and updated_date timestamps.
But I am getting this Exception: java.lang.ClassCastException: Cannot cast java.lang.String to java.time.LocalDateTime
I tried without #MappedSuperclass and it works.....but the created_date and updated_date fields are not getting populated.
Can anyone help me on this?
Here is the code snippet:
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class AuditableEntity implements Serializable {
#CreatedDate
#Column(name = "created_ts",nullable = false, updatable = false)
private LocalDateTime createdDate;
#LastModifiedBy
#Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;
#CreatedBy
#Column(name = "src_sys_cd",length = 15, updatable = false)
private String source;
#Version
#Column(name = "record_version_nb", length = 20, nullable = false)
private Long version;
}
----------------------------------
#Component
public class AuditorAwareImpl implements AuditorAware<String> {
#Value("${customer.service.source.code}")
private String auditor;
#Override
public Optional<String> getCurrentAuditor() {
return Optional.of(auditor);
}
}
----------------------------------
#Entity
#Setter
#Getter
#Builder
#Table(name = "customer_information")
#AllArgsConstructor
#NoArgsConstructor
public class CustomerEntity extends AuditableEntity {
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
}
#LastModifiedBy is used to set the current user when a modification happens. That is typically a String which can't be converted to anything date/time like and doesn't seem to be what you were looking for.
You should change this to:
#LastModifiedBy
#Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;
#LastModifiedDate
#Column(name = "updated_ts",nullable = false)
private LocalDateTime updatedDate;

Resources