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>
以上
相关推荐
在使用 Spring Data JPA 框架时,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及 @Query 注解实现。例如,我们可以定义一个方法来查询所有年龄大于 18 岁的用户: ```java public interface ...
### JavaEE就业班(夜光)③:SpringData开发 #### 一、Spring Data简介与优势 Spring Data 是一个用于简化数据库访问并支持云服务的开源框架。它旨在简化数据库访问逻辑,使得开发者能够更加关注业务逻辑而非底层...
Spring Data JPA 是 Spring 基于 Spring Data 框架、在JPA 规范的基础上开发的一个框架,使用 Spring Data JPA 可以极大地简化JPA 的写法,可以在几乎不用写实现的情况下实现对数据库的访问和操作,除了CRUD外,还...
Spring MVC Spring Data JPA Hibernate MySQL Spring Data Redis 用于缓存文章 Jade 作为视图模板,我极度不喜欢写 HTML 标签 Bootstrap 没有它我就不会写前端了 这是一个基于 Gradle 的项目,要想...
- 默认情况下,Spring Data JPA的方法会在已存在的事务中运行,如果当前没有事务,则会自动开启一个新的事务。 **2.7.3.4 为接口中的部分方法提供自定义实现** - 可以通过实现`CrudRepository`接口的子接口并覆盖...
Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷。可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括...
在实际开发中,还需要学习如何创建 RESTful API、处理 Web 请求、使用模板引擎(如 Thymeleaf 或 FreeMarker)构建动态网页、集成数据库、实现安全控制(如 Spring Security)以及测试策略。 标签中提到的 ...
3. **Spring Data JPA**:基于JPA,提供了更简洁的分页API。可以使用`Pageable`接口,通过`Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.ASC, "property"))`创建分页请求,...
<artifactId>spring-boot-starter-data-jpa <groupId>mysql <artifactId>mysql-connector-java <scope>runtime <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc10 <scope>runtime ``` ...
spring data jpa:数据库稳定连接技术 spring mvc:访问控制层技术 spring cloud robbin:使用客户端负载均衡,进行服务提供者的调用 spring cloud feign:分装了ribbon的使用,直接使用注解的方式,进行调用 弹簧靴...
- 考虑使用Spring的HibernateTemplate或JPA的EntityManager,它们提供了更高级的事务管理和资源管理功能。 6. 结合其他设计模式 - Service层:DAO层之上,负责业务逻辑,调用多个DAO完成复杂的业务处理。 - Factory...
这些类通常会包含实体属性,并使用`@Entity`注解标记,以便于Spring Data JPA处理。 4. **仓库(Repository)**:Spring Data JPA允许我们声明式地定义数据库操作。例如,我们可以创建一个`PostRepository`接口,...
Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷。可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括...
- Spring框架是一个全面的企业级应用程序开发框架,包含了许多模块,例如Spring MVC、Spring Data、Spring Security等。 - Spring MVC是Spring的核心模块之一,它是一个基于Java的实现了MVC设计模式的请求驱动类型的...