0


SpringDataJPA教程 三种配置方式

本教程分为三类配置

1.spring xml配置文件方式
2.spring 注解配置方式
3.springboot 配置方式

1.xml配置方式

引入maven依赖

  <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.33.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.19</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.在resources文件夹下创建application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
       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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
https://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <jpa:repositories base-package="com.yujie.dao" entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
    <!--创建实体工厂-->
    <bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--设置jpa实现方式HibernateJ-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--如果表不存在就创建,存在就不创建-->
                <property name="generateDdl" value="true"></property>
                <property name="showSql" value="true"></property>
            </bean>
        </property>
        <!--扫描的实体包位置-->
        <property name="packagesToScan" value="com.yujie.model"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="jdbc:mysql:///jpa"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123123"></property>
    </bean>

    <!--告诉事务工厂是谁-->
    <bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>
    <!--启动注解方式事务-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

3.创建实体类

package com.yujie.model;

import javax.persistence.*;

@Entity
@Table(name = "t_customer")
public class Customer{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String cusName;

    set..
    get..
}

4.创建dao

package com.yujie.dao;

import com.yujie.model.Customer;
import org.springframework.data.repository.PagingAndSortingRepository;
//PagingAndSortingRepository<实体类,主键类型> 
public interface CustomerDao extends PagingAndSortingRepository<Customer,Integer> {
}

5.进行测试

package com.yujie;

import com.yujie.dao.CustomerDao;
import com.yujie.model.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Optional;

@ContextConfiguration("classpath:application.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class JpaXMLTest {
    @Autowired
    CustomerDao customerDao;

    @Test
    public void save(){
        Customer customer = new Customer();
        customer.setCusName("王大宝2");
        customerDao.save(customer);
    }

    @Test
    public void delete(){
        //删除方式一
        Customer customer = new Customer();
        customer.setId(10);
        customerDao.delete(customer);
        //删除方式二
        //customerDao.deleteById(10);
    }

    @Test
    public void update(){
        Optional<Customer> byId = customerDao.findById(1);
        Customer customer = byId.get();
        customer.setCusName("老六");
        customerDao.save(customer);
    }

    @Test
    public void find(){
        Optional<Customer> byId = customerDao.findById(10);
        System.out.println(byId.get());
    }

    //分页查询
    @Test
    public void limitFind(){
        Page<Customer> page = customerDao.findAll(PageRequest.of(2, 2));
        //总条数
        long totalElements = page.getTotalElements();
        //总页数
        int totalPages = page.getTotalPages();
        //返回的实体对象
        List<Customer> content = page.getContent();
        System.out.println(content);
        //当前页数
        int number = page.getNumber();
    }
    //查询查询
    @Test
    public void sort(){
        //倒叙排序
        Sort.TypedSort<Customer> sort = Sort.sort(Customer.class);
        Sort descending = sort.by(Customer::getId).descending();
        Iterable<Customer> all = customerDao.findAll(descending);
        for (Customer customer : all) {
            System.out.println(customer);
        }
    }

}

2.方式二spring 注解进行配置

1.创建配置类

package com.yujie.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.yujie.dao")
@EnableTransactionManagement
public class SpringDataJPAConfig {

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("123123");
        dataSource.setUrl("jdbc:mysql:///jpa");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.yujie.model");
        factory.setDataSource(dataSource());
        return factory;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }

}

2.进行测试,注意测试类和上面的不一样

@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class JpaAnnotaionTest {
    @Autowired
    CustomerDao customerDao;

    @Test
    public void save(){
        Customer customer = new Customer();
        customer.setCusName("王大宝2");
        customerDao.save(customer);
    }
}

3.springboot 配置方式

等待更新..

复杂查询可以自定义方法,书写JPQL

1.在接口上定义方法

package com.yujie.dao;

import com.yujie.model.Customer;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
import java.util.List;

public interface CustomerDao extends PagingAndSortingRepository<Customer,Integer> {
    //通过占位符+索引位置 注意:?索引和:属性 在一个方法上,要么统一使用?索引,要么统一使用:属性,混合使用会报错
    @Query("FROM Customer WHERE id=?1 OR cusName=?2")
    public List<Customer> findCustomerByIdOrName(Integer id666, String cusName);

    //通过@Param注解
    @Query("FROM Customer WHERE id=:id")
    public Customer findCustomerById(@Param("id") Integer id666);

    //修改和删除要加上Modifying以及Transactional注解 JPQL不支持插入,可以使用原始SQL
    @Transactional
    @Modifying
    @Query("UPDATE  Customer SET cusName=?1 WHERE id=?2")
    public Integer updateCustomer( String cusName,Integer id);

    //通过原始SQL查询
    @Query(value = "SELECT * FROM t_customer WHERE id=:id",nativeQuery = true)
    public Customer findCustomerByIdSQL(@Param("id") Integer id666);

    //通过原始SQL更新
    @Transactional
    @Modifying
    @Query(value = "UPDATE t_customer SET cusName=?1 WHERE id=?2 ",nativeQuery = true)
    public Integer updateCustomerSQL(String name,Integer id666);
}

2.测试自定义的方法

@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class JpaTest {
    @Autowired
    CustomerDao customerDao;
     @Test
    public void findCustomerByIdOrName(){
        List<Customer> customers= customerDao.findCustomerByIdOrName(null,"老六");
        System.out.println(customers);
    }

    @Test
    public void findCustomerById(){
        Customer customer = customerDao.findCustomerById(1);
        System.out.println(customer);
    }

    @Test
    public void updateCustomer(){
        Integer count = customerDao.updateCustomer("老六啊", 1);
        System.out.println(count);
    }

    @Test
    public void findCustomerByIdSQL(){
        Customer customer = customerDao.findCustomerByIdSQL( 1);
        System.out.println(customer);
    }

    @Test
    public void updateCustomerSQL(){
        Integer customer = customerDao.updateCustomerSQL( "小王八",1);
        System.out.println(customer);
    }

   @Test
    public void saveCustomer(){
        Integer count = customerDao.saveCustomer("小贱人");
        System.out.println(count);
    }
}
标签: spring spring boot java

本文转载自: https://blog.csdn.net/qq_42058998/article/details/125057395
版权归原作者 请把小熊还给我& 所有, 如有侵权,请联系我们删除。

“SpringDataJPA教程 三种配置方式”的评论:

还没有评论