1、加入hibernate框架相关的jar包(数据库版本和驱动版本要匹配)
2、编写hibernate的配置文件:默认文件名称 hibernate.cfg.xml
1) 创建src/hibernate.cfg.xml(hibernate.properties)
<?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>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 数据库连接 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">00000</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 自动生成表结构 -->
<property name="hbm2ddl.auto">update</property>
<!-- mapping映射(xml或注解在哪) -->
<mapping class="wang.a.User"/>
<mapping class="wang.a.User1"/>
</session-factory>
</hibernate-configuration>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>是hibernate-configuration-3.0.dtd文件中截取
2) xml文件编写规则(.dtd或者.xsd),使用dtd文件
3) 如果xml文件中不能智能提示,则需要配置dtd文件
4) 配置节点:如数据库连接信息
3、编写实体类(不需要建表)
1) 在类上使用注解:@Entity, @Table
2) 在属性上使用注解:@Column
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tb_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 50) // 默认长度:255
private String name;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
4、测试:
- 增加一条记录
- 按主键查询
public class Test1 {
public static void main(String[] args) {
//1、创建SessionFactory对象
// configure():读取hibernate.cfg.xml文件。如果不调用该方法,则读取hibernate.properties文件
// SessionFactory代表一个数据库,是一个重量级对象(创建很耗时),它是线程安全的,应该使用单例模式共享
SessionFactory factory = new Configuration().configure().buildSessionFactory();
//2、创建Session对象:这是轻量级对象,是线程不安全的,不能共享,所以用完要关闭
// Session代表一次连接(即表示Connection),不是HttpSession
Session session = factory.openSession();
//3、增删改, 需要事务
Transaction tx = session.beginTransaction();
User user = new User();
user.setName("张三2");
user.setAge(20);
session.save(user); //调用session的API
tx.commit();
session.close();
factory.close();
}
}