标签:
狭义的理解: 持久化仅仅指把对象永久的保存到数据库中。
广义的理解: 持久化包括和数据库相关的各种操作。
保存: 把对象永久保存到数据库中。
更新: 更新数据库中对象的状态。
删除: 从数据库中删除一个对象。
查询: 根据特定的查询条件,把符合查询条件的一个或者多个对象加载到内存中。
ORM(Object-Relation-Mapping),对象关系映射。
ORM的思想: 将关系数据库中的表的记录映射成对象,以对象形式展现,可以把对数据库的操作转化成对对象的操作。
User.java
public class User{
private Integer uid;
private String username;
private String password;
public User(){
super();
}
public User(String username,String password){
super();
this.username = username;
this.password = password;
}
//getXxx、setXxx...
}
User.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.kiwi.domain.User" table="t_user">
<!-- 配置主键 -->
<id name="uid">
<!-- 主键生成策略 -->
<generator class="native"></generator>
</id>
<!-- 普通属性 -->
<property name="username"></property>
<property name="password"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?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> <!-- SessionFactory相当于连接池的配置 --> <session-factory> <!-- 基本四项 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <!-- Hibernate 的基本配置 --> <!-- Hibernate 使用的数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <!-- 运行时是否打印 SQL --> <property name="show_sql">true</property> <!-- 运行时是否格式化 SQL --> <property name="format_sql">true</property> <!-- 添加映射文件 --> <mapping resource="com/kiwi/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
@Test
public void testHello(){
//1.加载配置文件获取核心配置对象
Configuration config = new Configuration().configure();
//2.获得SessionFactory
SessionFactory factory = config.buildSessionFactory();
//3.获取会话session
Session session = factory.openSession();
//4.开启事务
Transaction tx = session.beginTransaction();
//操作
session.save(new User("Tom","123456"));
//5.提交事务 | 回滚事务
tx.commit();
//6.释放资源---关闭session
session.close();
//7.释放资源---关闭factory
factory.close();
}
结果:
标签:
原文地址:http://www.cnblogs.com/yangang2013/p/5496795.html