package net.qbzhong.po;
public class User {
private int id;
private String name;
private String password;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<?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="net.qbzhong.po.User" table="t_user">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name"></property>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
package net.qbzhong.test;
import net.qbzhong.po.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class TestClient {
public static void main(String[] args) {
//1.读取配置文件(hibernate.properties)
Configuration cfg = new Configuration();
//读取hibernate.cfg.xml配置文件
cfg = cfg.configure();
//2.建立与数据库会话(session)的factory
SessionFactory factory = cfg.buildSessionFactory();
//3.与数据库之间的会话
Session session = factory.openSession();
//数据库事务(开启事务)
Transaction tx = session.beginTransaction();
//4.生成User的实例
User user = new User();
user.setName("west");
user.setPassword("12345");
//5.保存到数据库
session.save(user);
//提交事务
tx.commit();
session.close();
}
}
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_basicmapping</property>
<!-- 数据库账号 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 在Console中输出sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 配置数据的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 映射指定的实体类文件,将映射文件加入到配置文件中 -->
<mapping resource="net/qbzhong/po/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<property name="hibernate.show_sql">true</property>
//这行代码的作用就是在运行main函数后,在Console视图框中可以输出执行的SQL语句。