Given the following db structure:
And having the following mapping for this structure:
#Entity
#Table(name = "a")
class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private int aId;
#Column(name = "title")
private String title;
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = aId)")
private Integer count;
}
My aim is to get the count of all references to A from B (where aId in the query is the value of the current entity).
But I get following Error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLException: Unknown column 'a0_.aId' in 'where clause'
As Simon mentioned you need to use the name of the column, not the attribute name. In your example above this would be:
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = id)")
You have to use the name of the column not the attribute name:
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = a_id)")
Related
i'm trying to execute this query inside the spring boot repository class , but console shows the error ' column id not found ' also the postman shows:
"status": 500,
"error": "Internal Server Error",
"message": "could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query",
QUERY REPOSITORY
#Query(nativeQuery=true, value="SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= :year")
public List<User> findALLUserByyear(#Param("year") String year);
CONTROLLER
#GetMapping(value="/etablissementAlls/{year}")
public EtablissementDto EtabDTOALL(#PathVariable String year) {
EtablissementDto a = new EtablissementDto();
a.setUsers(userRepository.findALLUserByyear(year));
return a;
}
Stack Trace
2021-05-05 11:14:17.600 WARN 5240 --- [nio-8020-exec-2] org.club.config.JwtRequestFilter : JWT Token does not begin with Bearer String
2021-05-05 11:14:17.604 WARN 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S0022
2021-05-05 11:14:17.604 ERROR 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'id' not found.
2021-05-05 11:14:17.606 ERROR 5240 --- [nio-8020-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1080) ~[mysql-connector-java-5.1.46.jar:5.1.46]
NOTE
I tested this query in MYSQL PHPmyAdmin, and it works fine
USER ENTITY
#Entity
#Table(name = "app_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "is_active")
private boolean active;
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
#JoinTable(name = "user_etablissement", joinColumns
= #JoinColumn(name = "user_id",
referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "etablissement_id",
referencedColumnName = "id"))
private List<Etablissement> etablissements;
Clarify few things:
The MYSQL PHPmyAdmin you have queried on and the service you are connecting database to are pointing to the same database server?
Have you checked manually if 'id' column is created in the tables you are querying to?
You should change your query if you have create_time field in User entity
#Query(value="SELECT u from User u where year(u.creatdate_time)=:year")
public List<User> findALLUserByyear(#Param("year") String year);
I was hopping to find an answer to my probleme on this here forum. My problem is as follows, I have two classes :
#Entity
#Table(name = "a")
public class A implements Serializable{
#Id
private String id = UUID.randomUUID().toString();
#Column(name = "REFERENCE_ID")
private String referenceId;
#Column(name = "VERSION")
private String version;
}
And
#Entity
#Table(name = "b")
public class B{
#Id
private String id = UUID.randomUUID().toString();
#Column(name = "REFERENCE")
private String reference;
#ManyToMany(fetch = FetchType.LAZY)
#NotFound(action = NotFoundAction.IGNORE)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(formula = #JoinFormula(value =
"(select r from A r where r.reference_id = reference_id order by r.version desc limit 1)",
referencedColumnName = "reference_id")),
#JoinColumnOrFormula(column = #JoinColumn(name = "reference_id",
referencedColumnName = "reference_id", insertable = false))
})
private A referenceId;
}
The thing is reference_id is not a unique key in the b table and was just an indicative value in table A so in order to fetch the entire correspondent row I had to do some filtering with the formula in my join annotation.
When I try to fetch my data I get the following error
[Request processing failed; nested exception is
org.springframework.dao.InvalidDataAccessResourceUsageException:
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract
ResultSet] with root cause org.postgresql.util.PSQLException:
ERROR: relation "a" does not exist Position : 309
EDIT
ACtually t works as intended when changing my join formula to
#JoinFormula(value =
"(select r from schema_A r where r.reference_id = reference_id order by r.version desc limit 1)",
referencedColumnName = "reference_id"))
the problem now is that the code is intended to work on multipple envirnments
as for my application.yml it looks a bit like this;
jpa:
database: POSTGRESQL
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
format_sql: true
default_schema: schema
jdbc:
lob:
non_contextual_creation: true
time_zone: UTC
Thanks for your responses :)
I agree with Simon's comment. For Postgres (and relational databases in general), the word "table" and "relation" are the same and where the term "relational" comes from. So, when it says "Can't find relation B" it literally means "Can't find a table called B".
You should check your connection settings for the schema to see if those tables have/haven't been defined. If it's not obvious, maybe add/edit the question accordingly with your connection settings & appropriate debugging showing you DO see the relations (tables) there.
I'm trying to figure Hibernate out. I thought I was doing ok with all the internet tutorials and all but I'm stuck with this exception. I'm trying to save an object that contains a couple Lists into my database.
The object is called DataPointsListResultSet and it contains a List predictDataPointsList and a actualDataPointsList
Here are the models:
(DataPointsListResultSet)
#Entity
public class DataPointsListResultSet {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer resultsetid;
#OneToMany(targetEntity= DataPoints.class,
mappedBy="dataPointsid",cascade = CascadeType.ALL,
fetch=FetchType.EAGER)
private List<DataPoints> predictDataPointsList = new ArrayList<>();
#OneToMany(targetEntity= DataPoints.class, mappedBy="dataPointsid",
cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<DataPoints> actualDataPointsList = new ArrayList<>();
//getters and setters
(DataPoints)
#Entity
public class DataPoints {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer dataPointsid;
double x;
double y;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "resultsetid")
DataPointsListResultSet dataPointsListResultSet;
public DataPoints(){
}
//getters and setters
Here is the some of the Stacktrace:
Message Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
Description The server encountered an unexpected condition that
prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
Root Cause
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
and this is the Java method that executes the logic:
public DataPointsListResultSet predictPriceOneAhead (MultiLayerNetwork net, List<Pair<INDArray, INDArray>> testData, double max, double min, int exampleLength, String nomeDoConjunto, GeneralStockDataSetIterator iterator) {
double[] predicts = new double[testData.size()];
double[] actuals = new double[testData.size()];
DataPointsListResultSet resultSet = new DataPointsListResultSet();
List<DataPoints> predictDataPointsList = new ArrayList<>();
List<DataPoints> actualDataPointsList = new ArrayList<>();
resultSet.setPredictDataPointsList(predictDataPointsList);
resultSet.setActualDataPointsList(actualDataPointsList);
resultSetDao.save(resultSet);
for (int i = 0; i < testData.size(); i++) {
predicts[i] = net.rnnTimeStep(testData.get(i).getKey()).getDouble(exampleLength - 1) * (max - min) + min;
actuals[i] = testData.get(i).getValue().getDouble(0);
DataPoints predictDataPoint = new DataPoints();
predictDataPoint.setDataPointsListResultSet(resultSet);
predictDataPoint.setY(predicts[i]);
predictDataPoint.setX(i);
dataPointsDao.save(predictDataPoint);
predictDataPointsList.add(predictDataPoint);
DataPoints actuaDataPoint = new DataPoints();
actuaDataPoint.setDataPointsListResultSet(resultSet);
actuaDataPoint.setY(actuals[i]);
actuaDataPoint.setX(i);
dataPointsDao.save(actuaDataPoint);
actualDataPointsList.add(actuaDataPoint);
}
log.info("Print out Predictions and Actual Values...");
log.info("Predict,Actual");
for (int i = 0; i < predicts.length; i++) log.info(predicts[i] + "," + actuals[i]);
return resultSet;
}
Could anyone shine some light into this issue, I'd really appreciate it!
You can try removing cascade = CascadeType.ALL from your DataPointsListResultSet entity and do save operations of both entities manually in your case.
I have my entity called Post which has Id as a primary key.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
In above code you may see GenerationType.IDENTITY which I would assume is responsible for generating a new ID in case of creation of a new Post.
However, when I make a HTTP POST with this JSON:
{"id":0,"title":"test","viewCount":0,"body":"test","tags":"","answerCount":0,"commentCount":0,"postTypeId":1,"favoriteCount":0,"creationDate":"Nov 25, 2015 11:43:22 AM","acceptedAnswerId":0,"lastEditorUserId":0,"score":0}
I am getting this error:
SEVERE: Servlet.service() for servlet [rest] in context with path [/StackExchange] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'Id' doesn't have a default value
I haven't set AI though, maybe that is the cause. But I am unable to alter the table. The data in the table are from SQL dumps and I can't alter it to set Id as AutoIncrement
#JoinColumn(name = "want_uid", referencedColumnName = "id")
#ManyToOne
private BookUsers wantUid;
#JoinColumn(name = "sale_uid", referencedColumnName = "id")
#ManyToOne
private BookUsers saleUid;
#JoinColumn(name = "book_id", referencedColumnName = "id")
this code is from a entity bean
and i write a query using want_uid as queryparam .as fllows:
BookUsers bookUsers=userDA.findUserByID(wantID);
Query query= em.createQuery("SELECT b FROM BookOrder b WHERE b.want_uid = :want_uid");
query.setParameter("want_uid", bookUsers);
a exception occurred:
javax.servlet.ServletException: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Error compiling the query [SELECT b FROM BookOrder b WHERE b.want_uid = :want_uid], line 1, column 34: unknown state or association field [want_uid] of class [com.xbook.entities.BookOrder].
i failed to find the reason...
can you tell me ?
Thanks
In the query
b.want_uid
needs to be changed to
b.wantUid
So,
SELECT b FROM BookOrder b WHERE b.wantUid = :want_uid