通过spring-boot [JAVA]

时间:2019-08-11 15:53:04

标签: java spring-boot h2

我正在学习Java Spring。现在,我正在尝试从数据库中检索数据。我依靠本教程https://dzone.com/articles/spring-boot-and-spring-jdbc-with-h2

当我尝试通过ID从数据库获取数据时,出现此错误:

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

这是我的数据库(schema.sql和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类(我在这里使用了Lombok和注解@Data)

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

我的存储库类:

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

最后一个方法调用我的主类:

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

有人有这种错误,知道如何修复吗?

3 个答案:

答案 0 :(得分:1)

从您的错误日志中,

ValueError: Conflicting metadata name a, need distinguishing prefix

它正在寻找默认的构造函数。尝试在Seans类中定义默认构造函数。


建议通过Spring Boot获取数据

您可以将CRUDRepository或JPARepository扩展到您的Repository类以获取数据。存储库将构造表并查询自身。

您可以按照本指南进行操作 https://spring.io/guides/gs/accessing-data-jpa/

答案 1 :(得分:1)

您可以通过添加另一个注释来使Lombok创建no-arg-constructor:

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

}

不要声明自己的构造函数; @NoArgsConstructor@RequiredArgsConstructor(使用@Data隐含)仅在没有自定义构造函数的情况下起作用。

答案 2 :(得分:1)

如上所述:

  1. 更专心地阅读堆栈跟踪消息-您可以在其中找到有关错误的信息。
  2. 您需要阅读JPA规范(https://download.oracle.com/otndocs/jcp/persistence-2_2-mrel-eval-spec/index.html),在这里您会找到很多信息。

这是您的情况: “实体类必须具有no-arg构造函数。实体类也可以具有其他构造函数。no-arg构造函数必须是公共或受保护的”