How to fix syntax error parsing JPQL with group by - java

I'm new using JPA and JPQL for a project, but I got SQL syntax error and I couldn't find the cause.
I'm using spring boot, MySQL.
I got a vote repository
public interface VoteRepository extends JpaRepository<Vote, Long> {
....
#Query(value = "SELECT NEW com.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.poll.id = :pollId GROUP BY v.choice.id", nativeQuery = true)
List<ChoiceVoteCount> countByPollIdGroupByChoiceId(#Param("pollId") Long pollId);
....
}
ChoiceVoteCount
public class ChoiceVoteCount {
private Long choiceId;
private Long voteCount;
}
Vote
public class Vote {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "poll_id", nullable = false)
private Poll poll;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "choice_id", nullable = false)
private Choice choice;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
}
But I got error when running this query
2019-03-27 16:01:34.783 ERROR 68064 --- [nio-5000-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.' at line 1
2019-03-27 16:01:34.787 ERROR 68064 --- [nio-5000-exec-4] 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 extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.self.polls.model.ChoiceVoteCount(v.choice.id, count(v.id)) FROM Vote v WHERE v.' at line 1

You have to add a constructor in ChoiceVoteCount.
To play safe, the default constructor could also be added.
public ChoiceVoteCount() {
}
public ChoiceVoteCount(Long choiceId, Long voteCount) {
this.choiceId = choiceId;
this.voteCount = voteCount;
}

Related

SQL Grammar Exception in Spring Boot H2

I'v got a problem in my Spring Boot with H2 project. I got a get method for listing elements from the SQL table and the SQL command working. In the H2 database I can execute and see the results but I can't get the values from Postman. My GET post went wrong. My SQL codes are also in here.
I also uploaded my project to github. If you want to see all classes Here is my GitHub project link
UrunEntity class
#Entity
#Table(name = "urunler")
public class UrunEntity{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "urun_id")
private int urunId;
#Column(name = "hayvan_kupe_no")
private int hayvanKupeNo;
#Column(name = "hayvan_adi")
private String hayvanAdi;
#Column(name = "dogum_sekli")
private String dogumSekli;
#Column(name = "hayvan_resmi")
private String hayvanResmi;
#Column(name = "hayvan_cinsiyet")
private String hayvanCinsiyet;
#Column(name = "hayvan_irki")
private String hayvanIrki;
#Column(name = "hayvan_anneAdi")
private String hayvanAnneAdi;
#Column(name = "dogum_tarihi")
private String dogumTarihi;
#Column(name = "dogum_agirligi")
private Double dogumAgirligi;
#Column(name = "tohuma_hazir")
private Boolean tohumaHazir;
#Column(name = "sut_miktari")
private Double sutMiktari;
#Column(name = "sut_tarihi")
private String sutTarihi;
#Column(name = "urun_tutar")
private Double urunTutar;
#Column(name = "user_id")
private Integer userId;
//getters and setters after that
Here is my UrunRepository
#Query(value="SELECT DOGUM_AGIRLIGI, DOGUM_SEKLI, DOGUM_TARIHI, HAYVAN_ADI, HAYVAN_ANNE_ADI, HAYVAN_CINSIYET, HAYVAN_IRKI, URUN_TUTAR FROM URUNLER d " +
"INNER JOIN kullanicilar k on d.user_id = k.user_id " +
"WHERE k.user_id=:userId AND HAYVAN_ADI IS NOT NULL",
nativeQuery=true)
List<UrunEntity> findHayvanAll(#Param("userId") String userId);
Here is the error code at backend
> 2021-01-12 17:58:39.357 WARN 19652 --- [nio-6161-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42122, SQLState: 42S22
2021-01-12 17:58:39.357 ERROR 19652 --- [nio-6161-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : Column "urun_id" not found [42122-200]
2021-01-12 17:58:39.374 ERROR 19652 --- [nio-6161-exec-5] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/invoiceControl] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT DOGUM_AGIRLIGI, DOGUM_SEKLI, DOGUM_TARIHI, HAYVAN_ADI, HAYVAN_ANNE_ADI, HAYVAN_CINSIYET, HAYVAN_IRKI, URUN_TUTAR FROM URUNLER d INNER JOIN kullanicilar k on d.user_id = k.user_id WHERE k.user_id=? AND HAYVAN_ADI IS NOT NULL]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "urun_id" not found [42122-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
at org.h2.jdbc.JdbcResultSet.getColumnIndex(JdbcResultSet.java:3169) ~[h2-1.4.200.jar:1.4.200]
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:3268) ~[h2-1.4.200.jar:1.4.200]
at org.h2.jdbc.JdbcResultSet.getInt(JdbcResultSet.java:352) ~[h2-1.4.200.jar:1.4.200]
Here is the error from Postman:
"timestamp": "2021-01-12T14:30:50.458+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute query; SQL [SELECT SUT_MIKTARI, SUT_TARIHI, URUN_TUTAR FROM URUNLER d INNER JOIN kullanicilar k on d.user_id = k.user_id WHERE k.user_id=? AND SUT_MIKTARI IS NOT NULL]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query",
"trace": "org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT SUT_MIKTARI, SUT_TARIHI, URUN_TUTAR FROM URUNLER d INNER JOIN kullanicilar k on d.user_id = k.user_id WHERE k.user_id=? AND SUT_MIKTARI IS NOT NULL]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.jpa.repository.support
KullanicilarEntity class
#Entity
#Table(name = "kullanicilar")
public class KullaniciEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private long userId;
#Column(name = "email")
private String email;
#Column(name = "kullanici_sifre")
private String kullaniciSifre;
#Column(name = "kullanici_adi")
private String kullaniciAdi;
#Column(name = "kullanici_soyadi")
private String kullaniciSoyadi;
#Column(name = "telefon_no")
private String telefonNo;
#Column(name = "enabled")
private boolean enabled;
#Column(name = "username")
private String username;
My Resource(endpoints) interface
#GetMapping(path = "/getSut")
public ResponseEntity<List<UrunEntity>> getSut(#RequestParam("userId") String userId) {
List<UrunEntity> urunEntities = ccAppService.findSutAll(userId);
return new ResponseEntity(urunEntities, HttpStatus.OK);
}
Seems like you want to materialize an entity from a native query, but the native query is not selecting the urun_id column which is required to materialize the entity. Try using HQL queries instead of native queries.
You are trying to map fields not fully fitting your entity. Try also selecting urun_id in your query or d.* in the selection part.
For more complex queries you can use SqlResultSetMapping. Check this link.
I create a new model class named HayvanDto and I created all of the UrunEntity entites inside of this.
public class HayvanDto {
private Double dogumAgirligi;
private String dogumSekli;
private String dogumTarihi;
private String hayvanAdi;
private String hayvanAnneAdi;
private String hayvanCinsiyet;
private String hayvanIrki;
private String hayvanResmi;
private Boolean tohumaHazir;
private Double urunTutar;
After that, in my implementation class, I wrote this code.
#Override
public List<HayvanDto> findHayvanAll(Integer userId) {
List<UrunEntity> urunEntities = urunRepository.findHayvanAll(userId);
List<HayvanDto> hayvanDtos = new ArrayList<>();
for (UrunEntity urunEntity : urunEntities) {
HayvanDto hayvanDto = new HayvanDto();
hayvanDto.setHayvanAdi(urunEntity.getHayvanAdi());
hayvanDto.setHayvanIrki(urunEntity.getHayvanIrki());
hayvanDto.setHayvanResmi(urunEntity.getHayvanResmi());
hayvanDto.setHayvanCinsiyet(urunEntity.getHayvanCinsiyet());
hayvanDto.setHayvanAnneAdi(urunEntity.getHayvanAnneAdi());
hayvanDto.setDogumAgirligi(urunEntity.getDogumAgirligi());
hayvanDto.setDogumSekli(urunEntity.getDogumSekli());
hayvanDto.setUrunTutar(urunEntity.getUrunTutar());
hayvanDto.setTohumaHazir(urunEntity.getTohumaHazir());
hayvanDtos.add(hayvanDto);
}
return hayvanDtos;
}
Then it worked. Thanks for the answers.

InvalidDataAccessResourceUsageException: org.hibernate.exception.SQLGrammarException:

I have the following problem I have been stuck for a while:
I get this error:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [call next value for hibernate_sequence]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
I found out that people with this error get it because they use reserve words for table names but I do not think this is my issue.
My two model classes are as follows. I am skipping the getters/setters and consturctors
#Entity
#Table(name = "GATEWAY_MODEL")
public class GetewayModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "serial_number", nullable = false, length = 12, updatable = true)
private String serialNumber;
#Column(name = "name", nullable = false, length = 12, updatable = true)
private String name;
#Column(name = "ipFour", nullable = false, length = 12, updatable = true)
private String ipFour;
#Column(name = "peripheral_devices", updatable = true)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "gateway")
private Set<PeripheralDevicesModel> peripheralDevices = new HashSet<PeripheralDevicesModel>();
#Entity
#Table(name = "PERIPHERAL_DIVICES_MODEL")
public class PeripheralDevicesModel {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "uID", nullable = false)
private String uID;
#Column(name = "vendor", nullable = false)
private String vendor;
#Column(name = "date_created", nullable = false)
private Date dateCreated;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private Status status;
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "gateway")
private GetewayModel gateway;
Then in the main class I try to put some data like this:
#Bean
CommandLineRunner initDatabase(GatewayRepository gatewayRepo, PeripheralDevicesRepository devicesRepo) {
Set<PeripheralDevicesModel> devicesSet = new HashSet<>();
GetewayModel gateway = new GetewayModel();
gateway.setId(123l);
gateway.setSerialNumber("1123");
gateway.setName("gateway");
gateway.setIpFour("1.160.10.240");
PeripheralDevicesModel devices = new PeripheralDevicesModel();
devices.setId(1234l);
devices.setuID("2");
devices.setDateCreated(new Date());
devices.setGateway(gateway);
devices.setStatus(Status.OFFLINE);
devices.setVendor("vendor");
devicesSet.add(devices);
gateway.setPeripheralDevices(devicesSet);
return args -> {
gatewayRepo.save(gateway);
devicesRepo.save(devices);
};
I am guessing that are is some issue because of the OneToMany Relationship in my model data.
I bit more from the stack trace
call next value for hibernate_sequence
2020-06-26 08:34:53 - SQL Error: 90036, SQLState: 90036
2020-06-26 08:34:53 - Sequence "HIBERNATE_SEQUENCE" not found; SQL statement:
call next value for hibernate_sequence [90036-200]
2020-06-26 08:34:53 -
Do you have any idea how to resolve this or why it is not working.
Thanks
configuration.properties:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/h2
spring.jpa.hibernate.ddl-auto=none
#Turn Statistics on and log SQL stmts
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.generate_statistics=false
#logging.level.org.hibernate.type=trace
#logging.level.org.hibernate.stat=debug
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
Update:
After making GenerationType.IDENTITY I got the following error now:
Hibernate:
select
getewaymod0_.id as id1_0_1_,
getewaymod0_.ip_four as ip_four2_0_1_,
getewaymod0_.name as name3_0_1_,
getewaymod0_.serial_number as serial_n4_0_1_,
peripheral1_.gateway as gateway5_1_3_,
peripheral1_.id as id1_1_3_,
peripheral1_.id as id1_1_0_,
peripheral1_.date_created as date_cre2_1_0_,
peripheral1_.gateway as gateway5_1_0_,
peripheral1_.uid as uid3_1_0_,
peripheral1_.vendor as vendor4_1_0_
from
gateway_model getewaymod0_
left outer join
peripheral_divices_model peripheral1_
on getewaymod0_.id=peripheral1_.gateway
where
getewaymod0_.id=?
2020-06-26 16:42:04 - SQL Error: 42102, SQLState: 42S02
2020-06-26 16:42:04 - Table "GATEWAY_MODEL" not found; SQL statement:
select getewaymod0_.id as id1_0_1_, getewaymod0_.ip_four as ip_four2_0_1_, getewaymod0_.name as name3_0_1_, getewaymod0_.serial_number as serial_n4_0_1_, peripheral1_.gateway as gateway5_1_3_, peripheral1_.id as id1_1_3_, peripheral1_.id as id1_1_0_, peripheral1_.date_created as date_cre2_1_0_, peripheral1_.gateway as gateway5_1_0_, peripheral1_.uid as uid3_1_0_, peripheral1_.vendor as vendor4_1_0_ from gateway_model getewaymod0_ left outer join peripheral_divices_model peripheral1_ on getewaymod0_.id=peripheral1_.gateway where getewaymod0_.id=? [42102-200]
2020-06-26 16:42:04 - HHH000327: Error performing load command
org.hibernate.exception.SQLGrammarException: could not prepare statement
I changed 2 things(besides the few grammar/typo errors in your code):
Added cascade=CascadeType.ALL as follows:
#JsonIgnore
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "gateway")
private GatewayModel gateway;
You can't add an entity, which has columns with nullable = false:
devices.setGateway(new GetewayModel());
devices.setGateway(gateway);
Otherwise, it's working fine on H2.
UPDATE:
Grammar/typo errors to look for:
#Table(name = "PERIPHERAL_DIVICES_MODEL") needs to be #Table(name = "PERIPHERAL_DEVICES_MODEL")
public class GetewayModel needs to be public class GatewayModel
private GetewayModel gateway; needs to be private GatewayModel gateway;
Ran into the same problem. The difference was that I did not specify strategy in #GeneratedValues. Turns out the default strategy is GeneratedType.AUTO.
So Simon Martinelli's comment solves my issue, by explicitly specify #GeneratedValue(strategy = GenerationType.IDENTITY) for the id column/field.
This article summarises the strategies nicely.
GenerationType.Identity does not create any additional sequence tables like GenerationType.AUTO / GenerationType.SEQUENCE and also maintain the sequences in every table starts from 0, rather than maintaining the sequence number across the tables like GenerationType.AUTO does it.
GenerationType.AUTO generates one more table named hibernate_sequences for maintaining the sequences.
GenerationType.SEQUENCE is purely customizable, probably every auto generation field would have configured with separate sequences.

Unknown column 'clientproj0_.clienthours_id' in 'field list (JPA #OneToMany(mappedBy = "clienthours"))

I have 2 views
"client_hours_view"
(ClientHoursInfo.java) and
"client_project_hours_view"
(ClientProjectHoursInfo.java)
The first view already existed in the application and :
Retrieves all the clients in the work hours in total
The second view is the new pne and:
Retrieves all the clients with a list of projects for each client and their hours
Anyways, I just want to find a way to retrieve all the clients (first view) with a list of their respective projects (second view), and the best I could figure out is by adding a field list in the ClientHoursInfo.java :
private List clientProjectList which will contain a list of projects for each client.
I have extracted below the code to show only the relation needed against these 2 views
However I am not able to succesfully run it, since it is showing the below error in the console.
Unknown column 'clientproj0_.clienthours_id'
I would like to get guidance to solve this or find a different approach to meet the requirement.
ClientHoursInfo.java
#Entity
#Table(name = "client_hours_view")
public class ClientHoursInfo {
#Id
#Column(name = "unique_id")
private String uniqueId;
private Long id;
private String client;
#Column(name = "week_ending")
private String weekEnding;
#Column(name = "total_hours")
private Double totalHours;
#OneToMany(mappedBy = "clienthours")
private List<ClientProjectHoursInfo> clientProjectList;
}
ClientProjectHoursInfo.java
#Entity
#Table(name = "client_project_hours_view")
public class ClientProjectHoursInfo {
#ManyToOne(fetch = FetchType.LAZY)
private Employee clienthours;
#Id
#Column(name = "id")
private String Id;
}
FinanceManagerReports.java
clientHours = clientHoursInfoViewRepository.findByWeekEndingBetween(from, to);
for (ClientHoursInfo clientHoursInfo : clientHours) {
clientProjectHours = clientProjectHoursInfoViewRepository
.findByClientIdAndWeekEnding(clientHoursInfo.getId(), clientHoursInfo.getWeekEnding());
clientHoursInfo.setClientProjectList(clientProjectHours);
}
Error Console
[2019-10-02 17:21:57.887] boot - 9656 ERROR [http-nio-8080-exec-3] --- SqlExceptionHelper: Unknown column 'clientproj0_.clienthours_id' in 'field list'
[2019-10-02 17:21:57.888] boot - 9656 ERROR [http-nio-8080-exec-3] --- [dispatcherServlet]: 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
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'clientproj0_.clienthours_id' in 'field list'

Column does not exist in spring boot Postgres app

Hi in my spring boot postgresql application, when i retrieve all record using DAO it show column does not exists.
ERROR
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42703
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: column merchantit0_.id does not exist
Position: 8
ERROR: org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/customerplus].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/customerplus] 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
org.postgresql.util.PSQLException: ERROR: column merchantit0_.id does not exist
Position: 8
Entity Domain
#Entity
#Table(name = "merchant_item_category")
public class MerchantItemCategory{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false, length = 11)
private long id;
#ManyToOne
#JoinColumn(name = "merchant_id", nullable = false)
private Merchant merchant;
// getters and setters
}
DAO
public List<MerchantItemCategory> getAllMerchantItemCategoryByMerchantId(long id) {
Session session=getSession();
List<MerchantItemCategory>itemCategories=session.createQuery("from MerchantItemCategory where merchant.id=:merchantId and isDelete='0' order by categoryName asc")
.setParameter("merchantId", id)
.list();
return itemCategories;
}
I just checked every object and it is correct, But how this error occurring..!
A potential cause of this error is when you haven't defined the hibernate "default schema" property.
I fixed this issue by adding line below to my application.properties:
spring.jpa.properties.hibernate.default_schema=${your-default-schema-name}

HQL syntax error

mysql 5.1
hibernate 4.3
spring 4
glassfish 4
I have written a application using spring and hibernate. It gives following error.
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Account WHERE accountNo = '123'' at line 1
Warning: StandardWrapperValve[dispatcher]: Servlet.service() for servlet dispatcher threw exception
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Account WHERE accountNo = '123'' at line 1
I think there is no issue with the hql statement.
method inside #Repository
public Account getAccountByNo(String accountNo) {
Account acc = null;
Query query = getSession().createSQLQuery(" FROM Account WHERE accountNo = :accno ");
query.setString("accno", accountNo);
List list = query.list();
if(!list.isEmpty()){
acc = (Account)list.get(0);
}
return acc;
}
#Entity
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "ACCOUNTNO", nullable = false)
private String accountNo;
#Column(name = "AMOUNT", nullable = false)
private Double amount;
#OneToOne
private AccHolder accHolder;
}
You do not create a HQL Query. Your create a SQL-Query:
Query query = getSession().createSQLQuery(" FROM Account WHERE accountNo = :accno ");
Change it to
Query query = getSession().createQuery(" FROM Account a WHERE a.accountNo = :accno ");

Categories

Resources