Hibernate教程(1) -配置文件
Hibernate 使得数据库访问变得轻松而简单,代码也更加易于维护。刚开始使用Hibernate时配置文件非常重要。
1. 创建数据库和表:
create database test;
use test;
create table product (
id int not null auto_increment,
name varchar(30),
price float,
primary key (id)
) default charset=utf8;
2.创建实体类:
public class Product {
int id;
String name;
float price;
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;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
3.配置Product.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.jinlei.wang.bean.Product" table="product">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="price"></property>
</class>
</hibernate-mapping>
注:配置文件要放在resources文件夹内否则会在项目启动时提示错误:org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : .hbm.xml : origin(.hbm.xml)
4.配置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>
<!--显示执行的sql语句-->
<property name="show_sql">true</property>
<!--自动更新数据库的表结构,不需要手动创建表,hibernate会自动创建-->
<property name="hbm2ddl.auto">update</property>
<!--指定数据库连接串-->
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<!--数据库驱动-->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--连接数据库用户名-->
<property name="connection.username">root</property>
<!--连接数据库用户密码-->
<property name="connection.password">pasword</property>
<!--映射文件-->
<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
5.测试结果
public class TestHibernate {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Product product = new Product();
product.setName("iphone8");
product.setPrice(7000);
session.save(product);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}