0

I am new to Spring so as to Hibernate frameworks. The task is to create a project with both front and back ends, but for now I would like to focus on DB connection.

I have MySQL database on localhost within my MySQL server. There is a simple application which needs to create clients, orders and search for them in the DB, so the task is trivial. Yet, I encounter the following 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"/>    

I tried some manipulations, read many similar issues here, which led me to other exceptions much like this.

My config.xml file is:

<?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>

And here is the project structure:

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

And here is my 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>

And the classes: Client

 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

}   
}

And lastly my 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>

I modified it several times, adding some additional info. What I currently want is to check, whether it works, so in the Main class I wrote primitive code to store info to database and see whether it actually stored, so I could move on:

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);
    }
   }

It now gives me mappingexception Any ideas, why? And, by the way who is "AnnotationConfiguration instance" and where it supposed to be?

St.running
  • 175
  • 1
  • 3
  • 14

1 Answers1

0

Normal hibernate.cfg.xml uses Configuration class for building Sessionfactory object

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

You need to use AnnotationConfiguration for the same.

In your above example you have specified classes in sessionFactory bean as

<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>

Wrong thing you did here is you added DAO classes also. AnnotatedClasses should be domain classes. You can remove them and keep only Client and Order in that.

Secondly you have also provided hibernate.cfg.xml file. Hence you can remove that as you are using annotated classes.

Hence final code may look like this:

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

And removing hibernate.cfg.xml

Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
  • Thank you for the answer! Yet there appears to be another exception: "...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 java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist" and after removig "" from my config, I another one: – St.running Oct 17 '14 at 14:08
  • "java.lang.NoSuchMethodError: org.hibernate.cfg.Configuration.addAnnotatedClass(Ljava/lang/Class;)Lorg/hibernate/cfg/Configuration;" like this.. – St.running Oct 17 '14 at 14:08
  • I updated hibernate version to 3.6.0.Final, according to http://stackoverflow.com/questions/14958708/java-lang-nosuchmethoderror-org-hibernate-cfg-configuration-addannotatedclass, but again it returned me an error "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 java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvider" – St.running Oct 17 '14 at 14:55
  • Try changing your `hibernate-commons-annotations` version to the latest version: `4.0.5.Final`. Also, the latest version of Hibernate is `4.3.6.Final` in case you wanted to update. – LucasP Oct 17 '14 at 15:42
  • Tried, but it gives "missing artifact javax.transaction:jta:jar:1.0.1B". Currently I downloaded the jar, but it do not want to get installed in Maver Repository folder.. – St.running Oct 17 '14 at 18:55
  • Well, after some manipulation it seems solved. Yet there appears another problem with annotation: my Client class has got a ClientDAOInterface field, which I suppose to annotate, but I cant. I'll try to figure it out – St.running Oct 17 '14 at 20:04
  • I updated the remaining problem here: http://stackoverflow.com/questions/26433631/spring-hibernate-maven-nosuchbeandefinitionexception – St.running Oct 17 '14 at 21:24