Spring + Hibernate + Maven org.hibernate.MappingException:需要AnnotationConfiguration实例

时间:2014-10-17 12:09:25

标签: java mysql spring hibernate maven

我是Spring的新手,以便Hibernate框架。任务是创建一个前端和后端的项目,但是现在我想专注于数据库连接。

我的MySQL服务器中的localhost上有MySQL数据库。有一个简单的应用程序需要在DB中创建客户端,订单和搜索它们,因此任务很简单。然而,我遇到了以下的ecxeption:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory ee.st.running.dao.ClientDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="ee.st.running.model.Client"/>    

我尝试了一些操作,在这里阅读了许多类似的问题,这导致了其他类似的异常。

我的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:p="http://www.springframework.org/schema/p"
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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
  <context:component-scan base-package=".*" />
 <tx:annotation-driven/>
  <context:annotation-config />
  <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/sqlconnection" />
    <property name="username" value="admin" />
    <property name="password" value="root" />
  </bean>


 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
     <property name="annotatedClasses">
            <list>
                <value>ee.st.running.model.Client</value>
                <value>ee.st.running.dao.ClientDAOImpl</value>
                <value>ee.st.running.model.Order</value>
                <value>ee.st.running.dao.OrderDAOImpl</value>
            </list>
        </property>
        <property name="configLocation">
    <value>classpath:hibernate.cfg.xml</value>
</property>
    <property name="hibernateProperties">
      <props>
        <prop
         key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>

    </property>
  </bean>

  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory">
  </bean>

  <bean id = "client" class = "ee.st.running.model.Client">
  <property name="clientDAO" ref = "ClientDAO"></property>
  </bean>

  <bean id = "clientDAO" class = "ee.st.running.dao.ClientDAOImpl">
  <property name="sessionFactory" ref = "sessionFactory"></property>
  </bean>


  <bean id = "order" class = "ee.st.running.model.Order">
  <property name="orderDAO" ref = "OrderDAO"></property>
  </bean>

      <bean id = "orderDAO" class = "ee.st.running.dao.OrderDAOImpl">
  <property name="sessionFactory" ref = "sessionFactory"></property>
  </bean>

  </beans>

这是项目结构:

enter image description here enter image description here enter image description here

这是我的pom.xml:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ee.st.running.aktorstask</groupId>
  <artifactId>aktorstask</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <dependencies>
      <dependency>
            <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.3.2.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.3.1.GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>3.3.0.ga</version>
    </dependency>


    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency> 

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>4.0.6.RELEASE</version>
   </dependency>

    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>4.0.6.RELEASE</version>
    </dependency>

    <dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>

    <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>


    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>
<properties>
    <spring.version>3.2.3.RELEASE</spring.version>
</properties>  
</project>

课程: 客户端

 package ee.st.running.model;

//import java.util.List;
//import java.util.Set;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
//import javax.persistence.OneToMany;
  import javax.persistence.Table;
  import ee.st.running.dao.ClientDAOInterface;
  import ee.st.running.dao.ClientDAOImpl;

  @Entity
  @Table(name = "client")
  public class Client implements ClientInterface {


private Order o;
ClientDAOInterface ClientDAOInterface;

@Id
@GeneratedValue
 private int id;


@Column (name = "name")
 private String name;
@Column (name = "surename")
 private String surename;
 @Column (name = "address")
private String address;
 @Column (name = "phone_number")
private long phoneNumber;
 @Column (name = "id_code")
private long idCode;

//@OneToMany(mappedBy = «client», fetch = FetchType.LAZY)


public void makeorder() {
    o.newOrder();
}

// getters nd setters

public Order getO() {
    return o;
}


public void setO(Order o) {
    this.o = o;
}


public String getName() {
    return name;
}


public void setName(String name) {
    this.name = name;
}


public String getSurename() {
    return surename;
}


public void setSurename(String surename) {
    this.surename = surename;
}


public String getAddress() {
    return address;
}


public void setAddress(String address) {
    this.address = address;
}


public long getPhoneNumber() {
    return phoneNumber;
}


public void setPhoneNumber(int phoneNumber) {
    this.phoneNumber = phoneNumber;
}


public long getIdCode() {
    return idCode;
}


public void setIdCode(int idCode) {
    this.idCode = idCode;
}


// ctor 

public Client ()
{

}



public void setClientInfDAO (ClientDAOInterface ClientDAOInterface) 
{
    this.ClientDAOInterface = ClientDAOInterface;
}


public void save(Client client) {

    ClientDAOInterface.save(client);
}


public void update(Client client) {

    ClientDAOInterface.update(client);
}


public void remove(Client client) {

    ClientDAOInterface.remove(client);
}
}

ClientInterface:

package ee.st.running.model;

public interface ClientInterface {
public void makeorder ();
public void save(Client client);
public void update (Client client);
public void remove (Client client);

}

ClientDAOInterface:

package ee.st.running.dao;

import java.util.List;
import ee.st.running.model.Client;
public interface ClientDAOInterface {

public void removeClient (long id);
public List<Client> listClient();
public void save (Client client);
public void update (Client client);
public void remove (Client client);
}

ClientDAOImpl:

 package ee.st.running.dao;

 import java.util.List;
 import org.hibernate.SessionFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 import org.springframework.stereotype.Repository;
 import ee.st.running.model.Client;

@Repository
public class ClientDAOImpl extends HibernateDaoSupport implements ClientDAOInterface {


@Autowired
private SessionFactory sessionFactory;


public void AddClient(Client client) {
    sessionFactory.getCurrentSession().save(client);

}

public void removeClient(long id) {


    Client client = (Client) sessionFactory.getCurrentSession().load(Client.class, id);
    if (null != client) {
        sessionFactory.getCurrentSession().delete(client);
    }

}

@SuppressWarnings("unchecked")
public List<Client> listClient() {

    return sessionFactory.getCurrentSession().createQuery("from Client").list();
}

public void save(Client client) {
    sessionFactory.getCurrentSession().save(client);

}

public void update(Client client) {
    // TODO Auto-generated method stub

}

public void remove(Client client) {
    // TODO Auto-generated method stub

}   
}

最后我的hibernate.cfg:

 <?xml version='1.0' encoding='utf-8'?>
 <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <mapping class="ee.st.running.model.Client" />
    <mapping class="ee.st.running.model.Order" />
</session-factory>
</hibernate-configuration>

我修改了几次,添加了一些额外的信息。我目前想要的是检查它是否有效,所以在Main类中我编写了原始代码来将信息存储到数据库并查看它是否实际存储,所以我可以继续:

package ee.st.running.aktorstask;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ee.st.running.dao.*;
import ee.st.running.model.*;
public class Main {

public static void main(String[] args) {

    ApplicationContext appContext = new ClassPathXmlApplicationContext ("./config.xml");

    Client clientx = (Client) appContext.getBean("client");
    Client client = new Client ();
    client.setName("Vasilij");
    client.setIdCode(389844455);
    client.setAddress("Pae 485 54 Tartu");
    client.setSurename("B");
    //client.makeorder();

    clientx.save(client);
    }
   }

它现在给了我mappingexception 有什么想法,为什么?顺便说一下,谁是“AnnotationConfiguration实例”以及它应该在哪里?

1 个答案:

答案 0 :(得分:0)

正常的hibernate.cfg.xml使用Configuration类来构建Sessionfactory对象

  return new Configuration().configure().buildSessionFactory();

您需要使用AnnotationConfiguration。

在上面的示例中,您已将sessionFactory bean中的类指定为

<property name="annotatedClasses">
            <list>
                <value>ee.st.running.model.Client</value>
                <value>ee.st.running.dao.ClientDAOImpl</value>
                <value>ee.st.running.model.Order</value>
                <value>ee.st.running.dao.OrderDAOImpl</value>
            </list>
        </property>

你在这里做的错误是你还添加了DAO课程。 AnnotatedClasses应该是域类。 您可以删除它们并仅保留客户端和订单。

其次,您还提供了hibernate.cfg.xml文件。因此,您可以在使用带注释的类时删除它。

因此最终代码可能如下所示:

<property name="annotatedClasses">
            <list>
                <value>ee.st.running.model.Client</value>
                <value>ee.st.running.model.Order</value>
            </list>
        </property>

删除hibernate.cfg.xml