`
sunxboy
  • 浏览: 2838164 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

spring data JPA的写法以及如何 测试

 
阅读更多

1。 pom 导入测试要用到的包

 

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.github.springtestdbunit</groupId>
			<artifactId>spring-test-dbunit</artifactId>
			<version>1.1.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.dbunit</groupId>
			<artifactId>dbunit</artifactId>
			<version>2.5.0</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<artifactId>junit</artifactId>
					<groupId>junit</groupId>
				</exclusion>
			</exclusions>
		</dependency>

 

 

2. spring data for JPA 数据库配置代码

 

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.eifesun.monitor.db.repository")
@PropertySource("classpath:application.properties")
@EnableJpaAuditing
public class PersistenceContext {

    protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";

    private static final String PROPERTY_PACKAGES_TO_SCAN = "com.eifesun.monitor.db.jpa";
    private static final String CONVERT_PACKAGES_TO_SCAN = "org.springframework.data.jpa.convert.threeten";

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
    	HikariConfig dataSourceConfig = new HikariConfig();
    	
    	dataSourceConfig.setDriverClassName(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
    	dataSourceConfig.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
    	dataSourceConfig.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
    	dataSourceConfig.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return new HikariDataSource(dataSourceConfig);
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN, CONVERT_PACKAGES_TO_SCAN);

        Properties jpaProperties = new Properties();
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        //jpaProperties.put("jadira.usertype.autoRegisterUserTypes", "true");

        entityManagerFactoryBean.setJpaProperties(jpaProperties);
        
        entityManagerFactoryBean.setMappingResources("META-INF/orm.xml");
        return entityManagerFactoryBean;
    }

注意:orm.xml

 

 

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd" version="2.0">
	<persistence-unit-metadata>
		<persistence-unit-defaults>
			<entity-listeners>
				<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" />
			</entity-listeners>
		</persistence-unit-defaults>
	</persistence-unit-metadata>
</entity-mappings>

 作用是为了使@createddate @version等spring annoation生效

 

 

3. 数据库的配置文件可以这样写,不同数据库有所不同

application.properties

 

#Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:mem:datajpa
db.username=sa
db.password=

#Hibernate Configuration
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=false
hibernate.format_sql=true

 

 

4. entity的写法很普通

 

@Entity
@Table(name = "inverter")
public class Inverter {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    @Column(name = "client_id", nullable = false, length = 20)
    private String clientId;
    
    @Column(name = "record_time")
    @Temporal(TemporalType.TIMESTAMP)
    private Date recordTime;
    
    @Column(name = "output_power")
    private int outputPower;
    
    @Column(name = "output_energy")
    private int outputEnergy;
    
    @Column(name = "energy_total")
    private long energyTotal;

    @CreatedDate
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime creationTime;
}

 

 

5.repository 的写法也很普通

 

public interface InverterRepository extends Repository<Inverter, Long>{
	 List<Inverter> findByClientIdAndRecordTimeBetween(String inverterId, Date startTime, Date endTime);

	 Inverter save(Inverter entity);
	 
}

 

 

6. 测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
@DatabaseSetup("inverterData.xml")
public class InverterRepositoryTest {
    @Autowired
    private InverterRepository repository;
    
    @Test
	public void when_find_by_clientid_and_record_times_should_return_one() throws Exception {
    	
    	// when
    	Date start = DateTime.now().withDate(2015, 5, 14).withTimeAtStartOfDay().toDate();
    	Date end = DateTime.now().withDate(2015, 5, 15).withTimeAtStartOfDay().toDate();
    	List<Inverter> inverters = repository.findByClientIdAndRecordTimeBetween("inverter1", start, end);
    	
    	// then
    	assertThat(inverters.size(), is(1));
	}
    
    @Test
	public void when_save_and_created_time_should_not_null() throws Exception {
		
    	// given
    	Inverter inverter = new Inverter();
    	inverter.setClientId("inverter2");
    	inverter.setEnergyTotal(1000);
    	inverter.setOutputEnergy(200);
    	inverter.setOutputPower(3000);
    	inverter.setRecordTime(new Date());
    	
    	// when
    	Inverter inverter2 = repository.save(inverter);
    	
    	// then
    	assertThat(inverter2.getCreationTime(), notNullValue());    	
	}
}

 

只要这样配置一下就可以使用操作数据库了,是不是很方便?

注意inverterData.xml里是表字段的信息

<dataset>
    <inverter id="1" client_id="inverter1" record_time="2015-05-14 15:55:32" output_power="100" output_energy="250" energy_total="345000"/>
</dataset>

 

以上

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics