How to delete record using primarykey in dynamodb - java

I get the record using primarykey id in amazon dynamodb using java.
AccountController.java
package com.dynamodb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.account.json.AccountJson;
import com.account.service.AccountService;
#Controller
public class AccountController extends AbstractServiceController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/deleteAccountByAccountId", method = RequestMethod.POST)
public #ResponseBody String deleteAccountByAccountId(#RequestBody AccountJson accountJson) {
try {
Boolean bool = accountService.deleteAccountByAccountId(accountJson.getAccountId());
if (bool) {
return "Record deleted Successfully";
} else {
return "Record not deleted";
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
AccountService.java
package com.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.account.dao.AccountRepository;
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public Boolean deleteAccountByAccountId(String accountId) {
return accountRepository.deleteAccountByAccountId(accountId);
}
}
AccountRepository.java
package com.account.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.account.datastore.Account;
#Repository
public class AccountRepository extends BaseRepository {
public Account getAccountByAccountId(String accountId) {
Account account = null;
try {
DynamoDBMapper mapper = getDynameDbMapper();
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression.addFilterCondition("accountId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS(accountId)));
List<Account> accounts = mapper.scan(Account.class, scanExpression);
if (accounts != null && accounts.size() > 0) {
account = accounts.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
public Boolean deleteAccountByAccountId(String accountId) {
try {
Account account = getAccountByAccountId(accountId);
if (account != null) {
DynamoDBMapper mapper = getDynameDbMapper();
mapper.delete(account);
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
Account.java
package com.account.datastore;
import java.io.Serializable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
#DynamoDBTable(tableName = "cd_accounts")
public class Account implements Serializable {
private static final long serialVersionUID = 244669855912873613L;
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
private String documentTypeId;
private String accountName;
private Long isActive;
private Long isBill;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getDocumentTypeId() {
return documentTypeId;
}
public void setDocumentTypeId(String documentTypeId) {
this.documentTypeId = documentTypeId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getIsActive() {
return isActive;
}
public void setIsActive(Long isActive) {
this.isActive = isActive;
}
public Long getIsBill() {
return isBill;
}
public void setIsBill(Long isBill) {
this.isBill = isBill;
}
}
Error is occurred while deleting the record. How to delete the record in amazon dynamodb using java.
com.amazonaws.AmazonServiceException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 ERROR [AccountRepository] deleteAccountByAccountId Error:The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 DEBUG [AccountController] --------------deleteAccountByAccountId----------------END------------------
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.deleteItem(AmazonDynamoDBClient.java:967)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1364)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1272)
at com.account.dao.AccountRepository.deleteAccountByAccountId(AccountRepository.java:110)
at com.account.service.AccountService.deleteAccountByAccountId(AccountService.java:40)
at com.account.controller.AccountController.deleteAccountByAccountId(AccountController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

documentTypeId is primarykey for cd_documentTypes table, this primarykey is used in cd_accounts table as a foreignkey.
If the table having foreignkey relation we must mention the #DynamoDBRangeKey annotation above documentTypeId attribute in Account class. Problem is solved after declared the #DynamoDBRangeKey on top of the attribute documentTypeId.
#DynamoDBRangeKey
private String documentTypeId;
If we want to save or update or delete records in amazon dynamodb using java we must mention the
annotation #DynamoDBHashKey on top of the primarykey column.
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
Below is the image shown for foreignkey relation exists in cd_accounts table.
Note:Range key attribute field is displayed if the table is mapping to another table primarykey in amaozong dynamodb.

Related

'Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' that could not be found.'

This is User class, which serves as the Entity.
package com.userproject.Entities;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "userservice")
public class User {
#Id
#Column(name="userID")
int userId;
#Column(name="username")
String username;
#Column(name="age")
int age;
public User(int userId, String username, int age) {
super();
this.userId = userId;
this.username = username;
this.age = age;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return "User [userId=" + userId + ", username=" + username + ", age=" + age + "]";
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my repository interface
package com.userproject.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.userproject.Entities.User;
public interface UserRepository extends JpaRepository<User, Integer> {
public User findById(int id);
}
This is my Service class
package com.userproject.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.userproject.Entities.User;
import com.userproject.dao.UserRepository;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User addUser(User usr) {
User savedUser = this.userRepository.save(usr);
return savedUser;
}
public List<User> getAllInfo(){
Iterable<User> allUsers = this.userRepository.findAll();
return (List<User>)allUsers;
}
public User getUser(int usrId) {
User usr = this.userRepository.findById(usrId);
if (usr == null)
throw new NullPointerException();
return usr;
}
}
This is my Controller
package com.userproject.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.userproject.Entities.User;
import com.userproject.Service.UserService;
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService service;
#PostMapping("/add")
public ResponseEntity<User> addUser(#RequestBody User u){
try {
User addUser = this.service.addUser(u);
return ResponseEntity.ok(addUser);
} catch(Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
#GetMapping("/{id}")
public ResponseEntity<User> getUserById(#PathVariable("id") int userID){
try {
User u = this.service.getUser(userID);
return ResponseEntity.ok(u);
} catch(NullPointerException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
#GetMapping("/all")
public ResponseEntity<List<User>> getAllUsers(){
try {
return ResponseEntity.ok(this.service.getAllInfo());
} catch(Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
This is my main application class
package com.userproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories("com.userproject.dao")
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class UserProjectApplication {
public static void main(String[] args) {
SpringApplication.run(UserProjectApplication.class, args);
}
}
This is application.properties file
spring.jpa.database=mysql
spring.datasource.username=*****
spring.datasource.password=*****
spring.datasource.url=jdbc:mysql://*******:3306/practice
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.jooq.sql-dialect = org.hibernate.dialect.MySQL57Dialect
spring.jpa.hibernate.ddl-auto= update
This is my project structure:
(https://i.stack.imgur.com/UR10B.png)
When I try to run the application, I keep getting the following message: `
Description:
Field userRepository in com.userproject.Service.UserService required a bean named 'entityManagerFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
If I remove the "exclude" parameter from #SpringBootApplication, it throws an error stating the datasource cannot be configured as the url is missing.
If I remove the #EnableJpaRepositories, it throws an error stating my userRepository field in Service class cannot be configured.
From what I understand, this whole problem arises from me trying to autowire the userRepository field (which is actually an interface) in the Service class. However, SpringBoot shall be able to do that with the help of proxy classes.
Please provide me with a solution to this.

Unable to locate persister

I have the following problem when i try to do the findCliente method. I have the class Cliente in the package model and when i run the findCliente controller I get this exception here. I don't know where I'm wrong because I don't have much skill with JPA and Spring Suite. Can someone tell me how to fix this exception?
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3416)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.UnknownEntityTypeException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.metamodel.internal.MetamodelImpl.locateEntityPersister(MetamodelImpl.java:727)
org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:3019)
org.hibernate.internal.SessionImpl.access$1800(SessionImpl.java:201)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2715)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2698)
org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1180)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3380)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
AppConfig
package it.myshop.orm.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
#EnableWebMvc
#Configuration
#ComponentScan("it.myshop.orm.controller")
public class AppConfig {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver iwv = new InternalResourceViewResolver();
iwv.setPrefix("/WEB-INF/view/");
iwv.setSuffix(".jsp");
iwv.setViewClass(JstlView.class);
return iwv;
}
//BEAN CONNESSIONE AL DB
#Bean
public DataSource getDbConnection() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/corso-spring-ud?serverTimezone=CET");
ds.setUsername("root");
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManager() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(getDbConnection());
factory.setJpaVendorAdapter(adapter); //passo adapter
factory.setPackagesToScan(getClass().getPackage().getName());
return factory;
}
#Bean
public ClienteService getClienteServiceImpl() {
return new ClienteServiceImpl();
}
App Initializer
package it.myshop.orm.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import it.myshop.orm.config.AppConfig;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
ClienteController
package it.myshop.orm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
import it.myshop.orm.model.Cliente;
#Controller
#RequestMapping("/cliente")
public class ClienteController {
#Autowired
private ClienteService cs;
#ResponseBody
#GetMapping("/add")
public String add() {
// cs.add(null);
System.out.println("Sei nella pagina di aggiunta");
return null;
}
#ResponseBody
#GetMapping("/findCliente")
public String findCliente() {
Cliente c = cs.getById(1);
System.out.println("Sei nella pagina di find del Cliente");
return c.getNome() + " " + c.getCognome();
}
Cliente
package it.myshop.orm.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String nome;
#Column
private String cognome;
#Column
private String codiceFiscale;
#Column
private String email;
#Column
private String telefono;
#Column
private String username;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getCodiceFiscale() {
return codiceFiscale;
}
public void setCodiceFiscale(String codiceFiscale) {
this.codiceFiscale = codiceFiscale;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Interface ClienteService
package it.myshop.orm.dao;
import it.myshop.orm.model.Cliente;
public interface ClienteService {
public Cliente add(Cliente c);
public Cliente getById(int id);
}
ClienteServiceImpl
package it.myshop.orm.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.model.Cliente;
public class ClienteServiceImpl implements ClienteService {
#PersistenceContext
public EntityManager em;
#Override
public Cliente add(Cliente c) {
em.persist(c);
return c;
}
#Override
public Cliente getById(int id) {
return em.find(Cliente.class, id);
}
}
In order to solve this problem you have two options. You can choose either of which .
1- you must have all you entity classes declared in you hibernate configuration file.
for this you must add you entity classes specially "Cliente" in hibernate.cfg.xml file
like this :
<mapping class="entity.Client"/>
or
2-another way is adding this entity to session configuration like this :
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Cliente.class) .buildSessionFactory();

No Session with spring.jpa.open-in-view=false

I have a Spring Boot 2.1 app with a simple rest controller, service tier, and data tier. I am attempting to disable spring.jpa.open-in-view as I want to manage the loading of my collections, etc. My problem seems to be when I disable open-in-view, I can't get anything back in my controller including simple properties including Strings.
Sample Project, simplified version of the code below:
https://github.com/csyperski/springbootopeninview
Here is my error:
2019-02-05 09:06:19.591 -ERROR 11355 --- [nio-8081-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : 175 : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session] with root cause
-
org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at com.cwssoft.pscafepos.model.Item$HibernateProxy$h2GPuZuU.getBuilding(Unknown Source) ~[main/:na]
at com.cwssoft.pscafepos.controllers.ItemController.lambda$getSingle$3(ItemController.java:52) ~[main/:na]
at java.util.Optional.filter(Optional.java:178) ~[na:1.8.0_201]
at com.cwssoft.pscafepos.controllers.ItemController.getSingle(ItemController.java:52) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
Here is my Model without getters/setters:
import com.cwssoft.pscafepos.model.converters.BooleanToStringConverter;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name="items", indexes = {
#Index(name="key_items_name", columnList="item_name"),
#Index(name="key_items_building", columnList="item_building"),
#Index(name="key_items_visible", columnList="item_visible"),
#Index(name="key_items_free", columnList="item_allowfree"),
#Index(name="key_items_reduced", columnList="item_allowreduced"),
#Index(name="key_items_typea", columnList="item_istypea"),
})
public class Item implements DomainObject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "item_id", updatable = false, nullable = false)
private Long id;
#Column(name="item_name", length = 100, nullable = false, unique = false)
private String name;
#Column(name="item_description", columnDefinition = "TEXT")
private String description;
#Column(name="item_price")
private double price;
#Column(name="item_building", length = 100, nullable = false, unique = false)
private String building;
#Column(name="item_category", columnDefinition = "TEXT")
private String category;
#Column(name="item_visible", length = 1, nullable = false, unique = false)
#Convert(converter= BooleanToStringConverter.class)
private boolean visible;
#Column(name="item_allowfree", length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowFree;
#Column(name="item_allowreduced",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowReduced;
#Column(name="item_istypea",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean typeA;
#Column(name="item_reducedprice")
private double reducedPrice;
#Column(name="item_addby", length = 100, nullable = false, unique = false)
private String addedBy;
#Column(name="item_adddate")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name="item_fr_bl")
private int freeReducedBreakfastLunch;
}
Here is my Service Tier:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.repositories.ItemRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
#Service
public class DefaultItemService extends BaseService<Item, ItemRepository> implements ItemService {
public DefaultItemService(ItemRepository itemRepository) {
super(itemRepository);
}
#Override
#Transactional
public Optional<Item> findByName(String name) {
if (name != null) {
return Optional.ofNullable(repository.findByName(name.trim()));
}
return Optional.empty();
}
#Override
#Transactional
public List<Item> findAll(String building) {
if (building != null) {
return repository.findByBuildingOrderByVisibleDescNameAsc(building.trim());
}
return Collections.emptyList();
}
}
and the service super class:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.DomainObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Slf4j
public abstract class BaseService<T extends DomainObject,U extends JpaRepository<T,Long>> implements CrudService<T,U> {
protected final U repository;
public BaseService(U repository) {
this.repository = repository;
}
public U getRepository() {
return repository;
}
#Transactional
public List<T> findAll() {
return repository.findAll();
}
#Transactional
public List<T> findAll(Sort sort) {
return repository.findAll(sort);
}
#Transactional
public List<T> findAllById(Iterable<Long> ids) {
return repository.findAllById(ids);
}
#Transactional
public Optional<T> save(T item) {
return Optional.ofNullable(repository.saveAndFlush(item));
}
#Transactional
public Optional<T> get(long id) {
return Optional.ofNullable(prepare(repository.getOne(id)));
}
#Transactional
public T prepare( T item ) {
return item;
}
#Transactional
public void delete(long id) {
get(id).ifPresent( repository::delete );
}
}
And the controller:
package com.cwssoft.pscafepos.controllers;
import com.cwssoft.pscafepos.model.AdminUser;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.services.AdminUserService;
import com.cwssoft.pscafepos.services.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
#RestController
#RequestMapping("/items")
#Slf4j
public class ItemController extends BaseController {
private final ItemService service;
public ItemController(ItemService itemService, AdminUserService adminUserService) {
super(adminUserService);
this.service = itemService;
}
#GetMapping("/all")
#Secured("CAFE_MANAGER")
public List<Item> all(Principal principal) {
return getLocation(principal)
.map( service::findAll )
.orElse( Collections.emptyList() );
}
#GetMapping("/single/{itemId}")
#Secured("CAFE_MANAGER")
public Item getSingle(Principal principal, #PathVariable("itemId") long id) {
final Optional<String> location = getLocation(principal);
location
.flatMap( l -> service.get(id) )
.ifPresent( item -> {
log.info("Item.toString {}", item);
});
return location
.flatMap( l -> service.get(id) )
.filter( item -> item.getBuilding() != null && item.getBuilding().equalsIgnoreCase(location.orElse(null)) )
.orElse( null );
}
}
So what am I missing, why can't I pull back basic properties, there are no collections in the Item class and it about as simple as they come. I see that I'm getting a HibernateProxy wrapped object back and when I attempt to call getBuilding is when it appears to be failing, even though building is just a simple string. This is all before Jaskson is attempting to serialize the object to put it over the wire. Thanks!

org.springframework.web.util.NestedServletException and org.hibernate.HibernateException: No Session found for current thread

i am trying to insert some record into my database table using spring hibernate,but the following error occur after running the project.please help me to solve the problem..thanks
Entity class Admin.java
package com.finalproject.entity;
// Generated Apr 20, 2017 4:49:19 PM by Hibernate Tools 4.3.1
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;
/**
* Admin generated by hbm2java
*/
#Entity
#Table(name="admin"
,catalog="advertisement_system"
)
public class Admin implements java.io.Serializable {
private Integer adminId;
private String adminName;
private String adminEmail;
private String adminPass;
private byte[] adminPhoto;
public Admin() {
}
public Admin(String adminName, String adminEmail, String adminPass) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
}
public Admin(String adminName, String adminEmail, String adminPass, byte[] adminPhoto) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
this.adminPhoto = adminPhoto;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="admin_id", unique=true, nullable=false)
public Integer getAdminId() {
return this.adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
#Column(name="admin_name", nullable=false, length=45)
public String getAdminName() {
return this.adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
#Column(name="admin_email", nullable=false, length=45)
public String getAdminEmail() {
return this.adminEmail;
}
public void setAdminEmail(String adminEmail) {
this.adminEmail = adminEmail;
}
#Column(name="admin_pass", nullable=false, length=45)
public String getAdminPass() {
return this.adminPass;
}
public void setAdminPass(String adminPass) {
this.adminPass = adminPass;
}
#Column(name="admin_photo")
public byte[] getAdminPhoto() {
return this.adminPhoto;
}
public void setAdminPhoto(byte[] adminPhoto) {
this.adminPhoto = adminPhoto;
}
}
AdminServiceImpl.java class
package com.finalproject.service.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Service("adminService")
#Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
#Autowired
AdminDao adminDao;
#Override
public void create(Admin admin) {
adminDao.create(admin);
}
#Override
public void update(Admin admin) {
adminDao.update(admin);
}
#Override
public void delete(Long adminId) {
adminDao.delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return adminDao.edit(adminId);
}
#Override
public List<Admin> getAll() {
return adminDao.getAll();
}
#Override
public Admin find(Long adminId) {
return adminDao.find(adminId);
}
}
Dao implemented class AdminDaoImpl.java
package com.finalproject.dao.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void create(Admin admin) {
currentSession().save(admin);
}
#Override
public void update(Admin admin) {
currentSession().update(admin);
}
#Override
public void delete(Long adminId) {
currentSession().delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return find(adminId);
}
#Override
public Admin find(Long adminId) {
return (Admin) currentSession().get(Admin.class, adminId);
}
#Override
public List<Admin> getAll() {
return currentSession().createCriteria(Admin.class).list();
}
}
controller class AdminController.java
package com.finalproject.controller;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#Autowired
AdminService adminService;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Map<String, Object> map) {
map.put("adminReg", new Admin());
return "/admin/add";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Admin admin, Map<String, Object> map) {
adminService.create(admin);
return "redirect:/admin/details/" + admin.getAdminId();
}
#RequestMapping(value = "/details/{adminId}",method = RequestMethod.GET)
public String details(#PathVariable("adminId") Long adminId, Map<String, Object> map) {
Admin admin = adminService.find(adminId);
map.put("adminName", admin.getAdminName());
map.put("adminEmail", admin.getAdminEmail());
map.put("adminPass", admin.getAdminPass());
return "admin/details";
}
}
Error message
type Exception report
message Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
com.finalproject.dao.impl.AdminDaoImpl.currentSession(AdminDaoImpl.java:19)
com.finalproject.dao.impl.AdminDaoImpl.create(AdminDaoImpl.java:24)
com.finalproject.service.impl.AdminServiceImpl.create(AdminServiceImpl.java:22)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy125.create(Unknown Source)
com.finalproject.controller.AdminController.create(AdminController.java:29)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Error Message
AdminDaoImpl.java

Hibernate No Session (No Dependencies)

I have the following JPA entity (generated with Netbeans):
package com.tsystems.tf.db.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johorvat
*/
#Entity
#Table(name = "TABLE1")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Testcase.findAll", query = "SELECT t FROM Testcase t")
})
public class Testcase implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "TESTCASE_ID")
private BigDecimal testcaseId;
#Basic(optional = false)
#Column(name = "TESTCASE_NAME")
private String testcaseName;
#Basic(optional = false)
#Column(name = "CREATOR")
private String creator;
#Basic(optional = false)
#Column(name = "CREATED_AT")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Column(name = "LAST_RUN")
#Temporal(TemporalType.TIMESTAMP)
private Date lastRun;
#Column(name = "LAST_RUN_RESULT")
private Character lastRunResult;
#Column(name = "INPUT")
private String input;
#Column(name = "OUTPUT")
private String output;
public Testcase() {
}
public Testcase(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public Testcase(BigDecimal testcaseId, String testcaseName, String creator, Date createdAt) {
this.testcaseId = testcaseId;
this.testcaseName = testcaseName;
this.creator = creator;
this.createdAt = createdAt;
}
public BigDecimal getTestcaseId() {
return testcaseId;
}
public void setTestcaseId(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public String getTestcaseName() {
return testcaseName;
}
public void setTestcaseName(String testcaseName) {
this.testcaseName = testcaseName;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastRun() {
return lastRun;
}
public void setLastRun(Date lastRun) {
this.lastRun = lastRun;
}
public Character getLastRunResult() {
return lastRunResult;
}
public void setLastRunResult(Character lastRunResult) {
this.lastRunResult = lastRunResult;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
#Override
public int hashCode() {
int hash = 0;
hash += (testcaseId != null ? testcaseId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Testcase)) {
return false;
}
Testcase other = (Testcase) object;
if ((this.testcaseId == null && other.testcaseId != null) || (this.testcaseId != null && !this.testcaseId.equals(other.testcaseId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.tsystems.tf.db.models.Testcase[ testcaseId=" + testcaseId + " ]";
}
}
I try to implement CRUD operations for this entity using Hibernate but I get LazyEvaluationException. There are NO references. Its only 1 table in the database... I can query but when I try to issue update the exception is being thrown. Now I have a really naive implementation that looks like the following:
package com.tsystems.tf.dao.impl;
import com.tsystems.tf.dao.ITestcaseDAO;
import com.tsystems.tf.db.models.Testcase;
import java.math.BigDecimal;
import java.util.Collection;
import javax.transaction.Transactional;
import org.apache.catalina.tribes.util.Arrays;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;
public class TestcaseDAOImpl implements ITestcaseDAO {
private static final SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
}
#Override
public Collection<Testcase> getAllTestcase() {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Collection<Testcase> testcaseCollection = null;
try {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("Testcase.findAll");
testcaseCollection = query.list();
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcaseCollection;
}
#Override
public void createTestcase(Testcase testcase) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Testcase readTestcase(BigDecimal id) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Testcase testcase = null;
try {
transaction = session.beginTransaction();
testcase = (Testcase) session.load(Testcase.class, id);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcase;
}
#Override
public void updateTestcase(Testcase testcase) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(testcase);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
}
#Override
public void deleteTestcase(BigDecimal testcaseId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
When the update is being called bamm No Session. Why is this happening? GetAll succeeds nice and smooth but that's all to it. Everything else returns in No Session error in my logs.
StackTrace:
14-Nov-2014 16:54:43.012 WARNING [http-apr-8080-exec-148] com.sun.faces.context.SessionMap.put JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: testcaseProvider, value class: com.tsystems.tf.beans.TestcaseProvider).
14-Nov-2014 16:54:46.812 WARNING [http-apr-8080-exec-148] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
javax.faces.FacesException: #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 29 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
14-Nov-2014 16:54:46.832 SEVERE [http-apr-8080-exec-148] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
replace your static block by a before() method, and add the session creation at the end of it :
#Before
public void before() {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
session = sessionFactory.openSession();
}
and an after() method :
#After
public void after {
session.close();
sessionFactory.close();
}
And of course, remove all open/close session in each test.

Categories