1. 程式人生 > >Spring整合Hibernate實現Spring Data JPA (簡單使用)

Spring整合Hibernate實現Spring Data JPA (簡單使用)

pda artifact framework factor path sta ans 項目結構 pub

直接上代碼:

pom.xml

        <!-- hibernate start -->
        <!-- spring data jpa  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.3.RELEASE</version
> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.0.Final</version> </dependency> <!--
hibernate end -->

項目結構:

技術分享圖片

the_data_jpa 包 裏面的 各類 代碼

User

package com.oukele.the_data_jpa.entity;


import org.springframework.stereotype.Component;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int id;

    @Column(name = "userName")
    private String name;
    private String password;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

UserDao

package com.oukele.the_data_jpa.dao;

import com.oukele.the_data_jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserDao extends JpaRepository<User, Integer> {

    User findByNameAndPassword(String name,String password);


}

UserService

package com.oukele.the_data_jpa.service;

import com.oukele.the_data_jpa.dao.UserDao;
import com.oukele.the_data_jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User findNameAndPassword(String name,String password){
        return userDao.findByNameAndPassword(name, password);
    }

}

SpringConfig

package com.oukele.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.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties;

@Configuration//聲明當前配置類
@ComponentScan(basePackages = "com.oukele.the_data_jpa")// 掃描當前包 使用 spring 註解
@PropertySource("classpath:jdbc.properties")//加載 資源文件
@EnableJpaRepositories(basePackages = "com.oukele.the_data_jpa.dao")//掃描 使用 jpa 註解的接口
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("com.oukele.the_data_jpa.entity");//掃描實體類
        bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        bean.setJpaProperties(properties);

        return bean;
    }
}

Main ( 測試 類)

package com.oukele.the_data_jpa;

import com.oukele.the_data_jpa.entity.User;
import com.oukele.the_data_jpa.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService service = context.getBean(UserService.class);
        User user = service.findNameAndPassword("oukele","oukele");

        System.out.println(user);

    }

}

jdbc.properties文件:

jdbc.driver=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://localhost:3306/test
jdbc.user=oukele
jdbc.password=oukele

示例代碼下載: https://github.com/oukele/spring-hibernate-spring-data-jpa

Spring整合Hibernate實現Spring Data JPA (簡單使用)