Reputation: 93
After executing the query count (*), I get an unexpected error. I fulfilled this request using a workbanch graphical interface, everything is fine there. In my code, an error occurs. I can not understand the reason.
Here is the entity manager that performs my work with the database:
@PersistenceContext
private val entityManager: EntityManager? = null
fun count(request: HttpServletRequest): Int {
val query = entityManager!!.createNativeQuery("SELECT COUNT(*) FROM resume r", Resume::class.java)
return (query.getSingleResult() as Number).toInt()
}
This is a class the amount of which you need to get:
@Entity
@ValidWorkType
@ValidProfField
@ValidEducation
@ValidAddress
@ValidDescResume
data class Resume (
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null,
@ManyToOne(fetch = FetchType.LAZY)
var user: User? = null,
var datecreate: LocalDateTime = LocalDateTime.now(),
@get:Size(min = 1, max = 60, message = "{error.work.profession}")
var profession: String? = null,
@OneToOne(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], orphanRemoval = true)
@get:Valid
var numberPhone: NumberPhone? = null,
@get:Email(message = "{text.error.user.email}")
@get:Size(min = 1, max = 100, message = "{text.error.user.email.size}")
var email: String? = null,
@ManyToOne(cascade = [CascadeType.MERGE])
@get:NotNull(message = "{error.work.prof.field}")
override var profField: ProfField? = null,
@ManyToOne(cascade = [CascadeType.MERGE])
@get:NotNull(message = "{error.work.work.type}")
override var workType: WorkType? = null,
@OneToOne(cascade = [CascadeType.ALL], orphanRemoval = true)
@get:Valid
var wage: Wage? = null,
@ManyToOne
override var education: Education? = null,
var experience: Int? = null,
@OneToOne(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, orphanRemoval = true)
@get:Valid
override var description: DescriptionResume? = null,
@OneToOne(cascade = [CascadeType.ALL], orphanRemoval = true)
override var address: Address? = null,
@OneToOne(fetch = FetchType.LAZY, cascade = [CascadeType.ALL], orphanRemoval = true)
var photo: ContainerSquareImages? = null,
@OneToOne(cascade = [CascadeType.ALL], orphanRemoval = true)
var views: Views = Views(),
@Transient
var rating: Int? = null
): ParentWorkType, ParentProfField, ParentEducation, ParentAddress, ParentDescResume {
fun getPeriodExperience(): Period? {
if (experience!=null) {
return Period.between(LocalDate.now(), LocalDate.now().plusDays(experience!!.toLong()))
} else { return null }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Resume
if (user != other.user) return false
if (profession != other.profession) return false
if (numberPhone != other.numberPhone) return false
if (email != other.email) return false
if (profField != other.profField) return false
if (workType != other.workType) return false
if (wage != other.wage) return false
if (education != other.education) return false
if (experience != other.experience) return false
if (description != other.description) return false
if (address != other.address) return false
return true
}
override fun hashCode(): Int {
var result = user?.hashCode() ?: 0
result = 31 * result + (profession?.hashCode() ?: 0)
result = 31 * result + (numberPhone?.hashCode() ?: 0)
result = 31 * result + (email?.hashCode() ?: 0)
result = 31 * result + (profField?.hashCode() ?: 0)
result = 31 * result + (workType?.hashCode() ?: 0)
result = 31 * result + (wage?.hashCode() ?: 0)
result = 31 * result + (education?.hashCode() ?: 0)
result = 31 * result + (experience?.hashCode() ?: 0)
result = 31 * result + (description?.hashCode() ?: 0)
result = 31 * result + (address?.hashCode() ?: 0)
return result
}
fun getYearsCalendar() {
}
companion object {
const val NAME_PARAM = "resume"
}
}
Here is the error log itself can not understand why, and why, please help:
Hibernate: SELECT COUNT(*) FROM resume r
[WARN ] 2019-07-01 00:37:08.485 [http-nio-8080-exec-1] SqlExceptionHelper - SQL Error: 0, SQLState: S0022
[ERROR] 2019-07-01 00:37:08.485 [http-nio-8080-exec-1] SqlExceptionHelper - Column 'id' not found.
[ERROR] 2019-07-01 00:37:08.525 [http-nio-8080-exec-1] [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'id' not found.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.result.ResultSetImpl.findColumn(ResultSetImpl.java:581) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.result.ResultSetImpl.getLong(ResultSetImpl.java:928) ~[mysql-connector-java-8.0.15.jar:8.0.15]
Upvotes: 1
Views: 4707
Reputation: 5034
The doc for createNativeQuery reads :
Query createNativeQuery(String sqlString, Class resultClass)
sqlString - a native SQL query string
resultClass - the class of the resulting instance(s)
Your query is :
SELECT COUNT(*) FROM resume r
That is accessing the resume
table, but it is returning an Integer - not a resume
instance. That's why you are getting the Column 'id' not found.
.
The fix is simply to pass Integer as the result class, so :
val query = entityManager!!.createNativeQuery("SELECT COUNT(*) FROM resume r", Integer::class.java)
Since scalars are not mapped, the fix is to not pass a result class, so :
val query = entityManager!!.createNativeQuery("SELECT COUNT(*) FROM resume r")
Upvotes: 2
Reputation: 93
Solved the problem by using JPQL:
@PersistenceContext
private val entityManager: EntityManager? = null
fun count(request: HttpServletRequest): Long {
val query = entityManager!!.createQuery("SELECT COUNT(resume.id) FROM Resume resume")
return query.singleResult as Long
}
Upvotes: 0
Reputation: 82
With The javax.persistence.Query JPA interface : choose NamedQuery or TypedQuery
Example
@javax.persistence.NamedQuery(
name="resumeCountTest", query = "SELECT COUNT(*) FROM resume r")
public class Resume {
-------------
Query query = entityManager.createNamedQuery("resumeCountTest");
long resumeCount = query.getSingleResult();
return resumeCount ;
More informations Running JPA Queries
Upvotes: 0