Hibernate--
Posted CrazyDream
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate--相关的知识,希望对你有一定的参考价值。
项目结构:
表:
1.实体类:
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; } }
2.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 package="com.how2j.pojo"> <class name="Product" table="product_"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="name" /> <property name="price" /> </class> </hibernate-mapping>
3.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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="com/h/pojo/Product.hbm.xml" /> </session-factory> </hibernate-configuration>
4.Test.java
public class Test { public static void main(String[] args) { /* hibernate的基本步骤是: 1. 获取SessionFactory 2. 通过SessionFactory 获取一个Session 3. 在Session基础上开启一个事务 4. 通过调用Session的save方法把对象保存到数据库 5. 提交事务 6. 关闭Session 7. 关闭SessionFactory */ SessionFactory sf = new Configuration().configure().buildSessionFactory(); Session s = sf.openSession(); s.beginTransaction(); Product p = new Product(); p.setName("iphone7"); p.setPrice(7000); s.save(p); s.getTransaction().commit(); s.close(); sf.close(); }
5.成功
以上是关于Hibernate--的主要内容,如果未能解决你的问题,请参考以下文章
使用反射在外部JAR / CLASS上调用包含Hibernate事务的方法(Java EE)
Hibernate CriteriaQuery where - ManyToOne 字段
Hibernate + MySQL:如何为数据库和表设置编码 utf-8
hibernate在使用getCurrentSession时提示no session found for current thread