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);
Related
I am not able add dummy data in child tables while using OneToMany mapping in spring boot. please help me with it
Here is Entity class (only sending join table):
#OneToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
#JoinTable(name = "recipeIngredients",
joinColumns = #JoinColumn(name = "recipe_id"),
inverseJoinColumns = #JoinColumn(name = "ingredient_id"))
private List<RecipeIngredient> recipeIngredientList;
#OneToMany(fetch = FetchType.LAZY , cascade = CascadeType.ALL)
#JoinTable(name = "recipeSteps",
joinColumns = #JoinColumn(name = "recipe_id"),
inverseJoinColumns = #JoinColumn(name = "step_id"))
private List<RecipeSteps> recipeSteps;
public Recipe(Long user_id, String title, String category, String recipeDescription) {
this.user_id = user_id;
this.title = title;
this.category = category;
this.recipeDescription = recipeDescription;
}
//getter setter
here is function for dummy data :
public String recipe(){
Integer i = 1;
Long l = Long.valueOf(i);
Recipe recipe = new Recipe(
l,"Maggie","Veg","2 min Noodles"
);
System.out.println("----------------" + recipe.getRecipeDescription() + " "
+ recipe.getCategory() + " "
+ recipe.getTitle() + " "
+ recipe.getId());
List<RecipeIngredient> list = new ArrayList<>();
list.add(new RecipeIngredient("salt","2kg"));
list.add(new RecipeIngredient("sugar","5kg"));
for (RecipeIngredient iff : list) {
System.out.println("--------------------"+iff.getName() + " " + iff.getIngredientQuantity());
}
List<RecipeSteps> steps = new ArrayList<>();
steps.add(new RecipeSteps("Step 1","chopping","chop the mf vegetables"));
steps.add(new RecipeSteps("Step 2","boiling","boil them rock hard"));
recipe.setRecipeIngredientList(list);
recipe.setRecipeSteps(steps);
recipeRerepository.save(recipe);
return "recipe Here";
}
Here is database table :
and Here error
Hello from AuthTokenFilter JWTnull
----------------2 min Noodles Veg Maggie null
--------------------salt 2kg
--------------------sugar 5kg
Hibernate: insert into recipe_info (category, recipe_description, title, user_id) values (?, ?, ?, ?)
Hibernate: insert into recipe_ingredients (ingredient_quantity, name) values (?, ?)
2021-12-01 18:16:10.692 WARN 375589 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2021-12-01 18:16:10.692 ERROR 375589 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'recipe_id' doesn't have a default value
2021-12-01 18:16:10.786 ERROR 375589 --- [nio-5000-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.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 'recipe_id' doesn't have a default value
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)")
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 configure an existing Spring Boot application to use an Oracle12c database, and I’ve got a problem with Identity columns.
Oracle12c supports identities natively, and i set the strategy as IDENTITY, but hibernate seems to ignore my identity column and try to use
select hibernate_sequence.nextval from dual
I hope someone can help me.
Thanks
This is the log:
Hibernate: select userlogini0_.id as id1_0_, userlogini0_.created_date as created_date2_0_, userlogini0_.register_number as register_number3_0_, userlogini0_.session_id as session_id4_0_, userlogini0_.session_status as session_status5_0_, userlogini0_.updated_date as updated_date6_0_, userlogini0_.user_bank as user_bank7_0_, userlogini0_.user_name as user_name8_0_, userlogini0_.user_structure as user_structure9_0_ from user_login_info userlogini0_ where userlogini0_.register_number=? and userlogini0_.user_name=? and userlogini0_.user_bank=? and userlogini0_.user_structure=? and userlogini0_.session_status=?
Hibernate: insert into user_login_info (created_date, register_number, session_id, session_status, updated_date, user_bank, user_name, user_structure) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
2021-03-03 20:39:23.707 WARN 8 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 2289, SQLState: 42000
2021-03-03 20:39:23.707 ERROR 8 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-02289: sequence does not exist
2021-03-03 20:39:23.724 ERROR 8 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/be-profiling-clm] 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
oracle.jdbc.OracleDatabaseException: ORA-02289: sequence does not exist
These are my configs:
org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
This is one of the tables:
CREATE TABLE user_login_info
(
id NUMBER(19,0) GENERATED ALWAYS AS IDENTITY INCREMENT BY 1 START WITH 1 NOT NULL ,
created_date TIMESTAMP (6) NOT NULL ,
register_number VARCHAR2(255 CHAR) NOT NULL ,
session_id VARCHAR2(255 CHAR) NOT NULL ,
session_status VARCHAR2(255 CHAR) NOT NULL ,
updated_date TIMESTAMP (6) NOT NULL ,
user_structure VARCHAR2(255 CHAR) NOT NULL ,
PRIMARY KEY (id)
);
and this is my entity:
#Data
#Entity
#Table(name = "user_login_info")
public class UserLoginInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false, updatable = false)
private Long id;
#Column(name = "REGISTER_NUMBER", nullable = false, updatable = false)
private String registerNumber;
#Column(name = "USER_NAME", nullable = false, updatable = false)
private String userName;
#Column(name = "USER_STRUCTURE", nullable = false, updatable = false)
private String userStructure;
#Column(name = "SESSION_ID", unique = true, nullable = false, updatable = false)
private String sessionId;
#Column(name = "SESSION_STATUS", nullable = false)
#Enumerated(EnumType.STRING)
private SessionStatus sessionStatus;
#Column(name = "CREATED_DATE", nullable = false, updatable = false)
private LocalDateTime createdDate;
#Column(name = "UPDATED_DATE", nullable = false)
private LocalDateTime updatedDate;
}
I have two classes User and Application.
User has one to many mapping to application. User has a lot of fields, some are pretty big ones like description. I don't want to load all the fields of the user when I want to use it to see the relationship between user and application so I created a proxy class that has username and a collection of application. How do I the two tables to this class? Or what is the best practice?
update :
#Entity
public class UserProfile implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String userName;
private String password;
#OneToMany
#JoinTable(name = "userapplicationlink", joinColumns = #JoinColumn(name = "userId"), inverseJoinColumns = #JoinColumn(name = "appId"))
private Collection<Application> applications;
}
#Entity
public class Application
{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String name;
private String url;
}
main()
{
UserProfile user1 = new UserProfile();
user1.setUserName("sasd");
user1.setPassword("123");
Application app = new Application();
app.setName("User Application");
app.setPriority(1);
app.setUrl("/user.do");
app.setDescription("app");
user1.setApplications(new ArrayList());
user1.getApplications().add(app);
SessionFactory sessionFac = new Configuration().configure().buildSessionFactory();
Session session = sessionFac.openSession();
session.beginTransaction();
session.save(user1);
session.save(app);
session.getTransaction().commit();
System.out.println("End");
session.close();
sessionFac.close();
sessionFac = new Configuration().configure().buildSessionFactory();
session = sessionFac.openSession();
session.beginTransaction();
try
{
Query query = session.createQuery("SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, u.applications) FROM UserProfile u JOIN FETCH u.applications");
List result = query.list();
session.getTransaction().commit();
session.close();
}
finally
{
session.close();
sessionFac.close();
}
}
Stack trace
Exception in thread "main" org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=empire.erp.server.db.UserProfile.applications,tableName=Application,tableAlias=applicatio2_,origin=UserProfile userprofil0_,columns={userprofil0_.id ,className=empire.erp.server.db.Application}}] [SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, u.applications) FROM empire.erp.server.db.UserProfile u JOIN FETCH u.applications]
at org.hibernate.QueryException.generateQueryException(QueryException.java:120)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907)
at empire.erp.server.db.UserProfile.main(UserProfile.java:216)
Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=null,role=empire.erp.server.db.UserProfile.applications,tableName=Application,tableAlias=applicatio2_,origin=UserProfile userprofil0_,columns={userprofil0_.id ,className=empire.erp.server.db.Application}}]
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:214)
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
... 8 more
Update 2: running query without fetch
Hibernate: select userprofil0_.userName as col_0_0_, . as col_1_0_ from UserProfile userprofil0_ inner join userapplicationlink applicatio1_ on userprofil0_.id=applicatio1_.userId inner join Application applicatio2_ on applicatio1_.appId=applicatio2_.id inner join userapplicationlink applicatio3_ on userprofil0_.id=applicatio3_.userId inner join Application applicatio4_ on applicatio3_.appId=applicatio4_.id
May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42601
May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: syntax error at or near "."
Position: 43
May 07, 2016 4:17:21 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/optimalyou]
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2115)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at empire.erp.server.db.UserProfile.main(UserProfile.java:217)
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "."
Position: 43
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2284)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2003)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:200)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:424)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:161)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:114)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 15 more
Had to use an alias for the collection. Not sure why though. The proper HQL is
SELECT NEW empire.erp.server.db.UserNameAndApplications(u.userName, app) FROM UserProfile u JOIN u.applications app