SpringDataJPA的实现

2020-04-08  本文已影响0人  煗NUAN

SpringDataJPA的实现

1.pom文件依赖添加

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--为了@ Resource注解-->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.28</version>
        </dependency>
        <!--
            添加spring-data-jpa的依赖
        -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <!--
            spring-data-jpa依赖于hibernate-entitymanager
        -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

2.配置数据源

url=jdbc:mysql://localhost:3307/jpaDatabase?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
driver=com.mysql.cj.jdbc.Driver
uname=root
upass=root
maxActive=50
minIdle=1

3.配置spring-jpa.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:context="http://www.springframework.org/schema/context"
       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/context
       http://www.springframework.org/schema/context/spring-context.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">

    <context:property-placeholder location="db.properties" />

    <!--包扫描-->
    <context:component-scan base-package="com.jpa.dao" />
    <context:component-scan base-package="com.jpa.service" />

    <!--配置druid数据源-->
    <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${url}" />
        <property name="driverClassName" value="${driver}" />
        <property name="username" value="${uname}" />
        <property name="password" value="${upass}" />
    </bean>

    <!--配置HibernateJpaVendorAdapter,用来分别设置数据库的方言和是否显示SQL语句-->
    <bean id="hjva" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <!--<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />--><!--无法直接操作数据库-->
        <property name="databasePlatform" value="org.hibernate.dialect.MySQL57InnoDBDialect" />
        <property name="showSql" value="true"/>
    </bean>

    <!--配置EntityManagerFactoryBean-->
    <bean id="emfb" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="ds" />
        <property name="packagesToScan" value="com.jpa.entity" />
        <property name="jpaVendorAdapter" ref="hjva" />
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.format_sql">true</prop>
                <!--
                    使用hibernate.hbm2ddl.auto属性来根据需要动态创建数据库的表结构
                    create:表示启动的时候先drop,再create
                    create-drop: 也表示创建,只不过再系统关闭前执行一下drop
                    update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
                    validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
                -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

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

    <!--配置事务的注册驱动-->
    <tx:annotation-driven proxy-target-class="false" transaction-manager="jtm" />
    <jpa:repositories base-package="com.jpa.dao" entity-manager-factory-ref="emfb" transaction-manager-ref="jtm" />

</beans>

4.entity层的Javabean

package com.jpa.entity;

import lombok.Data;
import javax.persistence.*;

@Data
@Entity
@Table(name = "employee")
public class Empl {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //GenerationType.IDENTITY设置自增
    @Column(name = "eid",unique = true,nullable = false,length = 5)
    private int eid;
    /**
     * Column注解的各个属性值说明:
     * name用来指定该属性所对应的列名,默认与属性名一致
     * unique为true代表该属性生成的字段唯一,默认不唯一
     * nullable为false不允许为空,默认运行为空
     * length可以给字段指定长度,默认为255
     */

    @Column(name = "e_name",unique = true,nullable = false,length = 30)
    private String eName;

    @Column(name = "e_password",nullable = false,length = 30)
    private String ePassword;

    @Column(name = "age",nullable = false,length = 5)
    private int age;
}

5.dao层接口

package com.jpa.dao;

import com.jpa.entity.Empl;
import org.springframework.data.jpa.repository.JpaRepository;

import java.io.Serializable;
import java.util.List;

public interface IEmployeeDao extends JpaRepository<Empl, Serializable> {

    //本身集成了单表的增删改查

    /**
    * Description: 添加其他自定义的方法 ,方法名一定要是findBy**形式
    * @date: 2020/4/6 14:27
    * @param:
    * @return:
    */

    //根据用户名查询信息
    List<Empl> findByEName(String eName);

    //根据用户名和密码查询用户
    List<Empl> findByENameAndEPassword(String name,String password);

    //根据用户名或者密码查询用户
    List<Empl> findByENameOrEPassword(String name,String password);

    //查询年龄在16-20之间的信息
    List<Empl> findByAgeBetween(int min,int max);

    //年龄大于18的信息
    List<Empl> findByAgeGreaterThan(int age);

    //模糊查询
    List<Empl> findByENameLike(String name);

    //查询名字,并根据年龄排序
    List<Empl> findByENameOrderByAge(String name);

}

6.service层的接口

package com.jpa.service;

import com.jpa.entity.Empl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;


public interface IEmployeeService {
    void saveEmpl(Empl empl);

    /**
     * Description: 添加其他自定义的方法
     * @date: 2020/4/6 14:27
     * @param:
     * @return:
     */

    //根据用户名查询信息
    List<Empl> findByEName(String eName);

    //根据用户名和密码查询用户
    List<Empl> findByENameAndEPassword(String name,String password);

    //根据用户名或者密码查询用户
    List<Empl> findByENameOrEPassword(String name,String password);

    //查询年龄在16-20之间的信息
    List<Empl> findByAgeBetween(int min,int max);

    //年龄大于18的信息
    List<Empl> findByAgeGreaterThan(int age);

    //模糊查询
    List<Empl> findByENameLike(String name);

    //查询名字,并根据年龄排序
    List<Empl> findByENameOrderByAge(String name);

    //查询所有内容并分页
    Page<Empl> findAll(Pageable pageable);
}

7.service层的实现类

package com.jpa.service.impl;

import com.jpa.dao.IEmployeeDao;
import com.jpa.entity.Empl;
import com.jpa.service.IEmployeeService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class EmployeeService implements IEmployeeService {

    @Resource
    private IEmployeeDao employeeDao;

    @Override
    public void saveEmpl(Empl empl) {
        employeeDao.saveAndFlush(empl);
    }

    @Override
    public List<Empl> findByEName(String eName) {
        return employeeDao.findByEName(eName);
    }

    @Override
    public List<Empl> findByENameAndEPassword(String name, String password) {
        return employeeDao.findByENameAndEPassword(name, password);
    }

    @Override
    public List<Empl> findByENameOrEPassword(String name, String password) {
        return employeeDao.findByENameOrEPassword(name, password);
    }

    @Override
    public List<Empl> findByAgeBetween(int min, int max) {
        return employeeDao.findByAgeBetween(17,19);
    }

    @Override
    public List<Empl> findByAgeGreaterThan(int age) {
        return employeeDao.findByAgeGreaterThan(17);
    }

    @Override
    public List<Empl> findByENameLike(String name) {
        return employeeDao.findByENameLike(name);
    }

    @Override
    public List<Empl> findByENameOrderByAge(String name) {
        return employeeDao.findByENameOrderByAge(name);
    }

    @Override
    public Page<Empl> findAll(Pageable pageable) {
        return employeeDao.findAll(pageable);
    }
}

8.service层单元测试

package service;

import com.jpa.entity.Empl;
import com.jpa.service.IEmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;


@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration("classpath:spring-jpa.xml")
public class EmplServiceTest {

    @Resource
    private IEmployeeService employeeService;

    @Test
    public void saveTest(){
        Empl empl=new Empl();
        empl.setEName("root");
        empl.setEPassword("root");
        empl.setAge(18);
        employeeService.saveEmpl(empl);
    }

    @Test
    public void getEmplByNameTest(){
        List<Empl> root = employeeService.findByEName("root");
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getEmplByNameAndPasswordTest(){
        List<Empl> root =employeeService.findByENameAndEPassword("admin","admin");
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getEmplByENameOrEPasswordTest(){
        List<Empl> root =employeeService.findByENameOrEPassword("root","admin");
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getAgeBetweenTest(){
        List<Empl> root =employeeService.findByAgeBetween(0,100);
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getAgeMoreThanTest(){
        List<Empl> root =employeeService.findByAgeGreaterThan(17);
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getENameLikeTest(){
        String name="r";
        List<Empl> root =employeeService.findByENameLike("%"+name+"%");
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }


    @Test
    public void getENameOrderByAgeTest(){
        
        List<Empl> root =employeeService.findByENameOrderByAge("root");
        for (Empl empl : root) {
            System.out.println(empl);
        }
    }

    @Test
    public void getAllByPageTest(){
        //注意pageable的包   注意:页数是从0开始的,不是1
        Pageable pageable= (Pageable) new PageRequest(0,2);
        Page<Empl> page = employeeService.findAll(pageable);

        List<Empl> list=page.getContent();

        for (Empl empl : list) {
            System.out.println(empl);
        }


    }
}

9.目录结构

jpa项目目录结构.jpg
上一篇下一篇

猜你喜欢

热点阅读