【问题标题】:Spring Boot and DaoSpring Boot 和 Dao
【发布时间】:2015-06-19 23:19:07
【问题描述】:

我在 Github 上上传了一个公共项目:

https://github.com/sotish/SpringMVC11.git

我的模型类是:

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

    import org.springframework.boot.orm.jpa.EntityScan;
    import org.springframework.data.annotation.Id;

    @EntityScan
    @Entity
    @Table(name = "Student")
    public class Student {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;

     @Column(nullable= false, unique=true)
        private String firstName;

     @Column(nullable= false, unique=true)
        private String lastName;

     @Column(nullable= false, unique=true)
        private int age;

     @Column(nullable= false)
        private String email;

     //getter and setters

        public int getId() {
            return id;
        }

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

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

    }

我做了一个学生界面:-

package com.sat.Dao;

import java.util.List;

public interface Student {

    public void insert(Student student);
    public Boolean update();
    public Student findById(int id);
    public Student findByFirstname(String  firstname);

    List<Student> select(int id, String firstname, String lastname, String       email, int age);
    List<Student> selectAll();

}

学生道是

import java.util.List;

public class StudentDao implements Student{

@Override
public void insert(Student student) {
    // TODO Auto-generated method stub

}

@Override
public Boolean update() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Student findById(int id) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Student findByFirstname(String firstname) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<Student> select(int id, String firstname, String lastname,
        String email, int age) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public List<Student> selectAll() {
    // TODO Auto-generated method stub
    return null;
}

}

我在 mySql 上有一个数据库

我正在尝试使用 SpringDriverManager 或 BasicdataSource 连接到 Student 数据库。

怎么办?

我的主要应用类是:

@SpringBootApplication
@ComponentScan ({"com.sat", "com.sat.controller"} )
@Configuration
@EnableAutoConfiguration
@EnableWebMvc

public class SpringMvc10Application extends SpringBootServletInitializer{


public static void main(String[] args) {


    SpringApplication application = new SpringApplication(SpringMvc10Application.class);
    application.setShowBanner(false);;
                   application.run(args);

    System.out.println("Let's inspect the beans provided by Spring Boot:");


}

}

我的应用程序属性文件是

# Spring MVC
#spring.view.prefix:classpath:/templates/
#spring.view.suffix:.html
#spring.view.view-names:jsp/*, html/*
#spring.thymeleaf.view-names:thymeleaf/*

name=Phil, david

# Server
server.port=8088

#override the spring parameter 'create-drop', 'create' creates the schema deleting the previous data
spring.jpa.hibernate.ddl-auto=create

# no sql in the log
spring.jpa.show-sql=false

# mySQL
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/student
database.username=root
database.password=root

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.check-template-location=true
#spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution
#spring.thymeleaf.view-names= well, # comma-separated list of view names that can be resolved
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache= true
# set to false for hot refresh

我的简单 index.html 是用户插入存储在数据库中的输入:

<!DOCTYPE html>
<html> <!--xmlns:th="http://www.thymeleaf.org">-->
    <head>
        <title>Thymeleaf tutorial: exercise 2</title>
        <!--<link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />-->
        <meta charset="utf-8" />
    </head>
    <body>

        <h1>Thymeleaf tutorial - Student Info</h1>
        <h2>Student information</h2>



        <input type="text" name="fname" value="" id="firstName"/>
        <input type="text" name="lname" value="" id="lastName"/>

<label for="submit">submit</label><input type="submit" name="submit" value="submit" id="submit"/>

  <span th:text="${name}"> </span>

    </body>

</html>

现在我很困惑,因为我正在学习很多教程,但我在 springBoot 上看不到太多。我不知道该怎么走。

请在我学习 Spring 时向我推荐正确的方向。我希望有人能提供帮助,因为我已经坚持了好几天了。

我想用spring Driver Manager做一个连接池:

@Bean (name = "dataSource")
    public DataSource dm() {

        DriverManagerDataSource dbs = new DriverManagerDataSource();

        dbs.setDriverClassName("jdbc.driverClassName");
        dbs.setUrl("jdbc:mysql://localhost:3306/student");
        dbs.setUsername("root");
        dbs.setPassword("root");

//      dbs.max-active=100;


        return dm();

    }

如何设置maxActive Connections,在这?

现在我想将它注入到我的 StudentDaoImp 类中,如下所示:

@Override
    public List<Student> select(int id, String firstname, String lastname,
            String email, int age) throws Exception {
        java.sql.Connection con = ds.getConnection();

        // List

        con.close();

        return null;
    }

当我将项目作为 Spring Boot 应用程序运行时,我得到了这个:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in com.sat.SpringMvc10Application: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dm' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [jdbc.driverClassName]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMetho

谁能帮我改正错误。

谢谢

【问题讨论】:

  • 如果您是 Spring 新手,请学习核心框架、mvc 和 Spring 数据(用于 JPA)。 Spring Boot 只是基于这些最佳实践的最佳实践和自动配置,因此,如果您正在学习 Spring,其中很多看起来像是“魔法”。
  • spring boot 背后的想法是它将配置所有必要的数据源等。你不需要做任何你已经做过的事情,比如配置数据源等
  • github.com/spring-projects/spring-boot/tree/master/… .. 下载此代码并执行,您可以看到引导是如何工作的..
  • 我下载了。有人可以看看我的代码并指出我做错了什么吗?

标签: mysql spring jpa dao


【解决方案1】:

你忘了设置正确的驱动类名:

java.lang.IllegalStateException:无法加载 JDBC 驱动程序类 [jdbc.driverClassName]

更改语句

dbs.setDriverClassName("jdbc.driverClassName");

dbs.setDriverClassName("com.mysql.jdbc.Driver");

你应该很高兴。好吧,至少这个例外应该消失了。并且不要忘记将驱动程序添加到您的类路径中。

编辑:

  • 您有一个无限递归:dm() 调用 dm() 而不是简单地返回 dbs
  • 您在 Student 实体中导入了错误的 @Id 注释(应该是 JPA 实体)。
  • 您似乎实现了 DAO 并使用 JDBC 访问数据库。使用 JPA 时,您应该使用 EntityManager 来执行此操作。在这种情况下,当使用 Spring Data JPA(类路径的一部分)时,您甚至不需要使用 EntityManager 实现 DAO,您只需使用所需方法定义 JPA 存储库 Java 接口即可。李>

【讨论】:

  • 感谢您的指出。这是一个 GitHub 链接:github.com/sotish/SpringMVC11.git
  • 感谢 Brian 查看代码并对延迟回复表示抱歉。让我改正错误,我会回来的……
猜你喜欢
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 2019-10-28
  • 2017-08-06
相关资源
最近更新 更多