SpringbootData中实现JPA

2020-12-24 00:29

阅读:686

标签:tomcat7   date()   jpa   图片   mod   pil   onclick   lse   open   

 

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_codeartifactId>
        groupId>city.albertgroupId>
        version>1.0-SNAPSHOTversion>
    parent>
    modelVersion>4.0.0modelVersion>

    artifactId>jpaartifactId>
    packaging>warpackaging>


    dependencies>
        dependency>
            groupId>junitgroupId>
            artifactId>junitartifactId>
            version>4.12version>
        dependency>

        
        dependency>
            groupId>org.springframework.datagroupId>
            artifactId>spring-data-jpaartifactId>
            version>2.1.9.RELEASEversion>
        dependency>
        
        dependency>
            groupId>javax.elgroupId>
            artifactId>javax.el-apiartifactId>
            version>3.0.0version>
        dependency>
        
        dependency>
            groupId>javax.elgroupId>
            artifactId>el-apiartifactId>
            version>2.2version>
        dependency>

        
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-aopartifactId>
            version>5.2.5.RELEASEversion>
        dependency>
        dependency>
            groupId>org.aspectjgroupId>
            artifactId>aspectjweaverartifactId>
            version>1.9.5version>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-contextartifactId>
            version>5.2.5.RELEASEversion>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-context-supportartifactId>
            version>5.1.12.RELEASEversion>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-ormartifactId>
            version>5.1.8.RELEASEversion>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-beansartifactId>
            version>5.2.5.RELEASEversion>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-coreartifactId>
            version>5.2.5.RELEASEversion>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-testartifactId>
            version>5.2.5.RELEASEversion>
        dependency>

        
        dependency>
            groupId>org.hibernategroupId>
            artifactId>hibernate-ehcacheartifactId>
            version>5.3.10.Finalversion>
        dependency>
        dependency>
            groupId>org.hibernategroupId>
            artifactId>hibernate-entitymanagerartifactId>
            version>5.3.10.Finalversion>
        dependency>
        dependency>
            groupId>org.hibernategroupId>
            artifactId>hibernate-enversartifactId>
            version>5.3.10.Finalversion>
        dependency>

        dependency>
            groupId>mysqlgroupId>
            artifactId>mysql-connector-javaartifactId>
            version>5.1.47version>
        dependency>
        dependency>
            groupId>com.alibabagroupId>
            artifactId>druidartifactId>
            version>1.1.21version>
        dependency>
    dependencies>

    build>
        finalName>jpafinalName>
        plugins>
            plugin>
                groupId>org.apache.maven.pluginsgroupId>
                artifactId>maven-compiler-pluginartifactId>
                version>3.3version>
                configuration>
                    encoding>utf-8encoding>
                    source>1.8source>
                    target>1.8target>
                    
                    compilerArgs>
                        arg>-parametersarg>
                    compilerArgs>
                configuration>
            plugin>
            plugin>
                groupId>org.apache.tomcat.mavengroupId>
                artifactId>tomcat7-maven-pluginartifactId>
                version>2.2version>
                configuration>
                    port>8080port>
                    path>/path>
                    uriEncoding>UTF-8uriEncoding>
                    server>tomcat7server>
                configuration>
            plugin>
        plugins>
    build>

    repositories>
        repository>
            id>centralid>
            name>aliyun mavenname>
            url>http://maven.aliyun.com/nexus/content/groups/public/url>
            layout>defaultlayout>
            
            releases>
                enabled>trueenabled>
            releases>
            
            snapshots>
                enabled>falseenabled>
            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>
    
    bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        
        property name="dataSource" ref="dataSource"/>
        
        property name="packagesToScan" value="city.albert.entity"/>
        
        property name="persistenceProvider" >
            bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        property>
        
        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"/>
                
                property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                
                property name="showSql" value="true"/>
            bean>
        property>
    bean>

    
    bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        property name="entityManagerFactory" ref="entityManagerFactory"/>
    bean>

    
    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
 * 

* JpaRepository 封装基本的curd操作 *

* JpaSpecificationExecutor 封装了分页,排序等复杂操作 *

* 查询方式 * 1、findById或者findOne等jpa定义的方式进行查询 * 2、引入jps语言查询例如:queryById * 3、使用原生语言进行sql查询,需要自己写sql ,例如:queryByLike * 4、在接口中自己写接口,通过jpa的编写规则进行写,例如:findByNameLikeAndAddressLike * 5、动态查询 * -----条件的不同sql不同 * -----Optional findOne(@Nullable Specification var1); //根据条件进行查询单个对象 * -----List findAll(@Nullable Specification var1); //根据条件进行查询所有 * -----Page findAll(@Nullable Specification var1, Pageable var2); //根据条件进行分页查询 * -----List findAll(@Nullable Specification var1, Sort var2); //根据条件进行查询,并且排序 * -----long count(@Nullable Specification var1); //根据条件进行查询总个数

*/ public interface ResumeDao extends JpaRepository, JpaSpecificationExecutor { /** * 基于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
 * 

* 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 specification = new Specification() {
            @Nullable
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                //获取属性
                Path name = root.get("name");
                Path 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 one = dao.findOne(specification);
        System.out.println("动态拼接:" + one.get());

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

        //分页
        Pageable pageable= PageRequest.of(1,2);
        Page 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 byId = dao.findById(1L);
        ResumeEntity resumeEntity = byId.get();
        System.out.println(resumeEntity);
    }

    public void findOne() {
        ResumeEntity entity = new ResumeEntity();
        entity.setId(1L);
        Example of = Example.of(entity);
        Optional 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 all = dao.findAll();
        for (ResumeEntity d : all) {
            System.out.println(d);
        }
    }

}

 

SpringbootData中实现JPA

标签:tomcat7   date()   jpa   图片   mod   pil   onclick   lse   open   

原文地址:https://www.cnblogs.com/niunafei/p/13213012.html


评论


亲,登录后才可以留言!