生成后目录结构:
CREATE TABLE cars (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30) ,
price float ,
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
package entity;
public class Car {
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;
}
}
<?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="entity">
<!-- 类Car映射到表cars -->
<class name="entity.Car" table="cars">
<id name="id" column="id">
<generator class="native">
</generator>
</id>
<property name="name" />
<property name="price" />
</class>
</hibernate-mapping>
Create default hibernate configuration and main class
默认生成的配置文件,如果没有默认生成,需要自己创建,需要注意的就是:路径固定(src文件夹下)、名称固定(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="entity/Car.hbm.xml" />
</session-factory>
</hibernate-configuration>
package test;
import entity.Car;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class test {
public static void main(String[] args) {
//获取SessionFactory
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//获取Session
Session session = sessionFactory.openSession();
//开启事务
session.beginTransaction();
//实例化对象,写具体的逻辑CURD操作
Car car = new Car();
car.setName("福特");
car.setPrice(70000);
session.save(car);
//提交事务
session.getTransaction().commit();
//关闭Session、SessionFactory
session.close();
sessionFactory.close();
}
}
原文:https://www.cnblogs.com/hhhqqq/p/12582905.html