SpringDataJPA开发环境的搭建

这里简单的介绍一下使用maven工程创建SpringDataJPA的开发环境的搭建

首先引入依赖

  <dependencies>
    <!-- junit单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
<!--spring使用aop需要引入的一个包-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>
    <!--mysql驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager
     这个是实体类管理
     -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.4.1.Final</version>
    </dependency>
    <!--连接池-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>2.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

    <!-- el beg 使用spring data jpa 必须引入 -->
    <dependency>
      <groupId>javax.el</groupId>
      <artifactId>javax.el-api</artifactId>
      <version>2.2.4</version>
    </dependency>

    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>javax.el</artifactId>
      <version>2.2.4</version>
    </dependency>
    <!-- el end -->

    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.20.0-GA</version>
    </dependency>
  </dependencies>

编写配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/data/jpa
       http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!--
    1.配置数据源
    2.配置entityManagerFactory对象
    3.事务
    4.jpa
    -->
    <!--1.配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///springdatajpa"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <!--2.配置entityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置jpaVendorAdapter适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL"></property>
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.qingmu.domain"></property>
    </bean>
    <!--3.配置事务-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven></tx:annotation-driven>
    <!--配置JPA-->
    <jpa:repositories base-package="com.qingmu.dao"
                      entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager">
    </jpa:repositories>
</beans>

使用JPA注解配置映射关系(在实体类中)

package com.qingmu.domain;

import javax.persistence.*;

/**
 * @Auther:qingmu
 * @Description:脚踏实地,只为出人头地
 * @Date:Created in 20:21 2019/5/15
 */
@Entity
@Table(name = "x_user")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "x_id")
    private Long id;
    @Column(name = "x_age")
    private int age;
    @Column(name = "x_name")
    private String name;

    public Long getId() {
        return id;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Customer() {
    }

    public Customer(int age, String name) {

        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

创建一个Dao层接口,并实现JpaRepositoryJpaSpecificationExecutor

提供相应的泛型

 
 
package com.qingmu.dao;

import com.qingmu.domain.Customer;

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

/**
* @Auther:qingmu
* @Description:脚踏实地,只为出人头地
* @Date:Created in 20:48 2019/5/15
*/
public interface UserDao extends JpaSpecificationExecutor<Customer>,JpaRepository<Customer,Long> {
}
 

进行测试

package com.qingmu;

import com.qingmu.dao.UserDao;
import com.qingmu.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @Auther:qingmu
 * @Description:脚踏实地,只为出人头地
 * @Date:Created in 20:49 2019/5/15
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class CustomerTest01 {
    @Autowired
    private UserDao userDao;

    @Test
    @Rollback(false)
    @Transactional
    public void saveTest(){
        Customer customer = new Customer();
        customer.setId(1L);
        customer.setName("太阳");
        customer.setAge(38);
        userDao.save(customer);
    }
    @Test
    @Rollback(false)
    @Transactional
    public void updateTest(){
        Customer customer = new Customer(37,"调养");
        customer.setId(1L);
        userDao.save(customer);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testFind1(){
        /**
         * Optional 是jdk1.8 新增的一个类  用来避免空指针的
         *
         * 自己程序中 如果养成好习惯 都会做判空运算
         *  User user=xxx();
         *  if(user!=null){
         *      //写自己的逻辑
         *  }
         * Optional 就是一个包装盒子 里面放对象
         */
        Optional<Customer> userDaoById = userDao.findById(1L);
        Customer customer = userDaoById.get();
        System.out.println(customer);
          /**if(optional.isPresent()){
          * User user = optional.get();
           * * System.out.println(user);
        }*/
        //官方 推荐使用手法
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testFind2(){
        Customer one = userDao.getOne(1L);
        System.out.println(one);
    }
    @Test
    @Transactional
    @Rollback(false)
    public void testDele(){
        Customer customer = userDao.findById(1L).get();

        userDao.delete(customer);
    }
}

猜你喜欢

转载自www.cnblogs.com/qingmuchuanqi48/p/10873080.html