首先要声明的依赖性:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
下创建配置文件hibernate.cfg.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/UserDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- <property name="FOREIGN_KEY_CHECKS">0</property> -->
<!-- Mapping files -->
<mapping class="com.stackoverflow.model.Person" />
<mapping class="com.stackoverflow.model.Phone" />
</session-factory>
</hibernate-configuration>
如果您有实体,你应该把它们的标签<mapping class="pathToEntity">
。
接下来在主要方法:
在这里,您创建Sessionfactory
并获取当前Session
对象能够查询数据库。
你看过毛茸茸的手册吗? http://hibernate.org/orm/documentation/5.2/ – 2017-04-18 05:32:31