我是休眠新手,我不完全了解如何在休眠配置文件中的 java 配置和 xml 之间进行选择?我看过的教程似乎已经过时了。所以我的问题是配置模型休眠的最佳和最新方法是什么。
以下是我目前的方法,似乎是唯一适合我的方法:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<!-- <property name="hibernate.generate_statistics">true</property> -->
我正在java文件中配置我的模型,如下所示:
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create your SessionFactory with mappings for every Entity in a specific package
Configuration configuration = new Configuration();
configuration.configure();
configuration.addAnnotatedClass(PersonModel.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
//SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
这是正确的方法吗? 还是应该通过XML文件完成,如果是这样,有人可以给我看一个例子吗?
提前致谢
有关示例,请查看以下文档:
对于注释映射:
https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping
对于 xml 映射:
https://docs.jboss.org/hibernate/orm/3.3/reference/fr-FR/html/xml.html
使用其中之一取决于您,有关更多详细信息,您可以查看此答案或此答案
编辑:休眠配置文件中的映射示例
<hibernate-configuration>
<session-factory>
<mapping package="test.animals"/>
<mapping class="test.Flight"/>
<mapping class="test.Sky"/>
<mapping class="test.Person"/>
<mapping class="test.animals.Dog"/>
<mapping resource="test/animals/orm.xml"/>
</session-factory>
</hibernate-configuration>
这样,您可以一次扫描所有实体类
SessionFactory sessionFactory = new LocalSessionFactoryBuilder(yourDataSource())
.scanPackages("com.yourpackage.name")
.addProperties(properties)
.buildSessionFactory();