I have a problem with Spring and Oracle, I can select objects, but I can't update and insert. (I usually use MySql)
Aplication 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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="{jdbc.username}"
p:password="${jdbc.password}" />
<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="jdbcTransactionManager"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="namePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="package.repository" />
<context:component-scan base-package="package.service" />
</beans>
jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#172.172.10.83:1521:orcl
jdbc.username=User
jdbc.password=Password
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
jpa.database = ORACLE
hibernate.generate_statistics = true
hibernate.show_sql = true
jpa.showSql = true
jpa.generateDdl = true
Usuario class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_USUARIO")
private String idUsuario;
#Column(name = "LOGIN")
private String login;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_AMBITO")
private Ambito ambito;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_ROL")
private Rol rol;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Ambito getAmbito() {
return ambito;
}
public void setAmbito(Ambito ambito) {
this.ambito = ambito;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
JPAUsuarioDao
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository(value = "usuarioDao")
public class JPAUsuarioDao implements UsuarioDao {
private EntityManager em = null;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override
#Transactional(readOnly = true)
public List<Usuario> getUsuariosList() {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u",
Usuario.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Usuario getUsuario(String login) throws NoResultException {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u WHERE u.login ='" + login + "'",
Usuario.class);
return query.getSingleResult() ;
}
#Override
#Transactional(readOnly = false)
public void addUsuario(Usuario usuario) {
em.merge(usuario);
}
}
This is the exception afer em.merge:
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No unresolved entity inserts that depended on [[package.domain.Usuario#70675c9a-5eb4-4241-aa83-9cdea9211d18]]
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No entity insert actions have non-nullable, transient entity dependencies.
Thank you
Related
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.
I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
Spring.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<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://localhost:3306/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.
I've been using objectDB as a database in my Spring application, yet it is only free for up to 10 tables, so i've tried to migrate to MySQL. When I look into database the tables are created, but when I try to persist I get the NullPointerException. Here are my configuration files:
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="cinemabookPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>cinemaDbCon</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
spring-servlet.xml:
<?xml version="1.0" encoding="windows-1252"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use #Component annotations for bean definitions -->
<context:component-scan base-package="cinema"/>
<!-- Use #Controller annotations for MVC controller definitions -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
</property>
</bean>
<tx:jta-transaction-manager />
<tx:annotation-driven />
<bean class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<import resource="/spring-security.xml" />
</beans>
Model City:
package cinema.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class City implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
protected City() {
}
public City(Long id, String name) {
this.id = id;
this.name = name;
}
public City(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
CityService.java:
package cinema.services;
import cinema.model.City;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
public interface CityService {
// Stores a new city:
#Transactional
public void persist(City city);
// Retrieves all the citys:
public List<City> getAllCities();
public City getCityById(Long id);
public void deleteAllCities();
}
CityServiceImpl.java:
package cinema.services.impl;
import cinema.services.CityService;
import cinema.model.City;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Component
public class CityServiceImpl implements CityService {
// Injected database connection:
#PersistenceContext(unitName="cinemabookPU")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
// Stores a new city:
#Transactional
public void persist(City city) {
em = getEm();
System.out.println("EM "+em);
em.persist(city);
}
// Retrieves all the citys:
public List<City> getAllCities() {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c", City.class);
return query.getResultList();
}
public City getCityById(Long id) {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c WHERE c.id = :id", City.class);
return query.setParameter("id", id).getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED)
public void deleteAllCities() {
TypedQuery<City> query = em.createQuery(
"DELETE FROM City", City.class);
query.executeUpdate();
}
}
Any help will be greatly appreciated.
I'm getting this error.
org.hibernate.MappingException: Could not determine type for: dom.Whore, at table: Message, for columns: [org.hibernate.mapping.Column(receiver)]
This is the class that is being mapped into the table.
package dom;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Message {
private Whore sender;
private Whore receiver;
private Date date = new Date();
private String messageText;
private Boolean read;
private long id;
public Message(){}
public Message(Whore sender, Whore receiver) {
this.sender = sender;
this.receiver = receiver;
}
public Whore getSender() {
return sender;
}
public void setSender(Whore sender) {
this.sender = sender;
}
public Whore getReceiver() {
return receiver;
}
public void setReceiver(Whore receiver) {
this.receiver = receiver;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public Boolean getRead() {
return read;
}
public void setRead(Boolean read) {
this.read = read;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
This is the class that the type can't be determined for.
package dom;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Whore {
private String username;
private String password;
private String email;
private List<Whore> friends = new ArrayList<Whore>();
private int reputation;
private long id;
private List<Message> messages = new ArrayList<Message>();
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
System.out.println("in set reputation : " + reputation);
this.reputation = this.reputation + reputation;
System.out.println("new repuration : " + this.reputation);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Whore> getFriends() {
return friends;
}
public void setFriends(List<Whore> friends) {
this.friends = friends;
}
public void addFriend(Whore friend) {
getFriends().add(friend);
}
public void removeFriend(Whore friend) {
getFriends().remove(friend);
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public void addMessage(Message message) {
getMessages().add(message);
}
}
I've read in a lot of posts that it's to do with not setting annotations on fields and getters at the same time. But as you can see that's not the cause here. I'm stumped.
<?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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:component-scan base-package="/dom" />
<context:component-scan base-package="/dao" />
<context:component-scan base-package="/controllers" />
<context:component-scan base-package="/services" />
<context:component-scan base-package="/security" />
<tx:annotation-driven />
<mvc:annotation-driven />
<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/culturewhore" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="/" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1000000" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Also I've just tried using #ManyToOne on the sender and receiver getters. But this didn't make any difference.
You haven't mapped the message to whore relationship inside message. Should be:
#ManyToOne
public Whore getSender() {
return sender;
}
#ManyToOne
public Whore getReceiver() {
return receiver;
}
Comment : You shouldn't annotate / use your entity as #Component
You should remove the leading slash ("/") character from your <context:component-scan> tags, and the packagesToScan property of your sessionFactory should be *, not /.
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