一步一步学hibernate4–初识hibernate
之前学的是c语言,所以对java的开发框架都不甚了解,现在转做java后,才开始学的herbinate,完全是新手,所以避免不了有很多错漏的地方,欢迎各位指正。
至于hibernate是什么就不用多做解释了,马上开始吧!
对于学一门新的技术,首先是要使用它,下面我们就先来用用hibernate吧。
1、第一步先新建一个Java工程,把下载下来的hibernate解压包中的lib\required下的所有jar加到工程中并加到类路径下,由于我使用的mysql数据库,所以还需要MySQL的驱动,当然还需要c3p0的包也要加进来。
2、在src中新建一个文件叫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/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">engine</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 控制台显示SQL -->
<property name="show_sql">true</property>
<mapping resource="com/test/hibernate/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3、新建一个包名叫,com.test.hibernate.model
在里面新建一个Student类,内容如下,省略get/set方法
public class Student {
private String id;
private String name;
private String emailString;
}
在此路径下再新建一个Student.hbm.xml文件命名方式为“类名”.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.test.hibernate.model">
<class name="Student" table="t_student">
<id name="id" column="stuId">
<!--主键-->
<generator class="native"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
4. 新建一个包com.test.hibernate.test,在其中新建一个Test1类内容如下
@Test
public void testAdd() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration
.buildSessionFactory(standardServiceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
Student student = new Student();
student.setName("test1");
student.setEmail("test1@163.com");
session.save(student);
session.getTransaction().commit();
session.close();
sessionFactory.close();
运行这个unitetest方法,就会发现hibernate数据库的student表中多了一个数据。
最后的工程目录如下![工程目录]([https://img-blog.youkuaiyun.com/20160106205313989]
下一章我们将介绍把hibernate的常用代码封装起来,还有介绍hibernate简单的CRUD,和基于注解的hibernate。