Spring Boot Dao和JpaRepositories在@Autowiring时抛出NullPointerException

7dl7o3gd  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(176)

问题:

自动装配SingerDaoImpl和JpaRepositoryImpl Bean会导致null结果。不会抛出Exception,但不会返回Data。使用Thymeleaf视图显示数据

采用的技术:

Spring、JpaRepository、Hibernate、Thymeleaf、H2 Embedded DB(脚本位于resources/SQL文件夹中)、Spring MVC、javax. validation。
我使用localhost:8080/songers通过位于resources/templates/listSingers.html中的thymeleaf列出歌手。

我划掉的东西:

  • 没有使用new运算符声明@Component(或其专门化)Class
  • 所有@Autowired的bean都使用@Component、@Repository或@Service进行注解
  • 二传手已经就位,
  • @ browser已经指向了正确的bean
  • 嵌入式数据库使用位于resources/SQL/test.sql中的数据填充,并通过DBConfig.java类使用EmbeddedDatabaseBuilder.addScript(“SQL/test.sql”)方法添加
  • gradle.build文件版本中的所有依赖项均由gradle管理为最新版本

github页面链接:

https://github.com/NikitaDyagilev/LearningSprinbMVC
注意:我正在使用Amazon Corretto Java 11

DBConfig.java

  1. package com.example.demo.Config;
  2. @Configuration
  3. @ComponentScan
  4. @EnableJpaRepositories(basePackages = {"com.example.demo.JpaRepo"})
  5. @PropertySource("classpath:application.properties")
  6. public class DBconfig {
  7. @Value("${jdbc.driverClassName}")
  8. private String driverClassName;
  9. @Value("${jdbc.username}")
  10. private String username;
  11. @Value("${jdbc.password}")
  12. private String password;
  13. @Value("${jdbc.url}")
  14. private String url;
  15. private Logger logger = LoggerFactory.getLogger(DBconfig.class);
  16. // MySQL DataSource Connection
  17. @Bean
  18. public DataSource dataSourceR(){
  19. try{
  20. SimpleDriverDataSource db =
  21. new SimpleDriverDataSource();
  22. Class<? extends Driver> driver =
  23. (Class<? extends Driver>) Class.forName(driverClassName);
  24. db.setDriverClass(driver);
  25. db.setUsername(username);
  26. db.setPassword(password);
  27. db.setUrl(url);
  28. return db;
  29. } catch (Exception e){
  30. logger.error("Something Went wrong when trying to Create the MySQL DataSource bean");
  31. return null;
  32. }
  33. }
  34. // Embedded DataSource Connection
  35. @Bean
  36. public DataSource dataSourceE(){
  37. try{
  38. EmbeddedDatabaseBuilder db =
  39. new EmbeddedDatabaseBuilder();
  40. db.setType(EmbeddedDatabaseType.H2);
  41. db.addScript("SQL/table.sql");
  42. db.addScript("SQL/test.sql");
  43. return db.build();
  44. } catch (Exception e ){
  45. logger.error("There was an error when trying to create Embeded DataSource: ", e);
  46. return null;
  47. }
  48. }
  49. @Bean
  50. public Properties hibernaProperties(){
  51. Properties prop = new Properties();
  52. prop.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
  53. // prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
  54. prop.put("hibernate.hbm2ddl.auto", "create-drop");
  55. prop.put("hibernate.format_sql", true);
  56. prop.put("hibernate.show_sql", true);
  57. prop.put("hibernate.max_fetch_depth", 3);
  58. prop.put("hibernate.jdbc.batch_size", 10);
  59. prop.put("hibernate.jdbc.fetch_size", 50);
  60. return prop;
  61. }
  62. @Bean
  63. public PlatformTransactionManager transactionManager(){
  64. return new JpaTransactionManager(entityManagerFactory());
  65. }
  66. @Bean
  67. public JpaVendorAdapter jpaVendorAdapter(){
  68. return new HibernateJpaVendorAdapter();
  69. }
  70. @Bean(name ="entityManagerFactory")
  71. public EntityManagerFactory entityManagerFactory(){
  72. LocalContainerEntityManagerFactoryBean emfb =
  73. new LocalContainerEntityManagerFactoryBean();
  74. emfb.setDataSource(dataSourceE());
  75. emfb.setPackagesToScan("com.example.demo.Model");
  76. emfb.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
  77. emfb.setJpaProperties(hibernaProperties());
  78. emfb.setJpaVendorAdapter(jpaVendorAdapter());
  79. emfb.afterPropertiesSet();
  80. return emfb.getObject();
  81. }
  82. }

字符串

控制器类

  1. package com.example.demo.Controllers;
  2. import java.util.List;
  3. @Controller
  4. public class TestController {
  5. private Logger logger = LoggerFactory.getLogger(TestController.class);
  6. private SingerDao dao;
  7. @GetMapping(value = "/hello")
  8. @ResponseBody
  9. public String sayHello(){
  10. return "Hello There";
  11. }
  12. @GetMapping(value ="/homepage")
  13. public String homepageListing(){
  14. return "homepage";
  15. }
  16. @GetMapping(value="/singers")
  17. public String listSingers(Model model){
  18. logger.info("Listing Singers:");
  19. List<Singer> singers = dao.findAll();
  20. String[] names = new String[singers.size()];
  21. for(int i = 0; i < names.length; i++){
  22. names[i] = singers.get(i).getFirstName();
  23. }
  24. model.addAttribute("singersNames", names);
  25. return "ListSingers";
  26. }
  27. @GetMapping(value="/getSinger{id}")
  28. public String getSingerById(Model model,@PathVariable Long id){
  29. model.addAttribute("singer", dao.findById(id).getFirstName());
  30. return "getSinger";
  31. }
  32. @Autowired
  33. public void setDao(SingerDao dao) {
  34. this.dao = dao;
  35. }
  36. }

Jpa仓库

  1. package com.example.demo.JpaRepo;
  2. @Repository("jpaRepositoryImpl")
  3. public class JpaRepositoryImpl implements JpaRepository {
  4. private EntityManagerFactory emf;
  5. @Override
  6. public List<Singer> findAll() {
  7. return emf.createEntityManager()
  8. .createQuery("select s from singer s")
  9. .getResultList();
  10. }
  11. @Override
  12. public Optional<Singer> findById(Long aLong) {
  13. return (Optional<Singer>) emf.createEntityManager().createQuery("select s from singer s where s.id = ?id").
  14. setParameter("id",aLong).getSingleResult();
  15. }
  16. @Autowired
  17. @Qualifier(value = "entityManagerFactory")
  18. public void setEmf(EntityManagerFactory emf) {
  19. this.emf = emf;
  20. }
  21. }

DAO服务

  1. package com.example.demo.DAO;
  2. @Service("singerDaoImpl")
  3. public class SingerDaoImpl implements SingerDao {
  4. private JpaRepository jpaRepo;
  5. @Override
  6. public List<Singer> findAll() {
  7. List<Singer> singers = new ArrayList<>();
  8. jpaRepo.findAll().forEach(item -> singers.add(item));
  9. System.out.println("# Of Singers: "+singers.size());
  10. return singers;
  11. }
  12. @Override
  13. public Singer findById(Long id) {
  14. return null;
  15. }
  16. @Autowired
  17. @Qualifier(value="jpaRepositoryImpl")
  18. public void setJpaRepo(JpaRepository jpaRepo) {
  19. this.jpaRepo = jpaRepo;
  20. }
  21. }

型号

  1. package com.example.demo.Model;
  2. @Table(name="singer")
  3. @Entity(name="singer")
  4. public class Singer implements Serializable{
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. @Column(name="id")
  8. private Long id;
  9. @NotEmpty(message = "{validation.firstname.NotEmpty.message}")
  10. @Size(min=3,max=60,message="{validation.firstname.Size.message}")
  11. @Column(name="first_name")
  12. private String firstName;
  13. @NotEmpty(message = "{validation.lastname.NotEmpty.message}")
  14. @Size(min=3,max=60,message ="{validation.lastname.Size.message")
  15. @Column(name="last_name")
  16. private String lastName;
  17. @Temporal(TemporalType.DATE)
  18. @Column(name="birth_date")
  19. private Date birthDate;
  20. @Column(name="description")
  21. private String description;
  22. @Basic(fetch=FetchType.LAZY)
  23. @Lob
  24. @Column(name="photo")
  25. private byte photo;
  26. public Long getId() {
  27. return id;
  28. }
  29. public void setId(Long id) {
  30. this.id = id;
  31. }
  32. public String getFirstName() {
  33. return firstName;
  34. }
  35. public void setFirstName(String firstName) {
  36. this.firstName = firstName;
  37. }
  38. public String getLastName() {
  39. return lastName;
  40. }
  41. public void setLastName(String lastName) {
  42. this.lastName = lastName;
  43. }
  44. public Date getDate() {
  45. return birthDate;
  46. }
  47. public void setDate(Date date) {
  48. this.birthDate = date;
  49. }
  50. public String getDescription() {
  51. return description;
  52. }
  53. public void setDescription(String description) {
  54. this.description = description;
  55. }
  56. public byte getPhoto() {
  57. return photo;
  58. }
  59. public void setPhoto(byte photo) {
  60. this.photo = photo;
  61. }
  62. @Transient
  63. public String getBirthDateString(){
  64. String birthDateString = "";
  65. if(birthDate != null){
  66. SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
  67. birthDateString = sdf.format(birthDate);
  68. }
  69. return birthDateString;
  70. }
  71. @Override
  72. public String toString() {
  73. return "Singer{" +
  74. "id=" + id +
  75. ", firstName='" + firstName + '\'' +
  76. ", lastName='" + lastName + '\'' +
  77. ", birthDate=" + birthDate +
  78. ", description='" + description + '\'' +
  79. ", photo=" + photo +
  80. '}';
  81. }
  82. }

  • 编辑:* 我添加了logging.level.org.springframework = debug

下面是控制台的相关部分

  1. 2020-05-26 11:26:13.500 INFO 14664 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2935 ms
  2. 2020-05-26 11:26:13.508 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'requestContextFilter'
  3. 2020-05-26 11:26:13.513 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'formContentFilter'
  4. 2020-05-26 11:26:13.513 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration'
  5. 2020-05-26 11:26:13.519 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'characterEncodingFilter'
  6. 2020-05-26 11:26:13.531 DEBUG 14664 --- [ main] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: characterEncodingFilter urls=[/*] order=-2147483648, formContentFilter urls=[/*] order=-9900, requestContextFilter urls=[/*] order=-105
  7. 2020-05-26 11:26:13.532 DEBUG 14664 --- [ main] o.s.b.w.s.ServletContextInitializerBeans : Mapping servlets: dispatcherServlet urls=[/]
  8. 2020-05-26 11:26:13.565 DEBUG 14664 --- [ main] o.s.b.w.s.f.OrderedRequestContextFilter : Filter 'requestContextFilter' configured for use
  9. 2020-05-26 11:26:13.565 DEBUG 14664 --- [ main] s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured for use
  10. 2020-05-26 11:26:13.566 DEBUG 14664 --- [ main] o.s.b.w.s.f.OrderedFormContentFilter : Filter 'formContentFilter' configured for use
  11. 2020-05-26 11:26:13.585 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'demoApplication'
  12. 2020-05-26 11:26:13.586 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'DBconfig'
  13. 2020-05-26 11:26:13.591 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.driverClassName' in PropertySource 'applicationConfig: [classpath:/application.properties]' with value of type String
  14. 2020-05-26 11:26:13.591 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.driverClassName' in PropertySource 'environmentProperties' with value of type String
  15. 2020-05-26 11:26:13.593 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.username' in PropertySource 'configurationProperties' with value of type String
  16. 2020-05-26 11:26:13.593 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.username' in PropertySource 'environmentProperties' with value of type String
  17. 2020-05-26 11:26:13.595 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.password' in PropertySource 'configurationProperties' with value of type String
  18. 2020-05-26 11:26:13.595 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.password' in PropertySource 'environmentProperties' with value of type String
  19. 2020-05-26 11:26:13.595 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.url' in PropertySource 'configurationProperties' with value of type String
  20. 2020-05-26 11:26:13.595 DEBUG 14664 --- [ main] o.s.c.e.PropertySourcesPropertyResolver : Found key 'jdbc.url' in PropertySource 'environmentProperties' with value of type String
  21. 2020-05-26 11:26:13.599 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'testController'
  22. 2020-05-26 11:26:13.607 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'singerDaoImpl'
  23. 2020-05-26 11:26:13.614 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'jpaRepositoryImpl'
  24. 2020-05-26 11:26:13.621 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'entityManagerFactory'
  25. 2020-05-26 11:26:13.673 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'dataSourceE'
  26. 2020-05-26 11:26:13.702 INFO 14664 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
  27. 2020-05-26 11:26:13.712 DEBUG 14664 --- [ main] o.s.jdbc.datasource.DataSourceUtils : Fetching JDBC Connection from DataSource
  28. 2020-05-26 11:26:13.713 DEBUG 14664 --- [ main] o.s.j.datasource.SimpleDriverDataSource : Creating new JDBC Driver Connection to [jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]
  29. 2020-05-26 11:26:13.971 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [SQL/table.sql]
  30. 2020-05-26 11:26:14.002 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 0 returned as update count for SQL: CREATE TABLE SINGER ( ID INT NOT NULL AUTO_INCREMENT, FIRST_NAME VARCHAR(60), LAST_NAME VARCHAR(40), BIRTH_DATE DATE, DESCRIPTION VARCHAR(2000) NULL, PHOTO BLOB NULL, VERSION INT NOT NULL DEFAULT 0, UNIQUE UQ_SINGER_1 (FIRST_NAME, LAST_NAME), PRIMARY KEY (ID) )
  31. 2020-05-26 11:26:14.002 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [SQL/table.sql] in 30 ms.
  32. 2020-05-26 11:26:14.002 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [SQL/test.sql]
  33. 2020-05-26 11:26:14.014 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('John', 'Mayer', '1977-10-16')
  34. 2020-05-26 11:26:14.014 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Eric', 'Clampton', '1954-03-20')
  35. 2020-05-26 11:26:14.017 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('John', 'Butler', '1975-04-01')
  36. 2020-05-26 11:26:14.017 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('B.B' , 'King', '1925-09-16')
  37. 2020-05-26 11:26:14.019 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Jimi', 'Hendrix', '1942-11-27')
  38. 2020-05-26 11:26:14.021 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Eddie', 'Van Halen','1955-01-26')
  39. 2020-05-26 11:26:14.022 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Saul Slash', 'Hudson', '1965-07-23')
  40. 2020-05-26 11:26:14.023 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Stevie', 'Ray Vaughan','1954-10-03')
  41. 2020-05-26 11:26:14.023 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('David', 'Gilmour','1946-03-06')
  42. 2020-05-26 11:26:14.026 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Kirk','Hammett','1992-11-18')
  43. 2020-05-26 11:26:14.027 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Angus','Young','1955-03-31')
  44. 2020-05-26 11:26:14.028 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Dimebad','Darrell','1966-08-20')
  45. 2020-05-26 11:26:14.029 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Carlos','Santana','1947-07-20')
  46. 2020-05-26 11:26:14.030 DEBUG 14664 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [SQL/test.sql] in 28 ms.
  47. 2020-05-26 11:26:14.039 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker'
  48. 2020-05-26 11:26:14.043 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties'
  49. 2020-05-26 11:26:14.064 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Autowiring by type from bean name 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker' via constructor to bean named 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties'
  50. 2020-05-26 11:26:14.065 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Autowiring by type from bean name 'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker' via constructor to bean named 'org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@456d6c1e'
  51. 2020-05-26 11:26:14.227 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'hibernaProperties'
  52. 2020-05-26 11:26:14.230 DEBUG 14664 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'jpaVendorAdapter'
  53. 2020-05-26 11:26:14.245 DEBUG 14664 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
  54. 2020-05-26 11:26:14.294 INFO 14664 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
  55. 2020-05-26 11:26:14.412 INFO 14664 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
  56. 2020-05-26 11:26:14.685 INFO 14664 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
  57. 2020-05-26 11:26:14.906 DEBUG 14664 --- [ main] o.s.j.datasource.SimpleDriverDataSource : Creating new JDBC Driver Connection to [jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]
  58. 2020-05-26 11:26:14.940 INFO 14664 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
  59. Hibernate:

**SQL查询 *

  1. drop table if exists singer CASCADE
  2. 2020-05-26 11:26:16.139 DEBUG 14664 --- [ main] o.s.j.datasource.SimpleDriverDataSource : Creating new JDBC Driver Connection to [jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]
  3. Hibernate:
  4. create table singer (
  5. id bigint generated by default as identity,
  6. birth_date date,
  7. description varchar(255),
  8. first_name varchar(255),
  9. last_name varchar(255),
  10. photo blob,
  11. primary key (id)
  12. )


我找到了一个表达方式

  1. javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
  2. at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291) ~[validation-api-2.0.1.Final.jar:na]
  3. at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:257) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  4. at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  5. at org.springframework.boot.autoconfigure.validation.ValidatorAdapter.afterPropertiesSet(ValidatorAdapter.java:83) ~[spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  6. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  7. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  8. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  9. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  10. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  11. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  12. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  13. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  14. at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  15. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1306) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  16. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  17. at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  18. at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  19. at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  20. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  21. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  22. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  23. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  24. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  25. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  26. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  27. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  28. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:895) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  29. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  30. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
  31. at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  32. at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  33. at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  34. at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  35. at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  36. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  37. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
  38. at com.example.demo.DemoApplication.main(DemoApplication.java:13) ~[main/:na]

3pvhb19x

3pvhb19x1#

你几乎就在那里了。事实上,你的数据库 * 是 * 空的。为什么?因为你的DBConfig类. prop.put("hibernate.hbm2ddl.auto", "create-drop");中的这一行(链接到该属性的文档)。你可以安全地删除它或将该属性设置为一个对你有意义的值。
您还需要设置照片属性(以及它的getter和setter)转换为Byte(这种类型也称为Wrapper Class)而不是byte,因为字节是一个不能设置为null的原始值。然而,在您的DB脚本中,您允许photo为null,因此,如果您不更改此代码,当你试图把DB列Map到Java对象时,它会导致一个异常。一旦你完成了这两件事,歌手的列表就会显示在浏览器中。
现在,一些最后的提示,因为你对编程有点陌生:
我已经检查了你的repo,你正在做很多你不需要做的工作和配置,因为你使用的是Sping Boot 和Sping Boot Data Jpa,而不仅仅是Spring。我建议你先开始全面使用Sping Boot ,然后学习Spring以及如何根据你的需求定制它,如果您需要单独使用Spring来满足您的需求,请使用Use this link作为网关来了解有关Sping Boot 和Sping Boot Data Jpa的更多信息。

相关问题