本文介绍如何通过java config方式配置JPA,其中数据源使用 hikari,在 spring boot 2.0 下正常运行
maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.8</version>
</dependency>
application.yml
database:
jdbcUrl: jdbc:postgresql://localhost:5432/yourdb?prepareThreshold=0
username: root
password: "123456"
poolName: csis-common
maxPoolSize: 5
minIdle: 1
connectionTestQuery: select 1
driverClassName: org.postgresql.Driver
java 配置
@EnableJpaRepositories(
basePackages = "com.royalnu.csis.ms.example.provider", // 更改对应repository & pojo 包名
entityManagerFactoryRef = "exampleEntityManager", // 与java bean 定义一致
transactionManagerRef = "exampleTransactionManager" // 与java bean 定义一致
)
java bean定义
//....
// 定义数据源
@Bean
@ConfigurationProperties(prefix = "datasource")
public DataSource dataSource() {
return new HikariDataSource();
}
@Bean
public LocalContainerEntityManagerFactoryBean exampleEntityManager() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabase(Database.valueOf("POSTGRESQL"));
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
// 更改为对应包名,包括 repository 及 pojo ,建议放到同级不同子目录
factory.setPackagesToScan("com.royalnu.csis.ms.example.provider");
factory.setDataSource(dataSource());
factory.setJpaProperties(jpaProperties());
return factory;
}
@Bean
private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.temp.use_jdbc_metadata_defaults", "false");
return properties;
}
@Bean
public PlatformTransactionManager exampleTransactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(exampleEntityManager().getObject());
return txManager;
}
repository:
package com.royalnu.csis.ms.example.provider.repository;
import com.royalnu.csis.ms.example.provider.pojo.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TeacherRepository extends JpaRepository<Teacher, Integer> {
}
pojo:
package com.royalnu.csis.ms.example.provider.pojo;
import lombok.Data;
import javax.persistence.*;
@Data
@Table(name = "t_teacher")
@Entity
public class Teacher {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
protected Integer id;
protected String name;
@Column(name = "job_title")
protected String jobTitle;
public Teacher() {}
public Teacher(String name, String jobTitle) {
this.name = name;
this.jobTitle = jobTitle;
}
}