Spring + Hibernate使用注释和存储库的简单应用程序

时间:2015-06-02 20:14:27

标签: java spring hibernate jpa

我想创建一个使用spring注释来配置bean的应用程序,以及spring jparepository,以便不需要创建对数据库的查询。到目前为止我创建了我的实体:

@Entity
public class Executor extends AbstractEntity {

    private String company;
    private String responsible;
    private String supervisor;

    public Executor() {        
    }

    public Executor(String company, String responsible, String supervisor) {
        this.company = company;
        this.responsible = responsible;
        this.supervisor = supervisor;
    }
... getters and setters...

我也创建了我的存储库:

public interface ExecutorRepository extends JpaRepository<Executor, Integer> {

    public List<Executor> findByCompany(String company);

    public List<Executor> findByResponsible(String responsible);

    public List<Executor> findBySupervisor(String supervisor);
}

服务:

public class ExecutorService {

    @Autowired
    private ExecutorRepository repository;

    @Transactional
    public Executor create(Executor calibration) {
        return repository.save(calibration);
    }

    @Transactional(rollbackFor = CalibrationNotFound.class)
    public Executor delete(int id) throws ExecutorNotFound {
        Executor deleted = repository.findOne(id);
        if (deleted == null) {
            throw new ExecutorNotFound();
        }
        repository.delete(deleted);
        return deleted;
    }

    @Transactional
    public List<Executor> findAll() {
        return repository.findAll();
    }

}

我使用了注释来配置bean:

// Informa que é uma classe que define beans.
@Configuration
// Cria o bean para o Environment.
@PropertySource("classpath:configuration/configuration.properties") 
@EnableTransactionManagement
@EnableJpaRepositories("com.metrum.persistence.repository")
@ComponentScan("com.metrum.persistence")
public class ApplicationConfig {


    /**
     * Representa o ambiente da aplicação. Modela profiles e propriedades. As
     * suas propriedades são carregadas através da anotação \@PropertySource.
     */
    @Autowired
    private Environment env;    


    /**
     * Produz um bean para DataSource.
     *
     * O DataSource carrega informações sobre o banco de dados e permite gerar
     * conexões com este.
     *
     * @return DataSource
     */
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty("db.driver"));
        dataSource.setUrl(env.getRequiredProperty("db.url"));
        dataSource.setUsername(env.getRequiredProperty("db.username"));
        dataSource.setPassword(env.getRequiredProperty("db.password"));

        return dataSource;
    }

    /**
     * Cria e retorna um bean para EntityManagerFactory.
     *
     * Uma EntityManagerFactory cria EntityManagers para o mesmo banco de dados,
     * com as mesmas configurações. Uma EntityManager permite acessar o banco de
     * dados em busca de entities.
     *
     * @return EntityManagerFactoryBean.
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty("entitymanager.packages.to.scan"));

        entityManagerFactoryBean.setJpaProperties(getHibernateProperties());

        return entityManagerFactoryBean;
    }

    /**
     * Retorna propriedades do ORM Hibernate.
     */
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        return properties;
    }

    /**
     * Bean para criação de uma JpaTransactionManager, 
     * implementação do Spring para o transações JPA.
     *
     * @return JpaTransactionManager
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
}

最后应用程序主要是:

public class Application {

    @Autowired
    private ExecutorService service;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(ApplicationConfig.class);
        ctx.refresh();

        Application app = new Application();
        app.test();
    }

    public void test() {
        Executor executor = new Executor("Metrum Sistemas de Medição", 
                "Leandro Santos de Lima", "Levy Albuquerque");
        service.create(executor);
    }

好吧,我以为我做得很好但是没有注入ExecutorService所以我收到了NullPointerException。

我想知道我做错了什么。

由于

0 个答案:

没有答案