1、新建项目–点击创建配置文件hibernate-cfg.xml
2、导入包,加入依赖
3、通过数据库中的表,来创建bean实例和Student.hbm.xml
4、bean类代码如下:Student.java
public class Student {
private int id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
5、Student.hbm.xml映射文件代码如下:
主键生成策略,使用native,表中主键需要设置成自动增长
<hibernate-mapping>
<!-- 将Java实体类Student与数据库Hibernate表Student映射 -->
<class name="com.entity.Student" table="student">
<!-- 主键 -->
<id name="id" column="id" type="java.lang.Integer">
<generator class="native"></generator>
</id>
<!-- 非主键属性使用property -->
<property name="name" column="name" type="java.lang.String" />
</class>
</hibernate-mapping>
6、修改hibernate-cfg.xml,代码如下:
<hibernate-configuration>
<session-factory>
<!-- 1、数据库连接信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/fresh</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 2、数据库操纵信息 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 注意dialect的值,否则会出现奇怪的问题 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!--<property name="dialect">org.hibernate.dialect.MySQLDialect</property>-->
<property name="hbm2ddl.auto">update</property>
<!-- 3、添加实体类映射文件 -->
<mapping resource="com/entity/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7、编写测试程序Hibernate.java
public class HibernateTest {
public static void main(String[] args) {
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction tx=session.beginTransaction();
try
{
Student s=new Student();
s.setId(2015);
s.setName("小孩");
session.save(s);
tx.commit();
}
catch(Exception ex){
tx.rollback();
ex.printStackTrace();
}
finally{
if(session!=null) {
session.close();
}
}
}
}