对象内存存储_习惯累积沉淀_新浪博客

用Spring Data JPA 基于内存存储pojo的简单案例

时间 2013-10-12 17:37:10   CSDN博客
主题  Spring  JPA

poject结构如下:

 

Customer.java类是一个pojo类,代码如下:

package hello;

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

@Entity
public class Customer {

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

    private 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);
    }

}
@Entity:说明该类是一个jpa entity,如果缺少@Table注解则默认匹配表Customer

@Id:jpa通过它定义识别对象Id,使用注解@GeneratedValue让id自动增长

toString:重写了对象打印出来的方法

CustomerRepository.java是jpa用来存储Customer对象的仓库。

package hello;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<<span class="title">Customer, Long> {

    List findByLastName(String lastName);

}

CustomerRepository继承了JpaRepository,除了能使用基本的增删改查外,还可以自己定义查找方法,如:findByLastName,关键在于findBy后面的属性要与Customer中的属性对应,在eclipse中编写的时候如果没有对应的属性eclipse也会提示你属性找不到。

这里只定义了一个接口,并没有具体实现,包括findByLastName方法,为什么?这就是Spring Data Jpa的魅力之处,因为它致力于在运行程序的时候从Repository接口处自动为它创建相应实现类。通过@EnableJpaRepositories注解实现。

Application.java应用主类,Spring Data JPA测试类

package hello;

import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2;

import java.util.List;

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

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@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(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }


    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
        List 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 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();
    }

}

@EnableJpaRepositories:告诉JPA找到继承了repository的接口,并为它创建相应的实现类,JpaRepository也继承了repository。 

DataSource:声明一个存储对象的数据库 

LocalContainerEntityManagerFactoryBean:对象的操作类,通过lef.setPackagesToScan("hello");避免了创建 persistence.xml ,它告诉JPA到hello包下面找bean类 

JpaVendorAdapter:为LocalContainerEntityManagerFactoryBean定义了基于hibernate的JPA适配器 

PlatformTransactionManager:用于处理事务持久化 

最后运行程序,结果如下:

Customers found with findAll():
-------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']

Customer found with findOne(1L):
--------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']

Customer found with findByLastName('Bauer'):
--------------------------------------------
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']
该项目需要用到的jar包,通过maven的pom.xml获得

pom.xml

<<span class="title">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">
    <<span class="title">modelVersion>4.0.0</<span class="title">modelVersion>
    <<span class="title">groupId>org.springframework</<span class="title">groupId>
    <<span class="title">artifactId>gs-accessing-data-jpa</<span class="title">artifactId>
    <<span class="title">version>0.1.0</<span class="title">version>

    <<span class="title">parent>
        <<span class="title">groupId>org.springframework.boot</<span class="title">groupId>
        <<span class="title">artifactId>spring-boot-starter-parent</<span class="title">artifactId>
        <<span class="title">version>0.5.0.M4</<span class="title">version>
    </<span class="title">parent>

    <<span class="title">dependencies>
        <<span class="title">dependency>
            <<span class="title">groupId>org.springframework</<span class="title">groupId>
            <<span class="title">artifactId>spring-orm</<span class="title">artifactId>
        </<span class="title">dependency>
        <<span class="title">dependency>
            <<span class="title">groupId>org.springframework.data</<span class="title">groupId>
            <<span class="title">artifactId>spring-data-jpa</<span class="title">artifactId>
        </<span class="title">dependency>
        <<span class="title">dependency>
            <<span class="title">groupId>org.springframework.boot</<span class="title">groupId>
            <<span class="title">artifactId>spring-boot-starter-web</<span class="title">artifactId>
        </<span class="title">dependency>
        <<span class="title">dependency>
            <<span class="title">groupId>org.hibernate</<span class="title">groupId>
            <<span class="title">artifactId>hibernate-entitymanager</<span class="title">artifactId>
        </<span class="title">dependency>
        <<span class="title">dependency>
            <<span class="title">groupId>com.h2database</<span class="title">groupId>
            <<span class="title">artifactId>h2</<span class="title">artifactId>
        </<span class="title">dependency>
    </<span class="title">dependencies>

    <<span class="title">properties>
        
        <<span class="title">project.build.sourceEncoding>UTF-8</<span class="title">project.build.sourceEncoding>
        <<span class="title">project.reporting.outputEncoding>UTF-8</<span class="title">project.reporting.outputEncoding>
        <<span class="title">start-class>hello.Application</<span class="title">start-class>
    </<span class="title">properties>

    <<span class="title">build>
        <<span class="title">plugins>
            <<span class="title">plugin> 
                <<span class="title">artifactId>maven-compiler-plugin</<span class="title">artifactId> 
                <<span class="title">version>2.3.2</<span class="title">version> 
            </<span class="title">plugin>
            <<span class="title">plugin>
                <<span class="title">groupId>org.springframework.boot</<span class="title">groupId>
                <<span class="title">artifactId>spring-boot-maven-plugin</<span class="title">artifactId>
            </<span class="title">plugin>
        </<span class="title">plugins>
    </<span class="title">build>

    <<span class="title">repositories>
        <<span class="title">repository>
            <<span class="title">id>spring-snapshots</<span class="title">id>
            <<span class="title">name>Spring Snapshots</<span class="title">name>
            <<span class="title">url>http://repo.spring.io/libs-snapshot</<span class="title">url>
            <<span class="title">snapshots>
                <<span class="title">enabled>true</<span class="title">enabled>
            </<span class="title">snapshots>
        </<span class="title">repository>
        <<span class="title">repository>
            <<span class="title">id>spring-milestones</<span class="title">id>
            <<span class="title">name>Spring Milestones</<span class="title">name>
            <<span class="title">url>http://repo.spring.io/libs-milestone</<span class="title">url>
            <<span class="title">snapshots>
                <<span class="title">enabled>false</<span class="title">enabled>
            </<span class="title">snapshots>
        </<span class="title">repository>
        <<span class="title">repository>
            <<span class="title">id>org.jboss.repository.releases</<span class="title">id>
            <<span class="title">name>JBoss Maven Release Repository</<span class="title">name>
            <<span class="title">url>https://repository.jboss.org/nexus/content/repositories/releases</<span class="title">url>
            <<span class="title">snapshots>
                <<span class="title">enabled>false</<span class="title">enabled>
            </<span class="title">snapshots>
        </<span class="title">repository>
    </<span class="title">repositories>

    <<span class="title">pluginRepositories>
        <<span class="title">pluginRepository>
            <<span class="title">id>spring-snapshots</<span class="title">id>
            <<span class="title">name>Spring Snapshots</<span class="title">name>
            <<span class="title">url>http://repo.spring.io/libs-snapshot</<span class="title">url>
            <<span class="title">snapshots>
                <<span class="title">enabled>true</<span class="title">enabled>
            </<span class="title">snapshots>
        </<span class="title">pluginRepository>
        <<span class="title">pluginRepository>
            <<span class="title">id>spring-milestones</<span class="title">id>
            <<span class="title">name>Spring Milestones</<span class="title">name>
            <<span class="title">url>http://repo.spring.io/libs-milestone</<span class="title">url>
            <<span class="title">snapshots>
                <<span class="title">enabled>false</<span class="title">enabled>
            </<span class="title">snapshots>
        </<span class="title">pluginRepository>
    </<span class="title">pluginRepositories>

</<span class="title">project>

 

这是从spring官网学习的,有不对的地方欢迎指导 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值