Spring Boot Saving/Reading entities running out of connections - spring-boot

I am relatively inexperienced in using Java Spring/Hibernate. This problem may be easy to solve, but I feel like I have done hours of error look ups at this point. Here are some overall specs of my program: Using h2 database, database is locally stored, using spring-boot-starter, spring-boot-security.
Problem
I am trying to create an online Wiki. So far, I have not had any hiccups. I am able to save, update, and delete entities (which are called WikiPages). However, I noticed that if I try to read/save/update/delete a WikiPage around 5 times, the application is no longer able to communicate with my locally stored h2 server, the program hangs, and I am unable to view any webpages at all. I did not encounter this problem on my previous project which has a very similar DAO.
I have a suspicion that there is some sort of problem with my DAO interacting with the database. Any help would be appreciated. Please let me know if you would like to see a different file in the program. I enabled debug console logging
Application Properties
spring.datasource.url = jdbc:h2:tcp://localhost/~/Downloads/Data/Database
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true
server.error.include-message=always
server.port=80
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
WikiPage
package com.costi.csw9.Model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
#Getter
#Setter
#EqualsAndHashCode
#NoArgsConstructor
#Entity
public class WikiPage {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(nullable = false, unique = true)
private String title;
#Column(nullable = false)
private LocalDateTime lastEdited;
#Column(nullable = false)
private String subtitle;
private boolean enabled = false;
private String category;
#Column(columnDefinition="text")
private String body;
#OneToOne
#JoinColumn(name = "user_id")
private User author;
public WikiPage(String title, String subtitle, User author, String category, String body) {
this.title = title;
this.subtitle = subtitle;
this.author = author;
this.category = category;
this.body = body;
}
public WikiPage(User author){
this.author = author;
}
}
WikiDaoImpl
package com.costi.csw9.Repository;
import com.costi.csw9.Model.User;
import com.costi.csw9.Model.UserRole;
import com.costi.csw9.Model.WikiCategory;
import com.costi.csw9.Model.WikiPage;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.List;
#Repository
public class WikiDaoImpl implements WikiRepository{
#Autowired
private SessionFactory sessionFactory;
#Override
public WikiPage findById(Long id) {
Session session = sessionFactory.openSession();
WikiPage wikiPage = session.get(WikiPage.class, id);
session.close();
return wikiPage;
}
#Override
public List<WikiPage> findByCategory(WikiCategory category) {
Session session = sessionFactory.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<WikiPage> cr = cb.createQuery(WikiPage.class);
Root<WikiPage> root = cr.from(WikiPage.class);
cr.select(root);
cr.select(root).where(cb.like(root.get("category"), category.name()));
Query<WikiPage> query = session.createQuery(cr);
List<WikiPage> results = query.getResultList();
return results;
}
#Override
public List<WikiPage> getByApproval(boolean enabled) {
Session session = sessionFactory.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<WikiPage> cr = cb.createQuery(WikiPage.class);
Root<WikiPage> root = cr.from(WikiPage.class);
cr.select(root);
if(enabled){
cr.select(root).where(cb.isTrue(root.get("enabled")));
}else{
cr.select(root).where(cb.isFalse(root.get("enabled")));
}
Query<WikiPage> query = session.createQuery(cr);
List<WikiPage> results = query.getResultList();
return results;
}
#Override
public List<WikiPage> findAll() {
// Open a session
Session session = sessionFactory.openSession();
// Get all people with a Hibernate criteria
List<WikiPage> all = session.createCriteria(WikiPage.class).list();
// Close session
session.close();
return all;
}
#Override
public void save(WikiPage wikiPage) {
//Add in last edited
wikiPage.setLastEdited(LocalDateTime.now());
// Open a session
Session session = sessionFactory.openSession();
// Begin a transaction
session.beginTransaction();
// Save the person
session.saveOrUpdate(wikiPage);
// Commit the transaction
session.getTransaction().commit();
// Close the session
session.close();
}
#Override
public void delete(WikiPage wikiPage) {
// Open the session
Session session = sessionFactory.openSession();
// Not completley sure why I have to do this, but I need to find the page via id in this function
WikiPage page = session.get(WikiPage.class, wikiPage.getId());
// Begin translation
session.beginTransaction();
// Delete Page
session.delete(page);
// Commit the transaction
session.getTransaction().commit();
// Close the session
session.close();
}
}
Error
2022-06-28 20:35:22.933 DEBUG 10820 --- [p-nio-80-exec-4] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2022-06-28 20:35:22.934 DEBUG 10820 --- [p-nio-80-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2022-06-28 20:35:22.935 DEBUG 10820 --- [p-nio-80-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2022-06-28 20:35:22.935 DEBUG 10820 --- [p-nio-80-exec-4] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 500

although I did not find what I did wrong in my code. I eventually go it to work with some light testing by turning as many DAO methods into JPA queries as I can. Hope this helps others!

Related

How do I specify a default value for an identity variable in Spring Boot?

I have a Spring Boot User class which always comes up with the error "java.sql.SQLException: Field 'id' doesn't have a default value". I have tried many times to provide a default value, both in the Java class and in the database table, but to no avail. And I have also switched from generation type = auto and = identity, but to no avail. Thank you very much for your help. Here is my Java Class and my Database Table:
package com.ykirby.myfbapp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.beans.factory.annotation.Value;
import java.sql.Timestamp;
import java.util.Date;
#Entity // This tells Hibernate to make a table out of this class
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
#Value("#{User.id ?: 0}")
private int id = 12345;
#Column(name = "fbuserid")
private String fbuserid;
#Column(name = "apttime")
#Temporal(TemporalType.TIMESTAMP)
private Date apttime;
#Column(name = "apttitle")
private String apttitle;
#Column(name = "aptaddress")
private String aptaddress;
#Column(name = "aptlonglat")
private String aptlonglat;
#Column(name = "aptdetails")
private String aptdetails;
public String getFbuserid() {
return fbuserid;
}
public void setFbuserid(String fbuserid) {
this.fbuserid = fbuserid;
}
public Date getApttime() {
return apttime;
}
public void setApttime(Date apttime) {
this.apttime = apttime;
}
public String getApttitle() {
return apttitle;
}
public void setApttitle(String apttitle) {
this.apttitle = apttitle;
}
public String getAptaddress() {
return aptaddress;
}
public void setAptaddress(String aptaddress) {
this.aptaddress = aptaddress;
}
public String getAptlonglat() {
return aptlonglat;
}
public void setAptlonglat(String aptlonglat) {
this.aptlonglat = aptlonglat;
}
public String getAptdetails() {
return aptdetails;
}
public void setAptdetails(String aptdetails) {
this.aptdetails = aptdetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
The changes in your User entity class may sometimes not reflect your DB schema accurately. You can try one of these below solutions:
1. Update your DB schema manually by adding AUTO_INCREMENT attribute
ALTER TABLE `user` CHANGE COLUMN `id` `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;
2. Drop the User table in your DB, and rerun the application
Make sure that spring.jpa.hibernate.ddl-auto is set to create or update. The default is none if you are NOT using an embedded/in-memory DBs like H2 database.
This configuration of Spring Data JPA will set Hibernate's hibernate.hbm2ddl.auto to the setting value. In our case, it is create or update.
You can read more about this in the below articles and docs.
Spring Boot reference - Database Initialization
What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do
In production, I suggest you not to use this option but instead use a database migration tool like Liquibase or Flyway and leave the spring.jpa.hibernate.ddl-auto configuration to be none.
More reads about this Hibernate: hbm2ddl.auto=update in production?
You should drop the existing database and re-generate it because sometimes changes done through the model don't reflect properly in the database. While re-generating the database you can scaffolding it with SchemaExport.
Does
#Column(name = "apttitle")
private String apttitle="default";
work?

Spring Data CrudRepository's save throws InvocationTargetException

I have spent the whole weekend trying to debug this piece of code. I have a Spring RestController :
import com.tsakirogf.schedu.model.ContactMean;
import com.tsakirogf.schedu.model.DefaultContactMean;
import com.tsakirogf.schedu.model.human.Business;
import com.tsakirogf.schedu.services.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
import java.util.Set;
#RestController
#RequestMapping("api/v1/business/")
public class BusinessController
{
#Autowired
BusinessService businessService;
#GetMapping(value = "businesss")
Iterable<Business> list()
{
Iterable<Business> retVal = businessService.findAll();
return retVal;
}
#RequestMapping(value = "business", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
Business create(#RequestBody Business business)
{
CollectionOfContactMethods collectionOfContact = business.getContact();
collectionOfContact.setBusiness(business);
Set<ContactMean> contactMeanSet = collectionOfContact.getContactMeans();
DefaultContactMean defaultContactMeanSet = collectionOfContact.getDefaultContactMean();
defaultContactMeanSet.getCollectionOfContactMethodsDefault().setId(collectionOfContact.getId());
for (ContactMean element : contactMeanSet)
{
element.setCollectionOfContactMethods(collectionOfContact);
}
collectionOfContact.setDefaultContactMean(defaultContactMeanSet);
business.setContact(collectionOfContact);
Business retval = businessService.save(business);
return retval;
}
#RequestMapping(value = "business/{id}", method = RequestMethod.GET )
Optional<Business> get(#PathVariable Long id)
{
return businessService.findById(id);
}
}
And the service :
public interface BusinessService extends CrudRepository<Business, Long>
{
}
This is the model :
#Table(name = "business")
public class Business
{
#Id
#Column(name = "business_id", nullable = false)
private Long id;
#JsonProperty("name")
private String name;
#Embedded
#JsonProperty("address")
private Address address;
#OneToMany(mappedBy = "business",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
#JsonProperty("operatives")
#JsonIgnore
Set<Professional> operatives;
#OneToOne(mappedBy = "business",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
optional = false)
#JsonBackReference
#JsonProperty("contact_numbers")
private CollectionOfContactMethods contact;
public Business()
{
}
// Getters and Setters
}
When I send a POST request like this :
Where I got the following
{
"timestamp": "2021-11-01T08:59:06.343+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/v1/business/business"
}
I debug and I am getting InvocationTargetException as seen below
This is the controller, right before save() which seems to throw :
And here is the catch :
I found this article posted in a similar event in StackOverflow but I don't think that's what is happening in this case since I have only H2 database for now.
This is application.properties file :
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.hbm2ddl.auto=create
I would appreciate any ideas. Thanks for your time.
If you look at your last screenshot you see a message indicating that there is an id field that has no value.
In your entity you have the following declaration of your id field:
#Id
#Column(name = "business_id", nullable = false)
private Long id;
Which indicates to hibernate that it shouldn't generate a key or that there is no database assigned one. Which means you will manually need to set the value for id. If you don't you will run into this exception.
Now I assume that this was a mistake and that you actually wanted to have a sequence or auto-incremented id field. For this add the #GeneratedValue annotation to add this behavior.
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE))
#Column(name = "business_id", nullable = false)
private Long id;
This will instruct hibernate to use a sequence to generate the id upon inserting the entity. If your database supports identity columns you might want to use GenerationType.IDENTITY instead of GenerationType.SEQUENCE.

Java Model Hibernate Mapping Issue

Note: I have Used Spring Data Jpa for persistence.
Problem:
I have two Models: User and Badge
I have a List of Badges owned By a User as data member in User class.
I also have User as data member in Badge class (i.e. The creator of the badge)
I want to make relationship between user and List of badges data member.
relationship is of type OneToMany (i.e. One User will going to have Many Badges) and vice versa also.
I want it to work in this way,
in code ,
When I save badge object with issuer (aka user) set to a particular user object , then need not to add it (the badge) into user's List of badges Owned by it.
I have tried to create the relationship but it returns an empty list of User Owned Badge in REST API response.
Badge Model
import javax.persistence.*;
#Entity
#Table(name = "badges")
public class Badge {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "badge_id")
private int mId;
#Column(name = "badge_name" , nullable = false , unique = true)
private String mName;
#Column(name = "badge_description")
private String mDescription;
#Lob
#Column(name = "badge_logo" , nullable = false)
private String mLogo;
#ManyToOne
#JoinColumn(name = "issuer_id")
private User mIssuer;
}
User Model
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "users")
public class User {
#Id#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private long mId;
#Column(name = "username" , nullable = false , unique = true)
private String mUserName;
#Column(name = "fullname",nullable = false)
private String mFullName;
#Column(name = "salt")
private String mSalt;
#OneToMany(mappedBy = "mIssuer",cascade = CascadeType.ALL)
private List<Badge> mOwnedBadges;
#OneToMany
#JoinColumn(name = "received_badges_id")
private List<Badge> mReceivedBadges;
}
CommandLineRunner
import com.badging.spinnerbadger.SpinnerBadger.Models.Badge;
import com.badging.spinnerbadger.SpinnerBadger.Models.User;
import com.badging.spinnerbadger.SpinnerBadger.Services.Intefaces.BadgeSerivce;
import com.badging.spinnerbadger.SpinnerBadger.Services.Intefaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
#Component
public class StartupExecutor implements CommandLineRunner {
#Autowired
private BadgeSerivce mBadgeSerivce;
#Autowired
private UserService mUserService;
#Override
public void run(String... args) throws Exception {
//TODO:: issuer cannot issue badge to itself
final User user1 = new User();
user1.setFullName("User1 FullName");
user1.setSalt("salt1");
user1.setUserName("User1 UserName");
mUserService.save(user1);
final User user2 = new User();
user2.setFullName("User2 FullName");
user2.setSalt("salt2");
user2.setUserName("User2 UserName");
mUserService.save(user2);
Badge badge1 = new Badge();
badge1.setDescription("Desc1");
badge1.setLogo("Logo1");
badge1.setName("Badge1");
badge1.setIssuer(user1);
mBadgeSerivce.save(badge1);
Badge badge2 = new Badge();
badge2.setDescription("Desc2");
badge2.setLogo("Logo2");
badge2.setName("Badge2");
badge2.setIssuer(user2);
mBadgeSerivce.save(badge2);
Badge badge3 = new Badge();
badge3.setDescription("Desc3");
badge3.setLogo("Logo3");
badge3.setName("Badge3");
badge3.setIssuer(user1);
mBadgeSerivce.save(badge3);
user1.setReceivedBadges(Arrays.asList(badge2));
user2.setReceivedBadges(Arrays.asList(badge1,badge3));
}
}
Note: It doesn't save user Received Badges list also , if you can figure that out too , then I will really be thankful to you.
BadgeRepo
import com.badging.spinnerbadger.SpinnerBadger.Models.Badge;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BadgeRepo extends PagingAndSortingRepository<Badge,Long> {
}
UserRepo
import com.badging.spinnerbadger.SpinnerBadger.Models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepo extends JpaRepository<User,Long> {
}
BadgeServiceImpl
package com.badging.spinnerbadger.SpinnerBadger.Services.Implentations;
import com.badging.spinnerbadger.SpinnerBadger.Repository.BadgeRepo;
import com.badging.spinnerbadger.SpinnerBadger.Models.Badge;
import com.badging.spinnerbadger.SpinnerBadger.Services.Intefaces.BadgeSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class BadgeServiceImpl implements BadgeSerivce {
#Autowired
private BadgeRepo mBadgeRepo;
#Override
public List<Badge> getAllBadges(int pageNumber , int sizeOfPage) {
if (sizeOfPage > 20) {
sizeOfPage = 20;
}
final Page<Badge> allPages = mBadgeRepo.findAll(PageRequest.of(pageNumber,
sizeOfPage));
if (allPages.getTotalElements() > 0) {
return allPages.toList();
} else{
return new ArrayList<Badge>();
}
}
#Override
public void save(Badge badge) {
mBadgeRepo.save(badge);
}
}
UserServiceImpl
import com.badging.spinnerbadger.SpinnerBadger.Models.Badge;
import com.badging.spinnerbadger.SpinnerBadger.Models.User;
import com.badging.spinnerbadger.SpinnerBadger.Repository.UserRepo;
import com.badging.spinnerbadger.SpinnerBadger.Services.Intefaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepo mUserRepo;
#Override
public void save(User user) {
mUserRepo.save(user);
}
#Override
public List<Badge> getUsersReceivedBadgeList(long userId) {
final Optional<User> byId = mUserRepo.findById(userId);
return byId.orElse(new User()).getReceivedBadges();
}
#Override
public List<Badge> getUserOwnedBadgeList(long userId) {
final Optional<User> byId = mUserRepo.findById(userId);
return byId.orElse(new User()).getReceivedBadges();
}
}
Generated SQL by Hibernate -> 1st for User model and 2nd for Badge Model
Hibernate: insert into users (fullname, salt, username, user_id) values (?, ?, ?, ?)
Hibernate: insert into badges (badge_description, issuer_id, badge_logo, badge_name, badge_id) values (?, ?, ?, ?, ?)
I see a couple of things that might go wrong here.
You don't seem to have transactions specified. Add #Transactional to those beans or methods that should participate in a transaction. At the very least that should include everything that modifies (eventually) the database, i.e. any statement modifying a managed entity, including the one that loads it from the database and save statements. I'm expecting this to be the actual cause of the problem you are seeing.
You don't seem to have code in place that synchronises the both sides of a bidirectional relationship. So, when you call
badge1.setIssuer(user1),
user1 does not get updated, so if you call user1.getOwnedBadges()
it will still return the unchanged (empty) value.
I doubt it is a problem in this case, but it will result in the
relationship looking different within a single transaction,
depending from which side you are looking at it. And changes to the
non-owning side (User in your case) will not get persisted. So this should be fixed
anyways. See also https://vladmihalcea.com/jpa-hibernate-synchronize-bidirectional-entity-associations/
When saving an entity, you should use the instance returned by the save method, not the one passed to save as an argument. Often they are the same but when they aren't modifying the one passed to save might not result in the state persisted to the database.
If these things are fixed and problems persist I recommend the following to gather more information about what is going on:
Activate logging of SQL statements including parameters in order to see what is actually persisted (and when).
Create a JUnit test testing your services. This makes it much clearer what is actually executed and allows to create variants to compare.

SpringMVC+Hibernate : criteria.list() is returning an empty list

I am using spring MVC with Hibernate, The aim is to get the table data and store it in a list.Here the entity class being used :
package com.bng.core.entity;
// default package
// Generated Oct 25, 2015 4:38:03 PM by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* servicenames generated by hbm2java
*/
#Entity
#Table(name = "servicenames")
public class ServiceNames implements java.io.Serializable {
private Integer id;
private String serviceName;
public ServiceNames() {
}
public ServiceNames(String servicename) {
this.serviceName = servicename;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "servicename", length = 25)
public String getServiceName() {
return this.serviceName;
}
public void setServiceName(String servicename) {
this.serviceName = servicename;
}
}
And the method used to get the list :
#Transactional
#Override
public List<ServiceNames> getServiceNames() {
Logger.sysLog(LogValues.APP_INFO, this.getClass().getName(), "Getting all Service names.");
Session session = sessionFactoryGlobal.openSession();
Criteria criteria = session.createCriteria(ServiceNames.class);
List<ServiceNames> serviceNamesList = criteria.list();
session.close();
return serviceNamesList;
}
When the method is called it returns an empty list. Please suggest where its going wrong ?
I think you are sure your table servicenames has data. So such problem can be when #Transactional is not working properly. Try to get list without #Transactional by open and close a transaction manually.

org.hibernate.hql.internal.ast.QuerySyntaxException: EdbmsEmployee is not mapped [from EdbmsEmployee edbmsEmployee where edbmsEmployee.employeeid=?]

I am working on spring 3 hibernate 4 and new to ORM. so getting below Exception please help.
I know Question for this exception is already asked but in my case i am still facing the issue after trying those solution.
Below is my Entity class
package com.aviva.qc.hrms.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="EDBMS_EMPLOYEE")
public class EdbmsEmployee implements Serializable{
#Id
#Column(name="EMPLOYEEID", nullable=false)
private String employeeid;
#Column(name="FIRSTNAME", nullable=false)
private String firstname;
#Column(name="LASTNAME", nullable=false)
private String lastname;
#Column(name="BANDID", nullable=false)
private String bandid;
#Column(name="DOJ", nullable=false)
private String doj;
#Column(name="DOB", nullable=false)
private String dob;
#Column(name="FUNCTIONNAME", nullable=false)
private String functionname;
public String getEmployeeid() {
return employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getBandid() {
return bandid;
}
public void setBandid(String bandid) {
this.bandid = bandid;
}
public String getDoj() {
return doj;
}
public void setDoj(String doj) {
this.doj = doj;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getFunctionname() {
return functionname;
}
public void setFunctionname(String functionname) {
this.functionname = functionname;
}
}
And here is my daoimplementaion class
package com.aviva.qc.hrms.daoimpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.aviva.qc.hrms.dao.EdbmsEmployeeDao;
import com.aviva.qc.hrms.entity.EdbmsEmployee;
#Repository("edbmsEmployeeDao")
public class EdbmsEmployeeDaoImpl implements EdbmsEmployeeDao{
private static Logger logger = LoggerFactory.getLogger(EdbmsEmployeeDaoImpl.class);
#Autowired
private SessionFactory sessionFactory;
#Transactional(readOnly=true)
public EdbmsEmployee getEdbmsEmployeeDetails(String employeeid){
Session session = sessionFactory.getCurrentSession();
System.out.println("session session "+session);
EdbmsEmployee edbmsEmployee = (EdbmsEmployee)session.createQuery("from EdbmsEmployee edbmsEmployee where edbmsEmployee.employeeid=?")
.setParameter("employeeid",employeeid)
.uniqueResult();
if(logger.isDebugEnabled()){
if(edbmsEmployee==null){
System.out.println("Employee not Found "+edbmsEmployee);
logger.trace("Employee not Found "+edbmsEmployee);
}else{
System.out.println("Employee Found "+edbmsEmployee);
logger.trace("Employee Found "+edbmsEmployee);
}
}
return edbmsEmployee;
}
}
And when i am trying to access dao i am getting below Exception -
org.hibernate.hql.internal.ast.QuerySyntaxException: EdbmsEmployee is not mapped [from EdbmsEmployee edbmsEmployee where edbmsEmployee.employeeid=?]
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3252)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3141)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:694)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:550)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:287)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:235)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:215)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:193)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1649)
at com.aviva.qc.hrms.daoimpl.EdbmsEmployeeDaoImpl.getEdbmsEmployeeDetails(EdbmsEmployeeDaoImpl.java:29)
at com.aviva.qc.hrms.daoimpl.EdbmsEmployeeDaoImpl$$FastClassByCGLIB$$52572915.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:163)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodI
I am trying to resolve it since 3 days but no luck,
I am importing correct Entity class javax.persistence.Entity; and using Entity class name in HQL "from EdbmsEmployee edbmsEmployee where edbmsEmployee.employeeid=?" (Code is running fine before this line giving exception on this line only)
session session SessionImpl(PersistenceContext[entityKeys=[],collectionKeys= []];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])
Sep 30, 2014 11:17:49 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet spring threw exception
and in my Entity class i have used all annotation correctly.
then why i am getting this Exception "EdbmsEmployee is not mapped".
I have googled the solution and found that this exception is come if we import wrong Entity class or if we've used table name in HQL.
In my both is correct.
And I believe while working with these annotation no need to map my entity class in xml file.
Please make sure to add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<property name="packagesToScan" value="com.hibernate.yourpackage" />
With above declaration hibernate would be able to map your entity class with database class
Same thing had happened to me i had to add #EntityScan("com.what ever package your entities are in ") on top of the Application Class .

Resources