Error when searching the database using Java, Hibernate and Spring. Use of Beans and Autowired

0

I'm trying to search my program, but errors appear:

  

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'courseSpringDataApplication': Unsatisfied dependency expressed through field 'personRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': Can not create inner bean '(inner bean) # 34f7234e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean) # 34f7234e': Can not resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [br / com / devmedia / course / config / SpringDataConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

     

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personRepository': Can not create inner bean '(inner bean) # 34f7234e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean) # 34f7234e': Can not resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [br / com / devmedia / course / config / SpringDataConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]   Code

@Configuration
@EnableJpaRepositories(basePackages = "br.com.devmedia.curso.repository")
@EnableTransactionManagement
@PropertySource(value = "classpath:application.properties")
public class SpringDataConfig {

@Value(value = "${jdbc.user}")
private String username;

@Value(value = "${jdbc.pass}")
private String password;

@Value(value = "${jdbc.driver}")
private String driver;

@Value(value = "${jdbc.url}")
private String url;


@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
    JpaTransactionManager manager = new JpaTransactionManager();
    manager.setEntityManagerFactory(factory);
    manager.setJpaDialect(new HibernateJpaDialect());

    return manager;     
}


@Bean
public EntityManagerFactory entityManagerFactory() {
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setShowSql(true);
    adapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(adapter);
    factory.setPackagesToScan("br.com.devmedia.curso.entity");
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();     
}



public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);

    return dataSource;
}

}


@SpringBootApplication
public class CursoSpringDataApplication  implements CommandLineRunner{

@Autowired
private PersonRepository personRepository;

@Autowired
private AddressRepository addressRepository;

@Autowired
private DocumentRepository documentRepository;

@Autowired
private PhoneRepository phoneRepository;

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

}

@Override
public void run(String... args) throws Exception{

    testConfiguration();
}

private void testConfiguration() {

    long total = personRepository.count();
    System.out.println("Total de Persons: " + total);

    List<Person> persons = personRepository.findAll();
    persons.forEach(System.out::println);

    long t2 = addressRepository.count();
    System.out.println("Total de Addresses: " + t2);

    long t3 = documentRepository.count();
    System.out.println("Total de Documents: " + t3);

    long t4 = phoneRepository.count();
    System.out.println("Total de Phones: " + t4);


}
}

PersonRepository class:

import pacote...entity.Person;

public interface PersonRepository extends JpaRepository<Person, Long>{

}

Class Person:

@Entity
@Table(
    name = "PERSONS",
    indexes = {@Index(columnList = "FIRST_NAME, LAST_NAME", name = "IDX_PERSON_NAME", unique = true)}
)
public class Person implements Serializable {

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID_PERSON")
    private Long id;

    @Column(name = "FIRST_NAME", nullable = false, length = 30)
    private String firstName;

    @Column(name = "LAST_NAME", nullable = false, length = 60)
    private String lastName;

    @Column(name = "AGE", nullable = false)
    private Integer age;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "DOCUMENT_ID")
    private Document document;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Fetch(FetchMode.SUBSELECT)
    private List<Phone> phones;

    public void addPhone(Phone phone) {
        if(phones == null) {
            phones = new ArrayList<Phone>();
        }
        phone.setPerson(this);
        phones.add(phone);
    }

    public void delPhone(Phone phone) {
        if(phones != null) {
            phones.remove(phone);
        }
    }

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "PERSONS_ADDRESSES",
                joinColumns = @JoinColumn(name = "ID_PERSON"),
                inverseJoinColumns = @JoinColumn(name = "ID_ADDRESS")
            )
    private List<Address> addresses;



    public Long getId() {
        return id;
    }

    public void setId(Long 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(Integer age) {
        this.age = age;
    }   

    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    public List<Phone> getPhones() {
        return phones;
    }

    public void setPhones(List<Phone> phones) {
        this.phones = phones;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }


    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }


    @Override
    public String toString() {
        return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age
                + ", document=" + document + "]";
    }
}
    
asked by anonymous 11.03.2018 / 22:26

0 answers