Spring 5框架之 Spring-Data-Jpa入门之HelloWorld (十)

1. 前言

Spring 为JPA提供了很好的支持。Spring Data项目提供了一个名为Spring Data JPA ,提供了存储数据库的概念与规范以及对查询特定语言(QueryDSL)的支持。

2.HelloWorld

引入核心的pom依赖如下:

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>2.2.6.RELEASEversion>
        dependency>

在Spring中如果使用JPA 需要有以下几个步骤:

  1. 配置数据源连接池
  2. 配置JPA的 EntityManagerFactory
  3. 配置事务管理器
  4. 配置Spring Data

首先配置一个jdbc.properties 文件,其文件内容如下所示:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8&autoReconnect=true
jdbc.username=root
jdbc.password=123456

其完整的配置内容的xml如下所示:

  <context:property-placeholder location="day6/jdbc.properties"/>
        
        <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
                <property name="driverClassName" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
        bean>

        
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
           
                <property name="dataSource" ref="dataSource"/>     
          
                <property name="packagesToScan" value="com.codegeek.ioc.day6.model"/>  
                
                <property name=" ">
                        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                                
                                <property name="generateDdl" value="true" />
                                <property name="database" value="MYSQL" />
                                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
                                <property name="showSql" value="true" />
                        bean>
                property>
        bean>
        
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
                <property name="entityManagerFactory" ref="entityManagerFactory"/>   
        bean>
        
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <tx:attributes>
                        <tx:method name="get*" read-only="true"/>
                        <tx:method name="find*" read-only="true"/>
                        <tx:method name="*" propagation="REQUIRED"/>
                tx:attributes>
        tx:advice>

        
        <aop:config>
                <aop:pointcut id="pointcut" expression="execution(* com.codegeek.ioc.day6.service.*.*(..))"/>
                <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
        aop:config>
        
        <jpa:repositories base-package="com.codegeek.ioc.day6.dao"
                          transaction-manager-ref="transactionManager"
                          entity-manager-factory-ref="entityManagerFactory"
        />

接下来我们创建相应的实体对象,其包结构如下所示:
Spring 5框架之 Spring-Data-Jpa入门之HelloWorld (十)_第1张图片

  • controller
@RestController
public class CompanyController {
    @Autowired
    private CompanyService companyService;


    @RequestMapping(value = "/saveCompany" )
    public ResponseEntity<String> saveCompany(@RequestBody Company company) {
        companyService.save(company);
        return ResponseEntity.ok("保存成功");
    }
}
  • Service
public interface CompanyService {

    void  save(Company company);
}

@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyDao companyDao;

    @Override
    public void save(Company company) {
        companyDao.save(company);
    }
}
  • model
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "t_company")
public class Company {
    @Column(name = "t_companyName")
    private String companyName;

    @Column(name = "t_createTime")
    private Date createTime;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
    @JsonManagedReference
    private List<Employee> employees;
    @Column(name = "t_companyAddress")
    private String companyAddress;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "t_company_id")
    private Integer id;
}


@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "t_employee")
public class Employee {
    @Column(name = "t_name")
    private String name;
    @Column(name = "t_salary")
    private Double salary;
    @Column(name = "t_phoneNumber")
    private Integer phoneNumber;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "t_employee_id")
    private Integer id;
    @ManyToOne
    @JoinColumn(name = "t_company_id")
    @JsonBackReference
    private Company company;
    @Column(name="t_gender")
    private String gender;
}

  • dao
@Repository
public interface CompanyDao  extends JpaRepository<Company, Integer> {
  
}

然后我们在Idea中成功启动项目后会成功创建数据库表如下所示:

然后我们打开postman向接口发送如下数据:

{"companyName":"google","createTime":1589459522947,"employees":[{"name":"张三","salary":5000.0,"phoneNumber":123456789,"gender":"男"},{"name":"小红","salary":9000.0,"phoneNumber":987452621,"gender":"女"}],"companyAddress":"America"}

Spring 5框架之 Spring-Data-Jpa入门之HelloWorld (十)_第2张图片
查看Company表如下所示:
Spring 5框架之 Spring-Data-Jpa入门之HelloWorld (十)_第3张图片
查看emplyee表如下所示;
Spring 5框架之 Spring-Data-Jpa入门之HelloWorld (十)_第4张图片
到这里一个简单的Spring Data JPA 的入门demo已经结束,下一篇我们将继续介绍Spring Data Jpa的使用方法。

你可能感兴趣的:(Spring)