我可以在我的应用程序中使用不同的hibernate文件名而不是hibernate.cfg.xml,我将Hibernate用作ORM框架吗?
configuration = new Configuration();
sessionFactory = configuration.configure("MyFileName.cfg.xml")
.buildSessionFactory();
我想在我的应用程序中使用不同的文件名吗?
答案 0 :(得分:5)
是的,你可以。在这种情况下,必须在上面的代码中明确指定它。如果文件在类路径中,则不需要在文件名前面加上斜杠。
configuration = new Configuration();
sessionFactory = configuration.configure("MyFileName.cfg.xml")
.buildSessionFactory();
这里,MyFileName.cfg.xml应该出现在类路径中。
答案 1 :(得分:0)
如果除了配置文件的默认名称(hibernate.properties
)之外还想更改默认属性文件(hibernate.cfg.xml
)的名称,则需要将它们放在资源文件夹中。然后,您可以强制Hibernate以这种方式使用它们:
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.IOException;
public class App
{
public static void main(String[] args) throws IOException
{
Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.load(App.class.getClassLoader().getResourceAsStream("myhibernate.properties"));
configuration.addProperties(properties);
final SessionFactory sessionFactory = configuration.configure(App.class.getClassLoader().getResource("myhibernate.cfg.xml")).buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
session.close();
}
}
myhibernate.properties
:
hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://127.0.0.1:3306/testdb
hibernate.connection.username=root
hibernate.connection.password=password
hibernate.connection.pool_size=1
hibernate.hbm2ddl.auto=create
myhibernate.cfg.xml
:
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- List of XML mapping files -->
<mapping class = "tech.procode.Student"/>
</session-factory>
</hibernate-configuration>