初识hibernate
新建名为test的数据库;新建实体类Student,属性有id,name
(1)Student.java
package com.java.model;
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(2)从官网下载hibernate源码包;在eclipse新建一个项目,在下载的源码包里面找到使用hibernate所需jar包,贴到项目里(连接mysql数据库所需jar包也贴进去)
(3)编写student实体对应的映射文件Student.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.java.model">
<!--配置实体对应的相应字段-->
<class name="Student" table="t_student">主键id
<id name="id" column="stuId">
<generator class="native"></generator> 主键生成策略
</id>
<property name="name" column="stuName"></property>属性name
</class>
</hibernate-mapping>
(4)从官方文档找到配置文件hibernate.cfg.xml并适当修改配置,例如数据库连接驱动名,url等,并且把student.hbm.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:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<!-- SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout 控制台显示sql语句 -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup 每次运行自动更新表结构-->
<property name="hbm2ddl.auto">update</property>
<!--映射文件配置-->
<mapping resource="com\java\model\Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(5)获取session,测试添加一个学生姓名
package com.java.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.java.model.Student;
public class StudentTest {
public static void main(String[] args) {
//实例化配置文件
Configuration configuration=new Configuration().configure();
//实例化服务登记:构造函数调用构建器配置configuration,返回服务登记类
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
//构建SessionFactory
SessionFactory sessionFactory=configuration.buildSessionFactory(serviceRegistry);
//创建一个新的session
Session session=sessionFactory.openSession();
//开启事务
session.beginTransaction();
Student s=new Student();
s.setName("张三");
session.save(s);
//提交事务
session.getTransaction().commit();
session.close();//关闭session
sessionFactory.close();//关闭sessionFactory
}
}
运行结果,控制台显示。。。
自动生成的表结构
数据成功添加到数据库