`

Spring Data CRUD

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2299253

 

1.Maven Dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.fool.springdata</groupId>
	<artifactId>springdata</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springdata</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.10.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.1.0.Final</version>
		</dependency>

		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.39</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.2.5.RELEASE</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.dbunit</groupId>
			<artifactId>dbunit</artifactId>
			<version>2.5.2</version>
		</dependency>

		<dependency>
			<groupId>com.github.springtestdbunit</groupId>
			<artifactId>spring-test-dbunit</artifactId>
			<version>1.3.0</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>2.3.4</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

 

2.Project Structure


 

3.Spring Config xml - beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd    
        http://www.springframework.org/schema/context     
        http://www.springframework.org/schema/context/spring-context.xsd    
        http://www.springframework.org/schema/tx     
        http://www.springframework.org/schema/tx/spring-tx.xsd    
        http://www.springframework.org/schema/aop    
        http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/jdbc 
		http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/data/jpa
    	http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

	<jpa:repositories base-package="org.fool.springdata.repository" />

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
		<property name="packagesToScan" value="org.fool.springdata.domain" />
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/springdata?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
	</bean>

	<bean id="jpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="generateDdl" value="true" />
		<property name="database" value="MYSQL" />
		<property name="showSql" value="true" />
	</bean>
</beans> 

 

4. Domain - Customer.java

package org.fool.springdata.domain;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

@Entity
public class Customer {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String firstName;
	private String lastName;
	private String address;
	private Date registerDate;

	public Customer() {
	}

	public Customer(String firstName, String lastName, String address, Date registerDate) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.address = address;
		this.registerDate = registerDate;
	}

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Date getRegisterDate() {
		return registerDate;
	}

	public void setRegisterDate(Date registerDate) {
		this.registerDate = registerDate;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}
}

 

5. Repository - CustomerRepository.java

package org.fool.springdata.repository;

import java.util.List;

import org.fool.springdata.domain.Customer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface CustomerRepository extends CrudRepository<Customer, Long> {
	List<Customer> findByLastName(String lastName);

	List<Customer> findByAddress(String address);

	@Query("select c from Customer c where c.firstName = :name or c.lastName = :name")
	List<Customer> findByFirstNameOrLastName(@Param("name") String name);
	
	@Query("select c from Customer c where c.firstName = ?1 and c.lastName = ?2")
	List<Customer> findByFirstNameAndLastName(String firstName, String lastName);
}

 

6. Unit Test - CustomerTest.java

package org.fool.springdata.test;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.fool.springdata.domain.Customer;
import org.fool.springdata.repository.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.google.common.collect.Lists;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class CustomerTest {
	@Inject
	private CustomerRepository customerRepository;

	private Customer customer;
	private List<Customer> customerList;

	@Test
	public void testFindByLastname() {
		List<Customer> cList = customerRepository.findByLastName("fei");
		cList.forEach(c -> System.out.println(c));
	}

	@Test
	public void testFindByAddress() {
		customerRepository.findByAddress("ShuGuo").forEach(c -> System.out.println(c));
	}

	@Test
	public void testFindByFirstNameOrLastName() {
		customerRepository.findByFirstNameOrLastName("Liu").forEach(c -> System.out.println(c));
	}

	@Test
	public void testFindByFirstNameAndLastName() {
		customerRepository.findByFirstNameAndLastName("Liu", "Shan").forEach(c -> System.out.println(c));
	}

	@Test
	public void testSave() {
		customer = new Customer();
		customer.setFirstName("Cao");
		customer.setLastName("Cao");
		customer.setAddress("WeiGuo");
		customer.setRegisterDate(new Date());

		Customer customer1 = new Customer("Liu", "Bei", "ShuGuo", new Date());
		Customer customer2 = new Customer("Guan", "Yu", "ShuGuo", new Date());
		Customer customer3 = new Customer("Zhang", "Fei", "ShuGuo", new Date());
		Customer customer4 = new Customer("Liu", "Shan", "ShuGuo", new Date());

		customerList = Lists.newArrayList(customer1, customer2, customer3, customer4);

		customerRepository.save(customer);
		customerRepository.save(customerList);
	}

	@Test
	public void testFindOne() {
		Customer c = customerRepository.findOne(11L);
		System.out.println(c);
	}

	@Test
	public void testFindAll() {
		List<Customer> cList = Lists.newArrayList(customerRepository.findAll());

		cList.forEach(c -> System.out.println(c));
	}

	@Test
	public void testDeleteAll() {
		List<Customer> cList = Lists.newArrayList(customerRepository.findAll());

		customerRepository.delete(cList);
	}
	
	@Test
	public void testUpdateOne() {
		Customer c = customerRepository.findOne(11L);
		c.setFirstName("Cao");
		c.setLastName("Pi");
		
		customerRepository.save(c);
	}
}

 

7.使用DBUnit+HSQLDB进行单元测试

DALConfigTest.java

package org.fool.springdata.dal.config;

import java.util.Properties;

import javax.inject.Inject;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
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.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:db.properties")
@EnableJpaRepositories("org.fool.springdata.repository")
@ComponentScan("org.fool.springdata.domain")
public class DALConfigTest {
	private static final String JDBC_DRIVER = "jdbc.driver";
	private static final String JDBC_URL = "jdbc.url";
	private static final String JDBC_USERNAME = "jdbc.username";
	private static final String JDBC_PASSWORD = "jdbc.password";

	private static final String HIERNATE_DIALECT = "hibernate.dialect";
	private static final String HIERNATE_FORMAT_SQL = "hibernate.format_sql";
	private static final String HIBERNATE_EJB_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
	private static final String HIBERNATE_SHOW_SQL = "hibernate.show_sql";
	private static final String HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";

	@Inject
	private Environment environment;

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

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

		return transactionManager;
	}

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

		Properties jpaProperties = new Properties();
		jpaProperties.put(HIERNATE_DIALECT, environment.getRequiredProperty(HIERNATE_DIALECT));
		jpaProperties.put(HIERNATE_FORMAT_SQL, environment.getRequiredProperty(HIERNATE_FORMAT_SQL));
		jpaProperties.put(HIBERNATE_SHOW_SQL, environment.getRequiredProperty(HIBERNATE_SHOW_SQL));
		jpaProperties.put(HIBERNATE_EJB_NAMING_STRATEGY, environment.getRequiredProperty(HIBERNATE_EJB_NAMING_STRATEGY));
		jpaProperties.put(HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(HIBERNATE_HBM2DDL_AUTO));
		entityManagerFactoryBean.setJpaProperties(jpaProperties);
		entityManagerFactoryBean.setDataSource(dataSource());
		entityManagerFactoryBean.setPackagesToScan("org.fool.springdata.domain");
		entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

		return entityManagerFactoryBean;
	}

	@Bean
	public DataSource dataSource() {
		final DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(environment.getRequiredProperty(JDBC_DRIVER));
		dataSource.setUrl(environment.getRequiredProperty(JDBC_URL));
		dataSource.setUsername(environment.getRequiredProperty(JDBC_USERNAME));
		dataSource.setPassword(environment.getRequiredProperty(JDBC_PASSWORD));

		return dataSource;
	}
}

 CustomerData.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
	<Customer id="1" firstName="Hello" lastName="World" address="China"
		registerDate="2016-06-20 00:00:00.0" />
</dataset>

 db.properties

#Database Configuration
jdbc.driver=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:payment;shutdown=false
jdbc.username=sa
jdbc.password=

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

AbstractRepositoryTest.java

package org.fool.sprindata.dal.test;

import org.fool.springdata.dal.config.DALConfigTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration
public class AbstractRepositoryTest {
	@Configuration
	@Import(DALConfigTest.class)
	static class Config {
	}
}

 CustomerTest.java

package org.fool.sprindata.dal.test;

import javax.inject.Inject;

import org.fool.springdata.repository.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class })
public class CustomerTest extends AbstractRepositoryTest {
	@Inject
	private CustomerRepository customerRepository;

	@Test
	@DatabaseSetup("classpath:CustomerData.xml")
	public void testFindAll() {
		System.out.println(customerRepository.findAll());
	}

}

 

 

 

 

 

 

 

  • 大小: 26.6 KB
分享到:
评论

相关推荐

    [简单]Spring简单CRUD示例

    默认情况下,Spring Data JPA提供了一些基本的CRUD方法: ```java public interface UserRepository extends JpaRepository, Long&gt; { } ``` 现在,我们可以使用这个Repository在Service层执行CRUD操作: ```java ...

    Java进阶教程数据层全栈方案SpringData高级应用视频教程

    5.SpringData ElasticSearch实现CRUD操作 第九章 SpringData MongDB 1.SpringData MongDB简介 2.MongDB环境搭建 3.MongDB基础知识回顾 4.SpringData MongDB入门案例 5.SpringData MongDB实现CRUD操作 第十章 综合...

    Spring Data JPA 笔记

    例如,Spring Data JPA支持自动化的查询生成,只需定义Repository接口,无需编写任何实现代码,就可以执行CRUD(创建、读取、更新、删除)操作。此外,它还支持复杂的查询方法命名,如findByXXX,根据方法名自动构建...

    Spring Data MongoDB中文文档

    - **MongoTemplate** 是 **Spring Data MongoDB** 提供的一个核心类,用于执行 MongoDB 的 CRUD 操作。 - 它提供了很多方便的方法来执行数据库操作,例如:`insert()`, `save()`, `findOne()`, `remove()`, `find()`...

    Spring Data JPA Spring Data Commons

    Spring Data JPA是Spring框架的一部分,它是一种简便的数据访问层(Repository)的实现技术,主要用来简化JPA(Java Persistence API)实体数据访问代码的编写。Spring Data JPA允许开发者通过简单的接口和注解配置...

    尚硅谷SpringData视频观看下载链接

    SpringData是Spring框架的一个重要模块,它为Java开发者提供了丰富的数据访问抽象,简化了与各种数据存储系统的交互。本资源“尚硅谷SpringData视频”旨在帮助学习者深入理解和掌握SpringData的相关知识,通过视频...

    Spring Data JPA从入门到精通

    4. **Repository接口**:Spring Data JPA的核心是Repository接口,通过继承自定义的Repository接口,开发者可以声明CRUD(创建、读取、更新、删除)操作以及自定义查询方法。 5. **Entity实体**:在Spring Data JPA...

    SpringData入门到精通

    SpringData是Spring框架的一个重要模块,它为Java开发者提供了与数据存储进行交互的简便方法,涵盖了关系型数据库、NoSQL数据库、搜索引擎等多种数据访问技术。本教程“SpringData入门到精通”将引领你逐步深入...

    SpringDataRedis的jar包.rar

    2. **RedisTemplate**:这是Spring Data Redis的核心组件,它提供了一套丰富的操作接口,包括字符串、哈希、列表、集合和有序集合等数据类型的CRUD操作。例如,可以使用`opsForValue()`进行字符串操作,`opsForHash...

    Maven整合Spring+SpringMVC+Hibernate+SpringDataJPA

    在现代Java Web开发中,"Maven整合Spring+SpringMVC+Hibernate+SpringDataJPA"是一个常见的架构组合,被广泛应用于构建企业级应用程序。这个组合通常被称为"SSM",其中"M"代表Maven,"S"代表Spring,包括Spring核心...

    Spring Boot整合SpringDataJPA

    Spring Data JPA是Spring生态系统中的一个重要组件,它为开发者提供了与JPA(Java Persistence API)交互的简化接口,极大地提高了数据访问的效率。本教程将深入探讨如何在Spring Boot项目中整合Spring Data JPA,...

    SpringData如何实现查询的代码

    在这个例子中,`JpaRepository`提供了基本的CRUD操作,而`findByUsername`方法是自定义的查询方法,SpringData会自动解析其名称并生成对应的SQL(对于JPA)或其他查询语言(对于其他数据存储)。这种方法的优点在于...

    spring学习:spring data jpa

    只需定义一个接口,该接口继承自Spring Data提供的Repository接口,并指定实体类和ID类型,Spring Data JPA就会自动生成对应的实现,包含基本的CRUD操作。 2. **Query 方法**:在Repository接口中,可以定义方法名...

    Spring Data JPA.zip

    - **强大的查询支持**:除了简单的 CRUD 方法,Spring Data JPA 还支持基于方法名的复杂查询,甚至可以使用 JPA Querydsl 或 Specification 进行更复杂的查询。 - **事务管理**:Spring Data JPA 结合 Spring 的事务...

    spring data实战源码

    1. **自动Repository生成**:Spring Data通过提供一个简单的接口定义,可以自动生成实现这些接口的Repository实例,从而减少了大量重复的CRUD操作代码。 2. **查询方法命名约定**:通过遵循特定的命名规则,开发者...

    spring data for redis

    Spring Data提供了一种声明式的方式来定义数据操作,如CRUD(创建、读取、更新、删除)。通过定义接口并继承`CrudRepository`或`JpaRepository`,可以自动生成对应的Redis操作。 ### 4. Spring Data for Redis的...

    spring-data-rest-angular例子

    Spring Data REST Angular 示例项目是一个整合了Java Spring Boot框架与Angular前端框架的应用实例,展示了如何构建一个现代化的Web应用。这个项目旨在演示如何利用Spring Data REST将后端数据服务暴露为RESTful API...

    一个完整的Spring MVC的CRUD操作实例

    **Spring MVC CRUD操作实例详解** Spring MVC是Spring框架的一个模块,专门用于构建Web应用程序,它提供了模型-视图-控制器(MVC)架构的支持。在本文中,我们将深入探讨如何实现一个完整的Spring MVC CRUD(创建、...

Global site tag (gtag.js) - Google Analytics