2015-01-16 23 views
21

Voglio impostare Spring Boot con MySQL e JPA. Per questo ho creato: personaCome utilizzare Spring Boot con database MySQL e JPA?

package domain; 

import javax.persistence.*; 

@Entity 
@Table(name = "person") 
public class Person { 

@Id 
@GeneratedValue 
private Long id; 

@Column(nullable = false) 
private String firstName; 

// setters and getters 
} 

PersonRepository

package repository; 

import domain.Person; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.Pageable; 
import org.springframework.data.repository.CrudRepository; 


public interface PersonRepository extends CrudRepository<Person, Long> { 

Page<Person> findAll(Pageable pageable); 
} 

PersonController

package controller; 

import domain.Person; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.ResponseBody; 
import repository.PersonRepository; 

@Controller 
public class PersonController { 

@Autowired 
private PersonRepository personRepository; 

@RequestMapping("/") 
@ResponseBody 
public String test() { 
    Person person = new Person(); 
    person.setFirstName("First"); 
    person.setLastName("Test"); 
    personRepository.save(person); 
    return "hello"; 
} 
} 

classe Inizio Esempio :

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class Example { 

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

} 

E per la configurazione del database, ho creare application.properties

spring.jpa.hibernate.ddl-auto=create-drop 
spring.jpa.properties.hibernate.globally_quoted_identifiers=true 

spring.datasource.url=jdbc:mysql://localhost/test_spring_boot 
spring.datasource.username=root 
spring.datasource.password=root 
spring.datasource.driverClassName=com.mysql.jdbc.Driver 

Così ho struttura del progetto:

enter image description here

Ma come risultato ho eccezioni:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [Example]; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/security/config/annotation/authentication/configurers/GlobalAuthenticationConfigurerAdapter.class] cannot be opened because it does not exist 

Come esempio che uso: spring-boot-sample-data-jpa/pom.xml

+0

Cosa dovrebbe dirci quel link? È il pom.xml per l'esempio 1.2.2.BUILD-SNAPSHOT di Spring Boot Data JPA. Inoltre, come stai facendo funzionare l'applicazione? – Steve

+0

@Steve, eseguo il mio Example.java in IDE ID – TestUser

+0

Viene eseguito dalla riga di comando? – Steve

risposta

22

ho creato un progetto come hai fatto tu. La struttura si presenta come questo

project structure

Le lezioni si basta copiare e incollare dalla vostra.

ho cambiato il application.properties a questo:

spring.datasource.url=jdbc:mysql://localhost/testproject 
spring.datasource.username=root 
spring.datasource.password=root 
spring.datasource.driverClassName=com.mysql.jdbc.Driver 
spring.jpa.hibernate.ddl-auto=update 

Ma penso che il problema è nella tua 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> 

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.4.1.RELEASE</version> 
</parent> 

<artifactId>spring-boot-sample-jpa</artifactId> 
<name>Spring Boot JPA Sample</name> 
<description>Spring Boot JPA Sample</description> 

<dependencies> 
    <dependency> 
     <groupId>mysql</groupId> 
     <artifactId>mysql-connector-java</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 
    <dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-data-jpa</artifactId> 
    </dependency> 
</dependencies> 
<build> 
    <plugins> 
     <plugin> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-maven-plugin</artifactId> 
     </plugin> 
    </plugins> 
</build> 

controllare questi file per le differenze. Spero che questo aiuti

Aggiornamento 1: Ho cambiato il mio nome utente. Il collegamento all'esempio è ora https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

+0

Copia le tue modifiche. È molto triste, ma ho ancora un'eccezione Causa di: java.io.FileNotFoundException: risorsa percorso classe [org/springframework/security/config/annotation/authentication/configurers/GlobalAuthenticationConfigurerAdapter.class] non può essere aperta perché non esiste ". – TestUser

+0

Poi hai più nel tuo progetto di quello che ci hai mostrato. Il tuo problema ha qualcosa a che fare con la sicurezza di primavera. Hai ancora una sicurezza primaverile nelle tue dipendenze da esperto? –

+0

No, non l'ho fatto. Mostro tutta la mia architettura e le mie lezioni – TestUser

-10

È possibile spostare Application.java in una cartella sotto java.

+0

Questo non fornisce una risposta alla domanda. Per criticare o richiedere chiarimenti da un autore, lascia un commento sotto il loro post - puoi sempre commentare i tuoi post, e una volta che hai [reputazione] sufficiente (http://stackoverflow.com/help/whats-reputation) essere in grado di [commentare qualsiasi post] (http://stackoverflow.com/help/privileges/comment). - [Dalla recensione] (/ recensione/post di bassa qualità/10777423) – SHAZ

+0

Cerco di eseguire l'applicazione e ottenere la stessa eccezione, dopo aver spostato la classe principale in una cartella, l'app può funzionare correttamente. – wuyuexin

3

Quando si spostano le classi in pacchetti specifici come repository, controller, dominio, solo il generico @SpringBootApplication non è sufficiente.

Si dovrà specificare il pacchetto di base per la scansione dei componenti

@ComponentScan("base_package") 

Per JPA

@EnableJpaRepositories(basePackages = "repository") 

è anche necessario, in modo i dati di primavera si sa dove guardare in per le interfacce repository.

+1

Mh sì e no. Se si utilizza '@ SpringBootApplication' tutti i componenti devono essere allo stesso livello o inferiori alla classe annotata con' @ SpringBootApplication'. In questo esempio questo è il caso, quindi non è necessario '@ ComponentScan'. –

0

Nel spring boot reference, ha detto:

Quando una classe non include una dichiarazione di package è considerato essere nel “pacchetto di default”. L'uso del "pacchetto predefinito" è generalmente scoraggiato e dovrebbe essere evitato. Può causare particolari problemi per le applicazioni Spring Boot che utilizzano le annotazioni @ComponentScan, @EntityScan o @SpringBootApplication, poiché verrà letta ogni classe di ogni jar.

com 
+- example 
    +- myproject 
     +- Application.java 
     | 
     +- domain 
     | +- Customer.java 
     | +- CustomerRepository.java 
     | 
     +- service 
     | +- CustomerService.java 
     | 
     +- web 
      +- CustomerController.java 

Nei tuoi casi. Devi aggiungere scanBasePackages nell'annotazione @SpringBootApplication.just come @SpringBootApplication(scanBasePackages={"domain","contorller"..})

Problemi correlati