springboot直接引入hibernate,用applications.properties当配置文件是很简单的:
spring.application.name=test-hibernate
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
然后直接打一个注解,就可以用hibernate了:
@PersistenceContextprivate EntityManager mEM;
下面获取所有的实体类的名字:
var emf = mEM.getEntityManagerFactory();var model = emf.getMetamodel();var ets = model.getEntities();for(var et:ets) {var s = et.getName();System.out.println(s);}
但是这种方式下,hibernate.cfg.xml不被加载,总不能所有的配置都在applications.properties里做,hibernate也要有自己的配置文件。deepseek上问了半天,给出的思路,是接替一个什么factory,我写了一个HibernateConfig.java,测试被spring加载了,但是里面的东西好像不生效,因为我故意写错了几个字也没事:
package com.example.hibernate;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;import javax.sql.DataSource;
import java.util.Properties;@Configuration
public class HibernateConfig {@Autowiredprivate DataSource dataSource;@Beanpublic LocalContainerEntityManagerFactoryBean entityManagerFactory() {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(dataSource);em.setPackagesToScan("com.example.hibernate"); // 扫描实体类所在的包// 使用 Hibernate 作为 JPA 实现HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();em.setJpaVendorAdapter(vendorAdapter);// 加载 hibernate.cfg.xmlProperties properties = new Properties();properties.put("hibernate.ejb.cfgfile", "classpath:hibernate.cfg.xml");em.setJpaProperties(properties);System.out.println("jjjjjj");return em;}
}
后续再看把。