Spring Data JPA

本文详细介绍了使用SpringDataJPA进行数据库操作的具体实现,包括service层、dao层和entity层的代码示例,以及SpringConfig配置文件的设置,展示了如何通过Repository接口执行各种数据库查询。

 

Spring Data JPA

 

service层

package the.data_jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import the.data_jpa.dao.BookDAO;
import the.data_jpa.entity.Book;

import java.util.List;
import java.util.Optional;

@Service
public class BookService {

    @Autowired
    private BookDAO bookDAO;

    public Optional<Book> getBookById(int id){
        Optional<Book> book = bookDAO.findById(id);
        return book;
    }

    public Book findByName(String name, float price){
        return bookDAO.findByNameAndPrice(name,price);
    }

    public Book findByName(String name){
        return bookDAO.findByName(name);
    }

    public List<Book> listCond(String name,float price){
        return bookDAO.findByNameOrPrice(name,price);
    }
}
View Code

 

dao层

package the.data_jpa.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import the.data_jpa.entity.Book;

import java.util.List;

public interface BookDAO extends JpaRepository<Book, Integer> {
    Book findByNameAndPrice(String name ,float price);

    List<Book> findByNameOrPrice(String name ,float price);

    Book findByName(String name);

    @Query("from Book as s where s.name like 'w%'")
    Book findsuibian();

}
View Code

 

entity层

package the.data_jpa.entity;

import javax.persistence.*;

@Entity
@Table(name = "t_book") //要和数据库表名一样
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    private String name;
    private float price;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
View Code

 

SpringConfig配置文件

package the.data_jpa;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
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.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties;

@Configuration
@ComponentScan(basePackages = "the.data_jpa")
@PropertySource("classpath:application.properties")//引入数据源
@EnableTransactionManagement//开启事务
@EnableJpaRepositories(basePackages = "the.data_jpa.dao")
public class SpringConfig {

    @Bean
    DataSource dataSource(Environment env) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(env.getProperty("jdbc.driver"));
        dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
        dataSource.setUser(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        return dataSource;
    }

    // SqlSessionFactory
    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPackagesToScan("the.data_jpa.entity");
        bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MariaDB103Dialect");
        bean.setJpaProperties(properties);

        return bean;
    }

    @Bean
    PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
View Code

 

测试代码

 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookService bean = context.getBean(BookService.class);
        //List<Book> listCond = bean.listCond("战争与和平", 111);
        //System.out.println(listCond);
        //Optional<Book> bookById = bean.getBookById(1);
        //System.out.println(bookById);
        Book byName = bean.findByName("战争与和平");
        System.out.println(byName);
View Code

 

 

转载于:https://www.cnblogs.com/gk126/p/10392490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值