SpringbootData中实现JPA

springDataJpa使用

0、引入依赖jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>test_code</artifactId>
        <groupId>city.albert</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>jpa</artifactId>
    <packaging>war</packaging>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--jpa相关-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.el/el-api -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.1.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!--hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>5.3.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.3.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>5.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>jpa</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <encoding>utf-8</encoding>
                    <source>1.8</source>
                    <target>1.8</target>
                    <!--编译时候记录形参-->
                    <compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>central</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <layout>default</layout>
            <!-- 是否开启发布版构件下载 -->
            <releases>
                <enabled>true</enabled>
            </releases>
            <!-- 是否开启快照版构件下载 -->
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>
View Code

 

1、配置xml
<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <context:component-scan base-package="city.albert"/>

    <!--引入配置文件-->
    <context:property-placeholder location="classpath*:jdbc.properties"/>

    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${classDr}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </bean>
    <!--jpa配置-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--设置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--扫苗包-->
        <property name="packagesToScan" value="city.albert.entity"/>
        <!--jpa实现类-->
        <property name="persistenceProvider" >
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>
        <!--jpa方言配置 不同jpa类似于事务的实现是不同的,应与上面保持一致-->
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        </property>

        <!--配置具体实现的属性-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--具体映射-->
                <!--配置数据表是否自动创建  通过实体类与数据表之间的映射-->
                <property name="generateDdl" value="false"/>
                <!--指定数据库-->
                <property name="database" value="MYSQL"/>
                <!--指定数据库方言,用于拼接sql-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                <!--日志是否打印sql-->
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <!--配置jpa的事务管理-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!--配置jpa扫描包-->
    <jpa:repositories base-package="city.albert.dao"
                      entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>


    <!--声明事务-->
    <tx:annotation-driven/>
</beans>

 

2、配置dao接口
package city.albert.dao;

import city.albert.entity.ResumeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

/**
 * @author niunafei
 * @function
 * @email niunafei0315@163.com
 * @date 2020/6/25  8:52 PM
 * <p>
 * JpaRepository 封装基本的curd操作
 * <p>
 * JpaSpecificationExecutor 封装了分页,排序等复杂操作
 * <p>
 * 查询方式
 * 1、findById或者findOne等jpa定义的方式进行查询
 * 2、引入jps语言查询例如:queryById
 * 3、使用原生语言进行sql查询,需要自己写sql ,例如:queryByLike
 * 4、在接口中自己写接口,通过jpa的编写规则进行写,例如:findByNameLikeAndAddressLike
 * 5、动态查询
 * -----条件的不同sql不同
 * -----Optional<T> findOne(@Nullable Specification<T> var1); //根据条件进行查询单个对象
 * -----List<T> findAll(@Nullable Specification<T> var1);  //根据条件进行查询所有
 * -----Page<T> findAll(@Nullable Specification<T> var1, Pageable var2);  //根据条件进行分页查询
 * -----List<T> findAll(@Nullable Specification<T> var1, Sort var2);  //根据条件进行查询,并且排序
 * -----long count(@Nullable Specification<T> var1); //根据条件进行查询总个数
 */
public interface ResumeDao extends JpaRepository<ResumeEntity, Long>, JpaSpecificationExecutor<ResumeEntity> {


    /**
     * 基于jpa上的查询
     *
     * @param id
     * @return
     */
    @Query("from ResumeEntity where id=?1")
    ResumeEntity queryById(Long id);

    /**
     * 使用原生sql  进行查询
     *
     * @param name
     * @param address
     * @return
     */
    @Query(value = "select * from tb_resume where name like ?1 AND address like ?2  ", nativeQuery = true)
    ResumeEntity queryByLike(String name, String address);


    /**
     * 按照规则名进行查询
     * 按照name和addree模糊查询
     * 开头findBy
     * 属性名首字母大写 +查询方式
     *
     * @param name
     * @param address
     * @return
     */
    ResumeEntity findByNameLikeAndAddressLike(String name, String address);

}

 

4、配置实体类
package city.albert.entity;

import javax.persistence.*;

/**
 * 简历实体类 简历属性与字段映射关系
 *
 * @author niunafei
 * @function
 * @email niunafei0315@163.com
 * @date 2020/6/25  8:09 PM
 * <p>
 * 1、Entity声明是一个实体类对象
 * 2、Table声明数据表与实体的对应关系
 * 2、@Id  指定主键
 * 3、@GeneratedValue  指定主键策略
 * GenerationType.TABLE:使用一个特定的数据库表格来保存主键。
 * GenerationType.SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。
 * GenerationType.IDENTITY:主键由数据库自动生成(主要是自动增长型)
 * GenerationType.AUTO:主键由程序控制。
 * 3、@Column  字段属性对应关系
 */
@Entity
@Table(name = "tb_resume")
public class ResumeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "phone")
    private String phone;
    @Column(name = "address")
    private String address;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "ResumeEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

 

5、测试
package city.albert;

import city.albert.dao.ResumeDao;
import city.albert.entity.ResumeEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Optional;

/**
 * @author niunafei
 * @function
 * @email niunafei0315@163.com
 * @date 2020/6/25  9:10 PM
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class JpaTest {

    @Autowired
    private ResumeDao dao;


    /**
     * 查询
     * 1、findById或者findOne等jpa定义的方式进行查询
     * 2、引入jps语言查询例如:queryById
     * 3、使用原生语言进行sql查询,需要自己写sql ,例如:queryByLike
     * 4、在接口中自己写接口,通过jpa的编写规则进行写,例如:findByNameLikeAndAddressLike
     * 5、动态查询
     * -----条件的不同sql不同
     */
    @Test
    public void test() {

        findById();
        findOne();
        saveOrUpdate();
        findAll();

        //查询jpa语法
        ResumeEntity entity = dao.queryById(2L);
        System.out.println(entity);

        //原生sql,手动编写
        ResumeEntity query = dao.queryByLike("%3%", "%3%");
        System.out.println(query);

        //根据规则进行查询
        ResumeEntity f = dao.findByNameLikeAndAddressLike("%3%", "%3%");
        System.out.println(f);

        //实现动态sql拼接
        Specification<ResumeEntity> specification = new Specification<ResumeEntity>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<ResumeEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                //获取属性
                Path<Object> name = root.get("name");
                Path<Object> address = root.get("address");
                //构建单个查询的条件
                Predicate predicate = criteriaBuilder.equal(name, "李2");
                //需要指定类型
                Predicate like = criteriaBuilder.like(address.as(String.class), "%2%");
                //整合查询条件
                return criteriaBuilder.and(predicate, like);
            }
        };
        Optional<ResumeEntity> one = dao.findOne(specification);
        System.out.println("动态拼接:" + one.get());

        //排序与分页处理
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        List<ResumeEntity> all = dao.findAll(sort);
        for (ResumeEntity d : all) {
            System.out.println("排序" + d);
        }

        //分页
        Pageable pageable= PageRequest.of(1,2);
        Page<ResumeEntity> page = dao.findAll(pageable);
        for (ResumeEntity resumeEntity : page.getContent()) {
            System.out.println("分页:" + resumeEntity);
        }
        System.out.println(page.getTotalElements()+"-"+page.getNumber()+"-"+page.getSize());
    }


    public void findById() {
        Optional<ResumeEntity> byId = dao.findById(1L);
        ResumeEntity resumeEntity = byId.get();
        System.out.println(resumeEntity);
    }

    public void findOne() {
        ResumeEntity entity = new ResumeEntity();
        entity.setId(1L);
        Example<ResumeEntity> of = Example.of(entity);
        Optional<ResumeEntity> byId = dao.findOne(of);
        ResumeEntity resumeEntity = byId.get();
        System.out.println(resumeEntity);
    }

    public void saveOrUpdate() {
        ResumeEntity entity = new ResumeEntity();
        entity.setAddress("测试测试");
        entity.setName("测试测试");
        entity.setPhone("12345678901");
        ResumeEntity save = dao.save(entity);
        System.out.println(save.toString() + "----------------" + entity.toString());

        save.setName("2342jhbhj");
        ResumeEntity save1 = dao.save(save);
        System.out.println(save1.toString() + "----------------" + save.toString());

        //删除
        dao.deleteById(save1.getId());
    }

    public void findAll() {
        List<ResumeEntity> all = dao.findAll();
        for (ResumeEntity d : all) {
            System.out.println(d);
        }
    }

}

 

posted @ 2020-06-30 12:14  albert飞的博客  阅读(267)  评论(0编辑  收藏  举报