packagesToS无法使用AnnotationSessionFactoryBean

时间:2015-09-16 19:04:34

标签: java spring hibernate

我是春天新手。我试图将spring与hibernate整合在一起 我无法使用packagesToScan获取我的实体类Employee,在此之前我尝试了annnotatedClasses以及也没有工作,我也尝试使用packagesToScan的通配符(com.sfb。**。*)但是没有运气。仅供参考我使用的是javax.persistence.Entity,因此也不是导入问题。下面是我的spring.xml文件和其他以及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;
    }

}

异常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)

请提前帮助我

NullpointerException的完整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.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

1 个答案:

答案 0 :(得分:0)

这是一个错误(Employee.java):

@OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =      
                  CascadeType.ALL)
private Address address;

mappedBy属性应仅用于反向关联大小,因此在此处不适用。

我猜你正在尝试构建简单的单向关联。

它应该类似于:

@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几乎完全相同的例子。