Configurando Spring Data-JPA por Classes

Arquivo PersistenceContext.java


package br.com.info4brasil.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "br.com.codigovivo.model"
, entityManagerFactoryRef="entityManagerFactory"
, transactionManagerRef="transactionManager")
public class PersistenceContext {

	@Bean
	DataSource datasource(){
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
	      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	      dataSource.setUrl("jdbc:mysql://localhost:3306/dbescola");
	      dataSource.setUsername( "root" );
	      dataSource.setPassword( "root" );
	      return dataSource;

	}

	 @Bean(name= "entityManagerFactory")
		public LocalContainerEntityManagerFactoryBean  entityManagerFactoryBean(DataSource ds ) {
			LocalContainerEntityManagerFactoryBean  emfb = new LocalContainerEntityManagerFactoryBean ();
			emfb.setDataSource(ds);
			emfb.setPackagesToScan("br.com.codigovivo.model");
			emfb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
			Properties jpaProterties = new Properties();
			jpaProterties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
			jpaProterties.put("hibernate.format_sql", true );
			jpaProterties.put("hibernate.show_sql", true);
			jpaProterties.put("hibernate.hbm2ddl.auto", "create");
			emfb.setJpaProperties(jpaProterties);
			return emfb;
		}

	 @Bean(name="transactionManager")
		public JpaTransactionManager transactionmanager(EntityManagerFactory emf){
			JpaTransactionManager transactionManager = new JpaTransactionManager();
			transactionManager.setEntityManagerFactory( emf );
			return transactionManager;
		} 

Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    return properties;
 }
}

Related posts

Leave a Comment