Bidirectional Association In JPA Repository Not Working - java

Here are my tables:
ORDER
CREATE TABLE ORDER_DETAILS (
ID INT NOT NULL AUTO_INCREMENT
, ORDER_ID VARCHAR(60) NOT NULL
, ADDRESS_ID INT
-- , DRIVER_ID INT
, BARCODE_ID INT
, CUSTOMER_ID VARCHAR(60)
, CUSTOMER_PIN VARCHAR(60)
, UNIQUE UQ_ORDER_ID_1 (ORDER_ID)
, FOREIGN KEY(BARCODE_ID) REFERENCES public.BARCODE(ID)
, PRIMARY KEY (ID)
);
AND BARCODE
CREATE TABLE BARCODE (
ID INT NOT NULL AUTO_INCREMENT
, BARCODE_DETAILS VARCHAR(60) NOT NULL
, DRIVER_ID INT
, VERSION INT NOT NULL DEFAULT 0
, UNIQUE UQ_BARCODE_ID_1 (BARCODE_DETAILS)
, PRIMARY KEY (ID));
Order to Barcode is Many To One Relationship i.e. Many Order Can Have One barcode
Here Are My repositories
OrderRepository
package com.eppvd.application.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.eppvd.application.domain.Address;
import com.eppvd.application.domain.Customer;
import com.eppvd.application.domain.Driver;
import com.eppvd.application.domain.Order;
public interface OrderRepository extends JpaRepository<Order, Long> {
Order findByOrderId(String orderId);
// Order findByBarcode(String barcode);
Order findByCustomerPin(String customerPin);
// Order findByDriver(Driver driver);
Order findByAddress(Address address);
Order findByCustomer(Customer customer);
}
And BarcodeRepository
package com.eppvd.application.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.eppvd.application.domain.Barcode;
public interface BarcodeRepository extends JpaRepository<Barcode, Long> {
Barcode findByBarcode(String barcode);
}
Here Are My ServiceImpls
OrderServiceImpl
package com.eppvd.application.service.jpa;
/** imports **/
#Service("OrderService")
#Repository
#Transactional
public class OrderServiceImpl implements OrderService {
/** Other Methods **/
#Override
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Order save(Order order) {
return orderRepository.save(order);
}
#Override
public void flush(){
orderRepository.flush();
}
}
And BarcodeServiceImpl
package com.eppvd.application.service.jpa;
#Service(value="barcodeService")
#Repository
#Transactional
public class BarcodeServiceImpl implements BarcodeService{
#Autowired
BarcodeRepository barcodeRepository;
#Override
#Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public Barcode save(Barcode barcode) {
return barcodeRepository.save(barcode);
}
}
And Entities
package com.eppvd.application.domain;
#Entity
#Table(name = "order_details")
public class Order implements Serializable {
private Barcode barcode;
#ManyToOne(optional = false)
#JoinColumn(name="BARCODE_ID")
public Barcode getBarcode() {
return barcode;
}
public void setBarcode(Barcode barcode) {
this.barcode = barcode;
}
}
package com.eppvd.application.domain;
#Entity
#Table(name = "barcode")
public class Barcode implements Serializable {
private static final long serialVersionUID = 3202943305655732979L;
private Long id;
private int version;
private String barcode_details;
private Set<Order> orders ;
#Column(name="BARCODE_DETAILS")
public String getBarcodeDetails() {
return barcodeDetails;
}
public void setBarcodeDetails(String barcode) {
this.barcodeDetails = barcode;
}
#OneToMany(cascade=CascadeType.ALL,mappedBy="barcode",fetch=FetchType.EAGER)
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
and application Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema.sql"/>
<!-- <jdbc:script location="classpath:test-data.sql"/> -->
</jdbc:embedded-database>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="com.eppvd.application.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<context:annotation-config/>
<jpa:repositories base-package="com.eppvd.application.repository"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/>
<!-- <bean id="customerService" class="com.eppvd.application.service.jpa.CustomerServiceImpl"> -->
<!-- </bean> -->
<context:component-scan base-package="com.eppvd.application.service.jpa"></context:component-scan>
</beans>
And JUNit Test
package com.eppvd.application.service;
import static org.junit.Assert.*;
#ContextConfiguration(locations="classpath:datasource-tx-jpa.xml")
#RunWith(SpringJUnit4ClassRunner.class)
#Transactional
public class OrderServiceTest {
#Autowired
private OrderService orderService;
#Autowired
private BarcodeService barcodeService;
#Before
public void createAddressCustomerDriver(){
Barcode barcode = new Barcode();
barcode.setBarcodeDetails("1234");
barcodeService.save(barcode);
}
#Test
public void testCreateOrder() {
Barcode barcode = barcodeService.findByBarcode("1234");
Order order = new Order();
order.setOrderId("OD001");
order.setBarcode(barcode);
order.setCustomerPin("1234");
order.setCustomer(customerService.findByFirstName("Abhijit"));
order.setAddress(addressService.findByStreet("BTM Layout"));
orderService.save(order);
orderService.flush();
Set<Order> orders = barcode.getOrders();
assertEquals("1234", orderService.findByOrderId("OD001").getBarcode().getBarcodeDetails()); /**Works **/
assertEquals(1, orders.size()); /**FAILS **/
}
}
I tried To be as detailed as possible. So it became a bit long. Any help would be greatly appreciated. I tried to figure out everything logically but not too sure what am I missing.There is little documentation around this area

You created an Order, and initialized its barcode. But you never added the order to the set of orders of the barcode. So its set of barcodes is empty. That's expected.
You're supposed to maintain the two sides of an association if you expect them to be coherent.

Related

Exception:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I am getting error after deploying the application. I have checked similar questions but still could not resolve the error. I have used #Transactional for the service class as well as
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
com.utd.dao.CustomerDaoImpl.getAllCustomer(CustomerDaoImpl.java:22)
com.utd.service.CustomerManagerImpl.getAllCustomer(CustomerManagerImpl.java:23)
com.utd.controller.CustomerController.listCustomers(CustomerController.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.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
I have following project files:
The controller:
#Controller
public class CustomerController {
#Autowired
private CustomerManager customerManager;
#RequestMapping(value="/", method= RequestMethod.GET)
public String listCustomers(ModelMap map){
map.addAttribute("customer", new Customer());
map.addAttribute("customerList", customerManager.getAllCustomer());
return "CustomerList";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute(value="customer") Customer customer, BindingResult result)
{
customerManager.addCustomer(customer);
return "redirect:/";
}
#RequestMapping("/delete/{customerId}")
public String deleteEmplyee(#PathVariable("customerId") Integer customerId)
{
customerManager.deleteCustomer(customerId);
return "redirect:/";
}
public void setCustomerManager(CustomerManager customerManager) {
this.customerManager = customerManager;
}
}
The dao class
public class CustomerDaoImpl implements CustomerDao{
#Autowired
private SessionFactory sessionFactory;
public void addCustomer(Customer customer) {
this.sessionFactory.getCurrentSession().save(customer);
}
#SuppressWarnings("unchecked")
public List<Customer> getAllCustomer() {
return this.sessionFactory.getCurrentSession().createQuery("from Customer").list();
}
public void deleteCustomer(Integer customerId) {
Customer customer = (Customer) sessionFactory.getCurrentSession().load(Customer.class, customerId);
if (null != customer) {
this.sessionFactory.getCurrentSession().delete(customer);
}
}
}
The Dto:
#Entity
#Table(name="Customer")
public class Customer {
#Id
#Column(name="ID")
#GeneratedValue
private int id;
#Column(name="NAME")
private String name;
#Column(name="CONTACT")
private String contact;
#Column(name="EMAIL")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
customer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.utd.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}"></bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="customerDao" class="com.utd.dao.CustomerDaoImpl"></bean>
<bean id="customerManager" class="com.utd.service.CustomerManagerImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.utd" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Manager class Implementation
package com.utd.service;
import com.utd.dao.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.utd.dto.Customer;
import javax.transaction.Transactional;
import java.util.List;
#Service
public class CustomerManagerImpl implements CustomerManager {
#Autowired
private CustomerDao customerDao;
#Transactional
public void addCustomer(Customer customer) {
customerDao.addCustomer(customer);
}
#Transactional
public List<Customer> getAllCustomer() {
return customerDao.getAllCustomer();
}
#Transactional
public void deleteCustomer(Integer customerId) {
customerDao.deleteCustomer(customerId);
}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
}
I would like to know how to resolve the error.

Why "org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]" error is coming

i am facing below error:
Type Exception Report
Message Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]
Entity Class:
package com.luv2code.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//#Table(schema = "web_customer_tracker", name = "customer")
#Table(name="customer")
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
DAO impl:
package com.luv2code.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.luv2code.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
//get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
//List customers = new ArrayList<Customer>();
//create a query
Query<Customer> theQuery=currentSession.createQuery("from customer", Customer.class);
//currentSession.createQuery("from Customer", Customer.class);
//execute query and get result list
List<Customer> customers=theQuery.getResultList();
// return the results
/* Customer cus1=new Customer();
cus1.setEmail("a#gmail.com");
cus1.setFirstName("Abhishek");
cus1.setId(10);
cus1.setLastName("Kumar");
customers.add(cus1); */
return customers;
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
There is a difference between the entity Customer and the relational table customer.
When you specify #Table(name="customer"), you ask your JPA implementation to use customer as table name which it is probably doing (check in your database).
When you specify createQuery("from customer", Customer.class), you ask your JPA implementation to create a JPQL query and customer is not a known entity because that's Customer or com.luv2code.springdemo.entity.Customer the entity.

java.lang.NullPointerException while trying to fetch entity by id

I'am using spring and hibernate.
My entity:
package com.igorgorbunov3333.core.entities.domain;
import com.igorgorbunov3333.core.entities.enums.Proceeding;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Игорь on 03.04.2016.
*/
#Entity
#Table(name = "cases")
#NamedQueries({
#NamedQuery(name = "getAllCases", query = "SELECT c FROM Case c JOIN FETCH c.client JOIN FETCH c.firstInstance " +
"JOIN FETCH c.secondInstance JOIN FETCH c.thirdInstance JOIN FETCH c.category")
})
public class Case {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "case_number")
private String caseNumber;
#ManyToOne
#JoinColumn(name = "client_id")
private Client client;
#OneToOne
#JoinColumn(name = "first_instance_id")
private FirstInstance firstInstance;
#OneToOne
#JoinColumn(name = "second_instance_id")
private SecondInstance secondInstance;
#OneToOne
#JoinColumn(name = "third_instance_id")
private ThirdInstance thirdInstance;
#Enumerated(EnumType.ORDINAL)
private Proceeding proceeding;
#Temporal(TemporalType.DATE)
#Column(name = "closing_date")
private Date closingDate;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
private float price;
public long getId() {
return id;
}
public String getCaseNumber() {
return caseNumber;
}
public Client getClient() {
return client;
}
public FirstInstance getFirstInstance() {
return firstInstance;
}
public SecondInstance getSecondInstance() {
return secondInstance;
}
public ThirdInstance getThirdInstance() {
return thirdInstance;
}
public Proceeding getProceeding() {
return proceeding;
}
public Date getClosingDate() {
return closingDate;
}
public Category getCategory() {
return category;
}
public float getPrice() {
return price;
}
public void setId(long id) {
this.id = id;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public void setClient(Client client) {
this.client = client;
}
public void setFirstInstance(FirstInstance firstInstance) {
this.firstInstance = firstInstance;
}
public void setSecondInstance(SecondInstance secondInstance) {
this.secondInstance = secondInstance;
}
public void setThirdInstance(ThirdInstance thirdInstance) {
this.thirdInstance = thirdInstance;
}
public void setProceeding(Proceeding proceeding) {
this.proceeding = proceeding;
}
public void setClosingDate(Date closingDate) {
this.closingDate = closingDate;
}
public void setCategory(Category category) {
this.category = category;
}
public void setPrice(float price) {
this.price = price;
}
}
spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
<!--#Transaction annotation support -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--Scanning components in base-package (look for annotations) -->
<context:component-scan base-package="com.igorgorbunov3333"/>
<!--Activates various annotations to be detected in bean classes: Spring's #Required and #Autowired and so on-->
<context:annotation-config/>
<!--Обеспечивает работу с транзакциями в Spring -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<!-- Datasource. Источник данных - база MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/database" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- EntityManagerFactory -->
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--Поставщик данных - hibernate-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<!--поиск сущностей в этом пакете-->
<property name="packagesToScan"
value="com.igorgorbunov3333"/>
<!--детали конфигурации поставщика постоянства (hibernate) -->
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
Here I'm getting NullPointerException:
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
I sure to you - id is correct, but entity can't be found. But when I'm getting all entities all fine:
public List<Case> findAll() {
Query query = entityManager.createNamedQuery("getAllCases");
return query.getResultList();
}
What is the reason?
Full track of NPE:
09-Oct-2016 12:40:41.650 SEVERE [http-nio-8080-exec-7] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ShowSingleCase] in context with path [] threw exception
java.lang.NullPointerException
at com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl.findById(CaseServiceImpl.java:32)
at com.igorgorbunov3333.web.servlet.display.single.ShowSingleCase.doGet(ShowSingleCase.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1096)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:760)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1480)
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)
My CaseServiceImpl:
package com.igorgorbunov3333.core.entities.service.impl;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.enums.CaseStatus;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.util.DateUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;
/**
* Created by Игорь on 27.07.2016.
*/
#Repository
#Service("CaseService")
public class CaseServiceImpl implements CaseService {
#PersistenceContext
private EntityManager entityManager;
public Case findById(long id) {
return entityManager.find(Case.class, id);
}
}
Servlet:
package com.igorgorbunov3333.web.servlet.display.single;
import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.entities.service.impl.CaseServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.igorgorbunov3333.web.util.Views.SINGLE_CASE_PAGE;
/**
* Created by Игорь on 09.08.2016.
*/
#WebServlet(name = "ShowSingleCase", urlPatterns = "/showSingleCase")
public class ShowSingleCase extends HttpServlet {
private CaseService caseService = new CaseServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long id = Long.valueOf(request.getParameter("caseID"));
Case c = caseService.findById(id);
request.setAttribute("case", c);
request.getRequestDispatcher(SINGLE_CASE_PAGE).forward(request, response);
}
}
Your problem is in this line:
private CaseService caseService = new CaseServiceImpl();
That's not how dependency injection works. You're instantiating your CaseService object manually. In this case framework won't inject any dependencies so your private EntityManager entityManager; field will be null. Instead you have to annotate your caseService field with #Autowired annotation. That will tell Spring to inject the bean from context:
#Autowired
private CaseService caseService;
The only thing that can be null (is not primitive) on the line you stated that would cause a problem is entityManager, so you're looking for the underlying reason for this, which I don't see in the code you posted.
As you are creating CaseServiceImpl class object by yourself in your servlet class, entityManager object is not autowire automatically by spring and that is the reason you are getting NullPointerException. either you should autowire service class object into servlet class so that spring will resolve entitymanager dependency by itself and provide you fully configured service object or you should set entity manager object into your service class while creating its object in servlet.

Spring Framework - Hibernate

I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

org.hibernate.hql.ast.QuerySyntaxException

org.hibernate.hql.ast.QuerySyntaxException:
users is not mapped [SELECT email, id
FROM users WHERE email='dsdd#dds.com'
AND password='asasas']
public ILogin authenticate(Login login) {
System.out.println(login);
System.out.println(login.getEmail());
String query = "SELECT email, id FROM users WHERE email='"
+ login.getEmail() + "' AND password='" + login.getPassword() + "'";
results = getHibernateTemplate().find(query);
System.out.println(results);
return null;
}
I have a Login Bean class... here it follows.
package
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Login {
public Login(){}
private Long id = null;
private String email;
private String password;
public Login(String email, String password)
{
this.email = email;
this.password = password;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" default-autowire="byName"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Turn on AspectJ #Configurable support -->
<context:spring-configured />
<context:property-placeholder location="classpath*:*.properties" />
<context:component-scan base-package="com.intermedix"/>
<context:annotation-config/>
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.intermedix.domain.Login</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"/>
<property name="username" value="monty"/>
<property name="password" value="indian"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Even if it does not belong to your question:
Don't use Hibernate/JPA in this way (String concatination) !:
String query = "SELECT email, id FROM users AS u WHERE email='"+ login.getEmail() + "' AND password='" + login.getPassword() + "'";
Instead use HQL like prepared statements:
createQuery(
"SELECT l FROM login WHERE l.email=:email AND l.password=:password")
.setParameter("login",login.getEmail())
.setParameter("password",login.getPassword());
If you do it in "your style" you will have lot of fun with SQL Injections!
Next: read the hibernate reference about HQL, for me it looks like you are writing SQL instead of HQL.
SELECT email, id FROM users
What is "users"? There is nothing in your config or code called "users", so Hibernate has no idea what you're talking about.
Secondly, your Login class is not annotated with #Entity, so Hibernate is likely ignoring it.
So add the annotation, and most likely change your query to:
SELECT email, id FROM Login
Looks obvious to me : "users is not mapped..."
Either you didn't map the Users table, or you have it incorrectly configured.
#Entity
#Table(name="users")
public class Login {
You actually need to annotate Login class since you say (<property name="annotatedClasses">) that in application-context.xml for example like this.
#Column(name="password")
public String getPassword() {
return password;
}
List list = getHibernateTemplate().find("from Form3A where FAC_ID=?",FAC_ID);
HERE Form3A is name of class and config file is
<property name="annotatedClasses">
<list>
<value>org.fbis.models.Form3A</value>
</list>
</property>

Categories