Table of Contents
0. 使用到的环境
// database related compile 'mysql:mysql-connector-java:8.0.15' compile 'org.hibernate:hibernate-core:5.4.1.Final' compile 'org.springframework.data:spring-data-jpa:2.1.5.RELEASE'
1. 开发阶段 或 直接提供datasource方式
no persistence.xml, use spring data jpa
public class MyJpaConfig { @Bean public DataSource dataSource(){ String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; return new DriverManagerDataSource(url, username, password); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setShowSql(true); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setDataSource(dataSource); factory.setJpaProperties(properties); factory.setPackagesToScan("com.my.entity"); return factory; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } }
factory.setPackagesToScan("com.my.entity");
这一句指定了扫描那个包里的所有@Entity类。这样就可以自动扫描了,直接使用定义的Entity类了。
2. 提供Jar集成第三方persistence.xml
在为其他人提供jar时,或者使用别人提供的jar集成时, 在persistence.xml里加入
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="commerce.jpa" transaction-type="RESOURCE_LOCAL"> <description> Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide </description> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <!-- integrate. add entity jar --> <jar-file>your-entity-0.0.1-SNAPSHOT.jar</jar-file> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="password" /> <property name="hibernate.dialect.storage_engine" value="innodb" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="validate" /> </properties> </persistence-unit> </persistence>
使用<jar-file>***.jar</jar-file>方式来自动扫描提供的第三方包里的@Entity类。