Spring Data JPA

 

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

 

 

posted @ 2019-02-17 20:23  小霸王丶  阅读(110)  评论(0编辑  收藏  举报