0

I'm in the process of learning java spring. Now I am trying to retrieve data from the database. I rely on this tutorial https://dzone.com/articles/spring-boot-and-spring-jdbc-with-h2

When I try to get data from the database via ID I get this error:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:542)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:782)
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:763)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:318)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
    at com.exam.kino.KinoApplication.main(KinoApplication.java:25)
    ... 6 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.exam.kino.database.Seans]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.exam.kino.database.Seans.<init>()
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:129)
    at org.springframework.jdbc.core.BeanPropertyRowMapper.mapRow(BeanPropertyRowMapper.java:285)
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:94)
    at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:61)
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:678)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:616)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:668)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:699)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:711)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:782)
    at com.exam.kino.repository.SeansRepository.findById(SeansRepository.java:26)
    at com.exam.kino.repository.SeansRepository$$FastClassBySpringCGLIB$$a208ec27.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.exam.kino.repository.SeansRepository$$EnhancerBySpringCGLIB$$b326407c.findById(<generated>)
    at com.exam.kino.KinoApplication.run(KinoApplication.java:31)
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779)
    ... 11 more
Caused by: java.lang.NoSuchMethodException: com.exam.kino.database.Seans.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:122)
    ... 31 more

This is my database (schema.sql and import.sql):

create table seans
(
   id integer not null AUTO_INCREMENT,
   title varchar(255) not null,
   datetime TIMESTAMP not null,
   primary key(id)
);
INSERT INTO seans (id, title, DATETIME) VALUES (1,'Captain America',parsedatetime('30-06-2016 08:00', 'dd-MM-yyyy hh:mm'));
INSERT INTO seans (id, title, DATETIME) VALUES (2,'Antman',parsedatetime('30-06-2016 10:00', 'dd-MM-yyyy hh:mm'));
INSERT INTO seans (id, title, DATETIME) VALUES (3,'Ironman',parsedatetime('30-06-2016 12:00', 'dd-MM-yyyy hh:mm'));

Seans class (I used Lombok and annotation @Data here):

package com.exam.kino.database;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import lombok.Data;

@Data
@Table(name="seans")
@Entity
public class Seans {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;
    @Column(name = "title")
    private String title;
    @Column(name = "datetime")
    private Date datetime;

    public Seans(int id, String title, Date datetime) {
        super();
        this.id = id;
        this.title = title;
        this.datetime = datetime;
    }
}

My repository class:

package com.exam.kino.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.exam.kino.database.Seans;

import antlr.collections.List;

@Repository
public class SeansRepository
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    public Seans findById(long id) {
        return jdbcTemplate.queryForObject("select * from seans where id=? ", new Object[] {
                id
        },new BeanPropertyRowMapper<Seans>(Seans.class));
    }
}

And last my main class with method call:

package com.exam.kino;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.exam.kino.repository.SeansRepository;

@SpringBootApplication
public class KinoApplication implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SeansRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(KinoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("Seans id 1 - > {}", repository.findById(1));
    }
}

Somebody had this type of error and know how repair this?

2
  • 1
    The message tells you what the problem is: Failed to instantiate [com.exam.kino.database.Seans]: No default constructor found. JPA entities must have a no-argument constructor. Commented Aug 11, 2019 at 15:57
  • Note however that you're using JPA annotations, but using a repository that uses JDBC, and not JPA. That doesn't make much sense. But in any case, BeanPropertyRowMapper also needs a no-arg constructor. Commented Aug 11, 2019 at 16:13

3 Answers 3

1

You can have the no-arg-constructor created by Lombok by adding one more annotation:

@Data
@NoArgsConstructor
@Table(name="seans")
@Entity
public class Seans {
  // ...
}

}

and do not declare your own constructor; @NoArgsConstructor and @RequiredArgsConstructor (which is implicit by using @Data) will only work if you do not have custom constructors.

Sign up to request clarification or add additional context in comments.

Comments

1

From your error logs,

Caused by: java.lang.NoSuchMethodException: com.exam.kino.database.Seans.<init>()

It is looking for a default constructor. Try defining a default constructor in Seans class.


Recommendation for getting data with spring boot

You can extend CRUDRepository or JPARepository to your Repository class to fetch data. Repository will construct the table and query itself.

You can follow this guide https://spring.io/guides/gs/accessing-data-jpa/

Comments

1

As mentioned above:

  1. More attentively read stack trace messages - there you can find information about your error.
  2. You need to read JPA specification (https://download.oracle.com/otndocs/jcp/persistence-2_2-mrel-eval-spec/index.html), here you will find much information.

It is your case: "The entity class must have a no-arg constructor. The entity class may have other constructors as well. The no-arg constructor must be public or protected"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.