hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:mysql://localhost:3306/xg</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- 配置hibernate的基本信息 --> <!-- 配置数据库方言dialect --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> <mapping class="orm.User"/> <mapping resource="orm/User.hbm.xml"/> </session-factory> </hibernate-configuration>
测试文件:
package Test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import orm.User; /** * Created by ggg on 2018/3/13. */ public class test1 { public static void main(String[] args) { SessionFactory sessionFactory; Session session; Transaction transaction; System.out.println("test...."); //1. 创建配置对象 Configuration config = new Configuration().configure(); //2. 创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //3. 创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistry); //4. 会话对象 session = sessionFactory.openSession(); //5. 开启事务 transaction = session.beginTransaction(); User user = (User)session.load(User.class, 2); System.out.println(user.getId()); transaction.commit(); session.close(); } }