spring data 之 Spring Data JPA


Spring Data 是一些令人兴奋的技术公司和开发人员开发的,让用新的数据库访问技术使用更方便。包含了多个子项目。
http://spring.io/guides/gs/accessing-data-jpa/

定义简单的实体类Customer:

//@Entity表明该实体未JPA实体,对应数据库中的Customer表,@Table
@Entity
public class Customer {

//@Id so that JPA will recognize it as the object’s ID. The id property is also annotated with @GeneratedValue to indicate that the ID should be generated automatically.

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }
}
Spring Data JPA 关注在关系型数据库使用JPA存储数据。最引人注目的功能是在运行时从一个respoitory接口 自动创建repository实现类。
public interface CustomerRepository extends CrudRepository<Customer, Long> {
    List<Customer> findByLastName(String lastName);
}
CustomerRepository 继承了CrudRepository 接口,通过泛型,指定了实体类型和ID类型为Customer和Long。
CrudRepository  包括多个持久化方法,包括保存、删除和查找Customer实体。Spring Data JPA同样允许自定义其它的查询方法。


EnableJpaRepositories 注解,表明Spring Data JPA遍历任何实现了org.springframework.data.repository.Repository接口的接口,然后自动生成它的实现类。
@Configuration
@EnableJpaRepositories
public class Application {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(H2).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
        lef.setDataSource(dataSource);
        lef.setJpaVendorAdapter(jpaVendorAdapter);
        lef.setPackagesToScan("hello");
        return lef;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setShowSql(false);
        hibernateJpaVendorAdapter.setGenerateDdl(true);
        hibernateJpaVendorAdapter.setDatabase(Database.H2);
        return hibernateJpaVendorAdapter;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager();
    }


    public static void main(String[] args) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        CustomerRepository repository = context.getBean(CustomerRepository.class);

        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        Iterable<Customer> customers = repository.findAll();
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : customers) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        System.out.println("Customer found with findOne(1L):");
        System.out.println("--------------------------------");
        System.out.println(customer);
        System.out.println();

        // fetch customers by last name
        List<Customer> bauers = repository.findByLastName("Bauer");
        System.out.println("Customer found with findByLastName('Bauer'):");
        System.out.println("--------------------------------------------");
        for (Customer bauer : bauers) {
            System.out.println(bauer);
        }
        context.close();
    }
}

maven pom文件
    
    
    
    
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns= "http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
     xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" >
     <modelVersion>4.0.0 </modelVersion>
     <groupId>org.springframework </groupId>
     <artifactId>gs-accessing-data-jpa </artifactId>
     <version>0.1.0 </version>
     <parent>
         <groupId>org.springframework.boot </groupId>
         <artifactId>spring-boot-starter-parent </artifactId>
         <version>0.5.0.M6 </version>
     </parent>
     <dependencies>
         <dependency>
             <groupId>org.springframework </groupId>
             <artifactId>spring-orm </artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.data </groupId>
             <artifactId>spring-data-jpa </artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot </groupId>
             <artifactId>spring-boot-starter-web </artifactId>
         </dependency>
         <dependency>
             <groupId>org.hibernate </groupId>
             <artifactId>hibernate-entitymanager </artifactId>
         </dependency>
         <dependency>
             <groupId>com.h2database </groupId>
             <artifactId>h2 </artifactId>
         </dependency>
     </dependencies>
     <build>
         <plugins>
             <plugin>
                 <artifactId>maven-compiler-plugin </artifactId>
             </plugin>
         </plugins>
     </build>
     <repositories>
         <repository>
             <id>spring-milestones </id>
             <name>Spring Milestones </name>
             <url>http://repo.spring.io/libs-milestone </url>
             <snapshots>
                 <enabled>false </enabled>
             </snapshots>
         </repository>
         <repository>
             <id>org.jboss.repository.releases </id>
             <name>JBoss Maven Release Repository </name>
             <url>https://repository.jboss.org/nexus/content/repositories/releases </url>
             <snapshots>
                 <enabled>false </enabled>
             </snapshots>
         </repository>
     </repositories>
     <pluginRepositories>
         <pluginRepository>
             <id>spring-milestones </id>
             <name>Spring Milestones </name>
             <url>http://repo.spring.io/libs-milestone </url>
             <snapshots>
                 <enabled>false </enabled>
             </snapshots>
         </pluginRepository>
     </pluginRepositories>
</project>

你可能感兴趣的:(spring,数据库)