spring 入门之 spring-data-jpa

在 IDEA 中,新建工程

  • 工程类型为 maven
  • 选中 create from archetype ,选择 quickstart 模板
  • 填写项目名称,完成创建

pom.xml 中添加 spring-data-jpa 依赖

  • jpa vendor 使用 hibernate
  • 数据库使用 H2
<groupId>org.springframework.data</groupId>
  <artifactId>spring-data-jpa</artifactId>
  <version>1.11.1.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.2.8.Final</version>
</dependency>

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <version>1.4.193</version>
</dependency>

创建 spring context 和数据源

resources/spring-beans.xml

  • 文件名任意,需要在 main 函数中指定该文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml");
  • 自动生成的 beans 标签可能会出错,需要仔细检查。
  • 创建相关 bean,按依赖关系排序

    DataSource: 指定数据源为 schema.sql
    JpaVendorAdapter: 实例化 HibernateJpaVendorAdapter, 指定数据库类型为 H2
    EntityManagerFactory: 依赖 DatasSource, JpaVendorAdapter
    TransactionManager: 依赖 EntityManagerFactory
    
  • context:component-scan= 指定扫描注解的包路径
  • jpa:repositories 指定 DAO 包路径, 依赖 EntityManagerFactory 和 TransactionManager
  • tx:annotation-driven 指定 transaction 管理器
  • 最后新建 service bean, 在 main 函数中通过 context.getBean 得到该 bean
<?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:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/data/jpa
       http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
       http://www.springframework.org/schema/jdbc
       http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

  <context:component-scan base-package="com.litchi"/>

  <bean id="transactionManager" 
        class="org.springframework.orm.jpa.JpaTransactionManager"
        p:entityManagerFactory-ref="emf"/>
  <tx:annotation-driven transaction-manager="transactionManager" />

  <bean id="jpaVendorAdapter" 
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="H2"/>
    <property name="showSql" value="true"/>
    <property name="generateDdl" value="false"/>
    <property name="databasePlatform" value="org.hibernate.dialect.H2Dialect"/>
  </bean>

  <jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="schema.sql"/>
  </jdbc:embedded-database>

  <bean id="emf" 
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:dataSource-ref="dataSource"
        p:jpaVendorAdapter-ref="jpaVendorAdapter"
        p:packagesToScan="com.litchi"/>

  <jpa:repositories base-package="com.litchi"
                    entity-manager-factory-ref="emf"
                    transaction-manager-ref="transactionManager">
  </jpa:repositories>

  <bean id="personService" class="com.litchi.PersonService"/>
</beans>

resources/schema.sql

drop table if exists Person;
create table Person (
  id identity,
  firstName varchar(25) not null,
);

新建代码文件

实体类 com.litchi.Person

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String firstName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

DAO 类 com.litchi.PersonDao

@Repository
public interface PersonDao extends JpaRepository<Person, Integer> {
    Person save(Person person);

    List<Person> findAll();
}

Service 类 com.litchi.PersonService

@Service
public class PersonService {
    @Autowired(/*required = true*/)
    private PersonDao personDao;

    @Transactional
    public void createPerson(String name) {
        Person person = new Person();
        person.setFirstName(name);
        personDao.save(person);
    }

    public void PrintAllPerson() {
        List<Person> persons = personDao.findAll();
        System.out.println("Count: " + persons.size());
        for (Person p : persons) {
            System.out.println(p.getId() + " : " + p.getFirstName());
        }
    }

}

Main 函数

public static void main( String[] args )
{
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml");
    PersonService service = (PersonService) context.getBean("personService");
    service.createPerson("FengJian");
    service.PrintAllPerson();
    System.out.println( "Hello World!" );
}

新建运行配置

  • 运行类型为 Application
  • Main class 为 com.litchi.App