我整天都在苦苦挣扎,但尚未找到解决方案。
我有一个简单的实体映射到数据库表:
@Entity
@Table(name = "PERSON")
public class Person implements Serializable {
// Attributes.
@Id
@Column(name = "ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name = "NAME", nullable = false, length=50)
private String name;
@Column(name = "ADDRESS", nullable = false, length=100)
private String address;
@Column(name = "TELEPHONE", nullable = false, length=10)
private String telephone;
@Column(name = "EMAIL", nullable = false, length=50)
private String email;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="PERSON_ID")
private List<Book> books;
// Constructors.
public Person() {
this.id = 0;
this.name = ("");
this.address = ("");
this.telephone = ("");
this.email = ("");
this.books = null;
}
此实体由Spring控制器管理,方法如下:
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String post(@ModelAttribute("person") Person person,
BindingResult bindingResult,
SessionStatus sessionStatus,
Model model /* ,
HttpSession session */) throws DAOException {
logger.info(PersonController.class.getName() + ".post() method called.");
personValidator.validate(person, bindingResult);
if (bindingResult.hasErrors()) {
return "register";
}
else {
// Write Person to database.
personService.insert(person);
// Set view.
sessionStatus.setComplete();
return "options";
}
}
服务类是:
@Service("personService")
@Transactional
public class PersonService {
@Autowired
PersonDAO personDAO;
public void insert(Person person) throws DAOException {
personDAO.insert(person);
}
DAO如下:
@Repository("PersonDAO")
public class PersonDAOImpl implements PersonDAO {
@Autowired
private SessionFactory sessionFactory;
static final Logger logger = Logger.getLogger(PersonDAOImpl.class.getName());
@Override
public void insert(Person person) throws DAOException {
logger.info(PersonDAOImpl.class.getName() + ".insert() method called.");
Session session = sessionFactory.openSession();
Transaction transaction = session.getTransaction();
try {
transaction.begin();
session.save(person);
transaction.commit();
}
catch(RuntimeException e) {
transaction.rollback();
throw new DAOException(e);
}
finally {
session.close();
}
}
当然,我的Spring servlet将所有内容绑定在一起:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class ">thread</prop>
<!-- What to do with the database schema. -->
<prop key="hbm2ddl.auto">validate</prop>
<!-- validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session. -->
</props>
</property>
</bean>
为什么我收到消息:
org.hibernate.MappingException: Unknown entity: library.model.Person
如果我尝试这样的话:
<property name="packagesToScan" value="library.model" />
<property name="annotatedClasses">
<list>
<value>library.model.Person</value>
</list>
</property>
目前我正在接受:
2014年6月15日下午10:50:58 org.apache.catalina.core.ApplicationContext log INFO:初始化Spring root WebApplicationContext 2014年6月15日 10:51:02 PM org.apache.catalina.core.StandardContext listenerStart SEVERE:将上下文初始化事件发送给侦听器的异常 类的实例 org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException:错误 用名称&#39; personController创建bean&#39 ;:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 autowire字段:library.services.PersonService library.controller.PersonController.personService;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 使用名称&#39; personService创建bean&#39 ;:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 autowire字段:library.dao.PersonDAOImpl library.services.PersonService.personDAO;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建名为&#39; PersonDAOImpl&#39;:注入自动装配的bean 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 autowire字段:org.hibernate.SessionFactory library.dao.PersonDAOImpl.sessionFactory;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建名为&#39; sessionFactory&#39;的bean在ServletContext中定义 resource [/WEB-INF/library-servlet.xml]:调用init方法 失败;嵌套异常是java.lang.NoClassDefFoundError: javax / persistence / NamedStoredProcedureQuery at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) 在 org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:304) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700) 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) 在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) 在 org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) 在 org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) 在 org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) 在 org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681) 在 org.apache.catalina.core.StandardContext $ 1.call(StandardContext.java:5184) 在 org.apache.catalina.core.StandardContext $ 1.call(StandardContext.java:5179) 在java.util.concurrent.FutureTask.run(FutureTask.java:266)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 在 java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617) 在java.lang.Thread.run(Thread.java:744)
答案 0 :(得分:3)
尝试更换:
<property name="annotatedClasses">
<list>
<value>library.model.Person</value>
</list>
</property>
使用:
<property name="packagesToScan">
<list>
<value>library.model</value>
</list>
</property>
在你的sessionFactory属性中。
如果您收到错误消息,说明该物业&#34; packagesToScan&#34;找不到,那么你应该将spring-orm库添加到你的项目中。如果你正在使用maven,那么你可以添加:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>YOUR SPRING VERSION HERE</version>
</dependency>