Why getting org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! when joining 3 tables - spring-boot

I have three entity basicInfo, gender and department. If I join with basicInfo and gender model then it works fine but when want to join department along with other two entities same time then showing
.QuerySyntaxException: Path expected for join!
My Three entity classes here,
#Entity
#Table(name = "employeebasicinfo")
public class BasicInfoModel {
#Id private String employeeId;
#NotBlank private String firstName;
#NotBlank private String lastName;
#NotNull private Integer companyId;
#Transient private String companyName;
private String phoneNo;
#Column(name = "sex")
private char sexId;
#Transient private String sexName;
#Temporal(TemporalType.TIMESTAMP)
private Date birthDate;
#Temporal(TemporalType.TIMESTAMP)
private Date joiningDate;
#NotNull private Integer department;
#Transient private String departmentName;
#ManyToOne()
#JoinColumn(name = "sex", referencedColumnName = "id", insertable = false, updatable = false)
private GenderModel genderModel;
#ManyToOne
#JoinColumn(
name = "department",
referencedColumnName = "id",
insertable = false,
updatable = false)
private DepartmentModel departmentModel;
// getter setter
}
Gender Model
#Entity
#Table(name = "gender")
public class GenderModel implements Serializable {
#Id
#Column(name = "id")
private char id;
#Column(name = "name")
private String name;
//getter setter
}
And Department model
#Entity
#Table(name = "department")
public class DepartmentModel {
#Id private int id;
private String name;
//getter setter
}
My Dto class
public class BasicInfoDto {
private String employeeId;
private String firstName;
private String lastName;
private Integer companyId;
private String companyName;
private String phoneNo;
private char sexId;
private String sexName;
private Date birthDate;
private Date joiningDate;
private Integer department;
private String departmentName;
public BasicInfoDto(char sexId, String sexName, int department, String departmentName) {
this.sexId = sexId;
this.sexName = sexName;
this.department = department;
this.departmentName = departmentName;
//getter setter
}
My Repository class is below:
#Repository
public interface BasicInfoRepository extends JpaRepository<BasicInfoModel, String> {
#Query(
value =
"SELECT new com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ("
+ " a.sexId, b.name, a.department,c.name) FROM "
+ " BasicInfoModel a INNER JOIN GenderModel b on a.sexId = b.id" +
" INNER JOIN DepartmentMode c on a.department = c.id")
List<BasicInfoDto> getBasicInfoList();
}
And finally I am getting this error
Caused by: java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for
join! [SELECT new
com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ( a.sexId,
b.name, a.department,c.name) FROM
com.employeeAttendance.employeeAttendance.model.BasicInfoModel a INNER
JOIN com.employeeAttendance.employeeAttendance.model.GenderModel b on
a.sexId = b.id INNER JOIN DepartmentMode c on a.department = c.id]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at com.sun.proxy.$Proxy109.createQuery(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
~[spring-data-jpa-2.1.4.RELEASE.jar:2.1.4.RELEASE]
... 76 common frames omitted
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [SELECT new
com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ( a.sexId,
b.name, a.department,c.name) FROM
com.employeeAttendance.employeeAttendance.model.BasicInfoModel a INNER
JOIN com.employeeAttendance.employeeAttendance.model.GenderModel b on
a.sexId = b.id INNER JOIN DepartmentMode c on a.department = c.id]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:277)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:191)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:119)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:595)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:704)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
... 84 common frames omitted
However, if I remove 2nd join with department then it work fine.

You are working on the entity properties in jpql not on tables. So you only tell jpql which property to use to join:
"SELECT new com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ("
+ " a.sexId, b.name, a.department,c.name) FROM "
+ " BasicInfoModel a INNER JOIN a.genderModel b "
+ " INNER JOIN a.departmentModel c";

Related

Hibernate - Query Result contains null and throws expection

I have two tables, TBL_MARKET_WATCH_NAME (Master) and TBL_MARKET_WATCH (Details) connected through an MW_ID column in MySQL. I'm using hibernate and doing a LEFT JOIN on these two tables to fetch data. Most of the time the Details table may not have data for the connecting ID column from left table which results in null values in resultset.
Master table is defined as
#Entity(name = "TBL_MARKET_WATCH_NAME")
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "MW_ID")
private List<MarketWatchScripDetailsDTO> mwDetailsDTO;
#Column(name = "MW_ID")
private Integer mwId;
#Column(name = "USER_ID")
private String userId;
#Column(name = "MW_NAME")
private String mwName;
The Details table is defined as below
#Entity(name = "TBL_MARKET_WATCH")
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "USER_ID")
private String userId;
#Column(name = "MW_ID")
private Integer mwId;
#Column(name = "SCRIP_NAME")
private String scripName;
In Master table, I have data like below
In Details table, I have data as below
I have a left join query running on Hibernate as below
#Transactional
#Query(value = "SELECT A.mwName as mwName, B.userId as userId, B.mwId as mwId, B.scripName as scripName FROM TBL_MARKET_WATCH_NAME as A LEFT JOIN A.mwDetailsDTO B on A.mwId = B.mwId and A.userId = B.userId where A.userId = :pUserId")
When running the query and converting it into an object my resultset is as below
List<Object> getUserScripDetailsNew(#Param("pUserId") String pUserId);
[
"LIST0",
"650156",
1,
"NATURALGAS 26OCT22 FUT",
],
.... <***some more data***>
[
"LIST2",
null,
null,
null
]
Instead of List if I use model interface like the one defined below, I'm getting null pointer exception because it is not able to convert null values to integer.
List<MwTblResponseModel> getUserScripDetailsNew(#Param("pUserId") String pUserId);
public interface MwTblResponseModel {
public String getMwName();
public String getUserId();
public Integer getMwId();
public String getScripName();
}
The error is as below.
java.lang.NullPointerException
at in.codifi.marketwatch.model.MwTblResponseModel_e3fe8bfde9ba7f8b10664ce55c6c5ef842396ab4.convert_getUserScripDetailsNew(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl$$function$$1.apply(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at org.hibernate.query.spi.StreamDecorator.collect(StreamDecorator.java:209)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl.getUserScripDetailsNew(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass.getUserScripDetailsNew$$superforward1(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass$$function$$8.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:53)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:40)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass.getUserScripDetailsNew(Unknown Source)
How to make sure when null values are coming from Query to assign 0 in final response?

QueryDSL Null Pointer exception left join unrelated tables

I have got two tables which are unrelated . Below are the entity classes .
UsersStaging
#Entity
#Table(name = "users_staging")
#Data
public class Usersstaging implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
#Column(name = "id", updatable = false, nullable = false)
private Integer id;
#Column(name = "employee_id", length = 10)
private String employeeId;
#Column(name="user_name")
private String userName;
#Column(name = "email")
private String email;
Roles table
#Entity
#Table(name = "user_roles")
#Data
#TypeDefs({ #TypeDef(name = "json", typeClass = JsonType.class) })
public class UserRoles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "employeeId", length = 10)
private String employeeId;
#Column(name = "username")
private String username;
#Type(type = "json")
#Column(name = "roles", columnDefinition = "json")
private List<String> roles;
}
I am trying to write the below query by using left join on username column. Query works fine as long as there are predicates(exp) for UsersStaging table . But if I add a predicate for userRoles table (roleExp) , the query fails .
JPAQuery<UsersStaging> query = new JPAQuery<>(entityManager);
QUsersStaging usersStagingPath = QUsersStaging.usersStaging;
QUserRoles userRolesPath = QUserRoles.userRoles;
BooleanExpression exp = usersStagingPath.legalFirstName
.containsIgnoreCase(criteria.getValue());
BooleanExpression roleExp = userRolesPath.roles.any().eq("SUPERADMIN");
return query
.select(Projections.constructor(UsersStagingDTO.class, usersStagingPath.employeeId,
usersStagingPath.userName, usersStagingPath.email, usersStagingPath.isActive,
usersStagingPath.legalFirstName, usersStagingPath.legalLastName, usersStagingPath.legalFullName,
userRolesPath.roles))
.from(usersStagingPath).leftJoin(userRolesPath).on(usersStagingPath.userName.eq(userRolesPath.username))
.where(exp.and(roleExp)).limit(10).fetch();
}
Getting the below exception
java.lang.NullPointerException: null
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromJoinElement(HqlSqlWalker.java:432) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.joinElement(HqlSqlBaseWalker.java:4007) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3793) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3671) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:746) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:602) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:5020) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4713) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2180) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2108) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:841) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
I was able to resolve it . The issue was that roles field is a json type column and JSON_CONTAINS function is not supported by Hibernate yet .
To fix it , I implemented the MetadataBuilderContributor interface .
public class SQLFunctionContributor implements MetadataBuilderContributor {
#Override
public void contribute(MetadataBuilder metadataBuilder) {
metadataBuilder.applySqlFunction("json_contains_key",
new SQLFunctionTemplate(BooleanType.INSTANCE, "JSON_CONTAINS(?1, JSON_QUOTE(?2))"));
}
}
Add the below line in application.properties so that Hibernate can register the contrib SQL function .
spring.jpa.properties.hibernate.metadata_builder_contributor=com.xxx.xxx.utils.SQLFunctionContributor
I modified my query in below way and no issues.
BooleanExpression roleExp = Expressions.booleanTemplate("json_contains_key({0}, {1})", userRolesPath.roles,
Expressions.constant(criteria.getValue())).isTrue();

Trying to Convert a SQL Query to a JPA Query

I want to convert this sql query to a JPA query, but I can't seem make sense of it... Should I use findByMarinaIdAndMovementGroupMeanId?? or findByMarinaIdAndMovementGroupMeanIdAndMovementMeanId??
Sql:
select m.* from movement_group m
join movement_group_mean mgm on m.id = mgm.movement_group_id
join movement_mean mm on mgm.movement_mean_id = mm.id
where mm.id = 1 and m.marina_id = :marinaId and mm.active = true;
MovementGroup:
#Entity
public class MovementGroup {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String code;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private Boolean active;
private String iconUrl;
#OneToMany(mappedBy = "movementGroup")
private Set<MovementGroupMean> movementGroupMeans;
#JsonIgnore
#ManyToOne()
#JoinColumn(name = "marina_id")
private Marina marina;
MovementGroupMean:
#Entity
public class MovementGroupMean {
#EmbeddedId
#JsonIgnore
private MovementGroupMeanPK movementGroupMeanPK;
#JsonBackReference
#ManyToOne
#JoinColumn(name = "movement_group_id", insertable = false, updatable = false)
private MovementGroup movementGroup;
#ManyToOne
#JoinColumn(name = "movement_mean_id", insertable = false, updatable = false)
private MovementMean movementMean;
MovementMean:
#Entity
public class MovementMean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#Enumerated(EnumType.STRING)
private MovementMeanType movementMeanType;
private Boolean active;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
#JsonBackReference
#ManyToOne()
#JoinColumn(name = "marina_id")
private Marina marina;
Not sure where the problem lies, so excuse the lengthy explanation on SQL->JPQL:
Replace your table names with your entity names
movement_group -> MovementGroup
Replace your joins with the java references, letting JPA use the relationship mapping you've defined instead.
"join movement_group_mean mgm on m.id = mgm.movement_group_id" becomes "join m.movementGroupMeans mgm"
"join movement_mean mm on mgm.movement_mean_id = mm.id becomes "join mgm.movementMean mm"
Only tricky spot is your entities do not define a basic mapping for the marina_id value. So to get at m.marina_id, you will have to use the 'marina' reference and use its presumably ID value:
"m.marina_id = :marinaId" -> "m.marina.id = :marinaId"
Giving you JPQL:
"Select m from MovementGroup m join m.movementGroupMeans mgm join mgm.movementMean mm where mm.id = 1 and m.marina.id = :marinaId and mm.active = true"

Emulating a LEFT JOIN in Spring Entity

In effect, what I am trying to do is this...
SELECT a.*, b.description, c.description FROM a
LEFT JOIN b ON b.code = a.b_code
LEFT JOIN c ON c.code = a.c_code
I would like to map this entirely using Spring/JPA framework. I've played around with #SecondaryTable only to find out that it will not work in thie case, and I've been getting a number of errors while trying to map it using #OneToOne or #JoinColumn. Here are my current entity classes...
#Entity
#Table(name = "a")
public class a {
#Id
#Column(name = "id")
private String id;
#Column(name = "b_code")
private String bCode;
//I'd like to have b.description here
#Column(name = "c_code")
private String cCode;
//I'd like to have c.description here
}
#Entity
#Table(name = "b")
public class b {
#Column(name = "code")
private String code;
#Column(name = "description")
private String description;
}
#Entity
#Table(name = "c")
public class c {
#Column(name = "code")
private String code;
#Column(name = "description")
private String description;
}
You need to use #JoinColumn with referencedColumnName as shown below.
#Entity
#Table(name = "a")
public class a {
#Id
#Column(name = "id")
private String id;
#Column(name = "b_code")
private String bCode;
//I'd like to have b.description here
#Column(name = "c_code")
private String cCode;
//I'd like to have c.description here
#OneToOne // this should be based on your joining
#JoinColumn(name = "b_code", referencedColumnName = "code", insertable = false, updatable = false)
B b;
#OneToOne// this should be based on your joining
#JoinColumn(name = "c_code", referencedColumnName = "code", insertable = false, updatable = false)
C c;
}
#Entity
#Table(name = "b")
public class B {
#Column(name = "code")
private String code;
#Column(name = "description")
private String description;
}
#Entity
#Table(name = "c")
public class C {
#Column(name = "code")
private String code;
#Column(name = "description")
private String description;
}

TransactionSystemException when #Scheduled is used

When I want to use #Scheduled, it throws org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
When I tried to use noRollbackFor=TransactionSystemException - it does not help either...
I even tried to use propagation=NEVER and then the code does not work,because it needs to be transactional. Iam getting those documents ok, but I cannot do blockDocument(document).
How to make it work?
Thank you in advance
#Component
public class ScheduleService {
#Autowired
private DocumentService documentService;
#Scheduled(cron = "0 33 13 * * ?")
public void blockPassedDocuments() {
List<Document> passedDocuments = documentService.getAllPassedDocuments();
if (passedDocuments != null) {
System.out.println("blocked docs "+ passedDocuments.size());
passedDocuments.forEach(document -> documentService.blockDocument(document));
}
}
}
#Service
#Transactional
public class DocumentService {
#Autowired
private DocumentRepository documentRepository;
#Autowired
private UserService userService;
#Autowired
private EmailService emailService;
#Transactional(noRollbackFor = TransactionSystemException.class)
public void blockDocument(Document document){
documentRepository.blockDocument(document);
}
// repository
#Override
public void blockDocument(Document document) {
DocumentState documentState = getDocumentState(3);
document.setDocumentState(documentState);
entityManager.merge(document);
}
#Entity
#Table(name = "document_state")
public class DocumentState {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotBlank(message = "State is mandatory")
#Size(min=1, max=60)
#Column(length = 60)
private String state;
#JsonIgnore
#OneToMany(mappedBy = "documentState", cascade= CascadeType.ALL)
private List<Document> documents;
public DocumentState(){
}
#Entity
public class Document {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(unique = true, length = 60, nullable = false)
#NotBlank(message = "Name is mandatory")
private String name;
#NotBlank(message = "Title is mandatory")
#Size(min = 3, max = 15)
#Column(length = 15, nullable = false)
private String title;
#NotBlank(message = "Description is mandatory")
#Size(min = 3, max = 255)
#Column(length = 255, nullable = false)
private String description;
#ManyToOne
#JoinColumn(name = "document_state_id", nullable = false)
private DocumentState documentState;
#JsonIgnore
#Column(name = "resource_path", length = 255, nullable = false)
private String resourcePath;
#Column(name = "upload_datetime", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "UploadDateTime is mandatory")
private Date uploadDatetime;
#Column(name = "approval_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Approval end time is mandatory")
private Date approvalEndTime;
#Column(name = "active_start_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active start time is mandatory")
private Date activeStartTime;
#Column(name = "active_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active end time is mandatory")
private Date activeEndTime;
#OneToMany(mappedBy = "document", cascade= CascadeType.ALL, orphanRemoval = true)
private Set<UsersDocuments> documentsForUsers = new HashSet<>();
#ManyToOne
#JoinColumn(name="user_id")
private User user;
public DocumentState getDocumentState() {
return documentState;
}
EDIT STACK:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:541) ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at com.patrikmaryska.bc_prace.bc_prace.service.ScheduleService$$EnhancerBySpringCGLIB$$68ed607b.blockPassedDocuments(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]
Add the #Transactional annotation on blockPassedDocuments method.
Add the #Transactional annotation on ScheduleService class.

Resources