0

I'm trying to write my first program with spring and hibernate I got such configuration classes:

package com.my.jdbcTest.config;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

@Configuration
@ComponentScan(basePackages = "com.my.jdbcTest")
@PropertySource("classpath:application.properties")
@EnableTransactionManagement
public class AppConfig {

    //org.postgresql.Driver

    @Value("${db.driver}")
    private String DB_DRIVER;

    @Value("${db.password}")
    private String DB_PASSWORD;

    @Value("${db.url}")
    private String DB_URL;

    @Value("${db.username}")
    private String DB_USERNAME;

    @Value("${hibernate.dialect}")
    private String HIBERNATE_DIALECT;

    @Value("${hibernate.show_sql}")
    private String HIBERNATE_SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HIBERNATE_HBM2DDL_AUTO;


    @Bean
    public DataSource dataSource() {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(DB_DRIVER);
            dataSource.setUrl(DB_URL);
            dataSource.setUsername(DB_USERNAME);
            dataSource.setPassword(DB_PASSWORD);
            return dataSource;
        }
        catch (Exception e){
            return null;
        }
    }

    private Properties hibernateProperties (){
        Properties hibernateProp = new Properties();
        hibernateProp.put("hibernate.dialect",
                "org.hibernate.dialect.PostgreSQLDialect");
        hibernateProp.put("hibernate.format_sql", true);
        //hibernateProp.put("hibernate.hbm2ddl.auto");
        hibernateProp.put("hibernate.use_sql_comments", true);
        hibernateProp.put("hibernate.show_sql", true);
        hibernateProp.put("hibernate.max_fetch_depth", 3);
        hibernateProp.put ( "hibernate.jdbc.batch_size", 10);
        hibernateProp.put ("hibernate.jdbc.fetch_size", 50);
        return hibernateProp;
    }
    

    @Bean
    public SessionFactory sessionFactory() throws IOException {
        LocalSessionFactoryBean sessionFactoryBean  = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setPackagesToScan("com/my/jdbcTest/Enties");
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.afterPropertiesSet();
        return sessionFactoryBean.getObject();

    }

    @Bean
    public PlatformTransactionManager transactionManager() throws IOException{
        return new HibernateTransactionManager(sessionFactory());
    }

}

DAO class:

package com.my.jdbcTest.dao;

import com.my.jdbcTest.Enties.testTable;

import java.util.List;

public interface simpleDao {
    List<testTable> findAll();
}

package com.my.jdbcTest.dao;

import com.my.jdbcTest.Enties.testTable;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Repository("simpleDaoImpl")
public class simpleDaoImpl implements simpleDao{

    private SessionFactory sessionFactory;

    @Resource(name = "sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @Transactional
    public List<testTable> findAll() {
        return sessionFactory.getCurrentSession().createQuery("from testTable t").list();
    }
}

and Entity class:

package com.my.jdbcTest.Enties;
import javax.persistence.*;
;

@Entity
@Table(name="testTable")

public class testTable {

    private Long id;
    private Integer salary;
    private String name;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    public Long getId(Long id) {
        return id;
    }

    @Column(name = "salary")
    public Integer getSalary(){
        return salary;
    }

    @Column(name = "name")
    public String getName(){
        return name;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

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

    public String toString(){
        return "id: " + id +" salary: " + salary + " name: " + name;
    }
}

But when running main:

package com.my.jdbcTest;

import com.my.jdbcTest.Enties.testTable;
import com.my.jdbcTest.config.AppConfig;
import com.my.jdbcTest.dao.simpleDaoImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import java.util.List;


public class HibernateMain {
    public static void main(String[] args) {
        GenericApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

        //simpleDaoImpl dao = ctx.getBean(simpleDaoImpl.class);
       //listToString(dao.findAll());
    }
    private static void listToString(List<testTable> lst){
        lst.stream().forEach(System.out::println);
    }
}

I get an error java.lang.NoClassDefFoundError :

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/core/metrics/ApplicationStartup
    at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:229)
    at org.springframework.context.support.GenericApplicationContext.<init>(GenericApplicationContext.java:112)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:67)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:91)
    at com.my.jdbcTest.HibernateMain.main(HibernateMain.java:13)
Caused by: java.lang.ClassNotFoundException: org.springframework.core.metrics.ApplicationStartup
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)

I saw that this is a fairly common mistake, I looked at the articles, but I never found a solution ,if someone can help me figure it out, I would be happy!

my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>sJDBCtest</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>



        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>


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


        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.5.Final</version>
        </dependency>




        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.23</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>


        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>

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



    </dependencies>



    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

</project>

btw : Fixing spring versions-jdbc, core ,arm to 5.2.16.RELEASE give an error org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [C:\Users\Loken\IdeaProjects\sJDBCtest\target\classes\com\my\jdbcTest\Enties\testTable.class];

Omegon
  • 387
  • 2
  • 10
  • Does this answer your question? [How can I solve "java.lang.NoClassDefFoundError"?](https://stackoverflow.com/questions/17973970/how-can-i-solve-java-lang-noclassdeffounderror) – vaibhavsahu Sep 13 '21 at 18:55
  • @vaibhavsahu I saw this article,but I didn't find a solution here, since it's just ```AppConfig app = new AppConfig()``` works – Omegon Sep 13 '21 at 18:58
  • I think this url will surely help you. https://stackoverflow.com/questions/65046056/spring-boot-classnotfoundexception-org-springframework-core-metrics-applications – vaibhavsahu Sep 13 '21 at 19:00
  • @vaibhavsahu I don't think there is a solution to the rejection of spring boot ,and I don't use it – Omegon Sep 13 '21 at 19:02
  • what version of Spring Framework you are using? – vaibhavsahu Sep 13 '21 at 19:04
  • @vaibhavsahu 5.2.16.RELEASE – Omegon Sep 13 '21 at 19:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/237064/discussion-between-vaibhavsahu-and-omegon). – vaibhavsahu Sep 13 '21 at 19:11

1 Answers1

-1

You have messed up the dependencies' versions. You should conform to 5.2.16.RELEASE version for your spring related dependencies. So change the versions of the following dependencies to 5.2.16.RELEASE as:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.16.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.16.RELEASE</version>
    </dependency>
pleft
  • 7,567
  • 2
  • 21
  • 45
  • Thank you ,but now instead of that error appeared ```Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [C:\Users\Loken\IdeaProjects\sJDBCtest\target\classes\com\my\jdbcTest\Enties\testTable.class]; ``` Do you know if it is also due to an incorrect version of some dependency? – Omegon Sep 13 '21 at 19:09
  • @Omegon Well I see one error in your `testTable` class, its the getter of Id, it shouldn't have method parameter (`Long id`), its a getter not setter, it should be: `public Long getId()` and not `public Long getId(Long id)`. As for the error `Failed to read candidate component class` I would suggest you to do a clean build of your project but I don't know what it might be. In my tries to reproduce your project I didn't encounter such error. – pleft Sep 14 '21 at 06:28