sessionFactory获取:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SessionFactoryUtil {
private static final SessionFactory sessionFactiry = getSessionFactoryInstance();
private static SessionFactory getSessionFactoryInstance(){
Configuration configuration = new Configuration().configure();
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(standardServiceRegistry);
}
public static SessionFactory getSessionFactory(){
return sessionFactiry;
}
}
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>
<!--数据库连接设置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/db_hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 控制台显示SQL -->
<property name="show_sql">true</property>
<!-- 事务隔离级别 -->
<property name="connection.isolation ">2</property>
<!-- 自动更新表结构 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/java1111/model/Student.hbm.xml"/>
<mapping class="com.java1111.model.Class"/>
</session-factory>
</hibernate-configuration>
Student.hbm.xml
<hibernate-mapping package="com.java1234.model">
<class name="Student" table="t_student">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<property name="password" column="psd"></property>
<many-to-one name="c" column="classId" class="com.java1111.model.Class" cascade="save-update"></many-to-one>
</class>
</hibernate-mapping>