Hibernate简单步骤—–第五步:
编写添加数据的入门代码(添加操作)
public class CrudTest {
//添加
@Test
public void insert() {
//创建sessionFactory
//默认加载classpath下的hibernate.cfg.xml
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
//创建sessionFactory创建session
//创建一个新的session
Session session = sessionFactory.openSession();
//开启事务
Transaction transaction = session.beginTransaction();
try {
//创建session操作数据库
//创建一个customer对象
CstCustomer cstCustomer = new CstCustomer();
cstCustomer.setCustName("兔斯基2");
session.save(cstCustomer);
//提交事务
transaction.commit();
} catch (Exception e) {
//打印日志
e.printStackTrace();
//回滚
transaction.rollback();
} finally {
//释放资源
session.close();
sessionFactory.close();
}
}
}
添加后数据库cst_customer表如下:
编写添加数据的入门代码(查询更新删除操作)
@Before
public void setUp(){
//创建sessionFactory
//默认加载classpath下的hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
}
//根据主键查询
@Test
public void getById() {
//创建sessionFactory创建session
//创建一个新的session
Session session = sessionFactory.openSession();
//根据主键查询一条记录
CstCustomer customer = session.get(CstCustomer.class, 94l);
System.out.println(customer);
session.close();
}
//更新
@Test
public void update() {
//创建sessionFactory创建session
//创建一个新的session
Session session = sessionFactory.openSession();
//开启事务
Transaction transaction = session.beginTransaction();
try {
/* //创建session操作数据库
//根据主键更新一条记录
CstCustomer cstCustomer = new CstCustomer();
cstCustomer.setCustId(95l);
cstCustomer.setCustName("兔斯基1");
//指定主键
*/
//建议先查询出记录,再设置更新的值
CstCustomer customerOld = session.get(CstCustomer.class, 96l);
customerOld.setCustPhone("123456789");
customerOld.setCustMobile("43994399");
session.update(customerOld);
//提交事务
transaction.commit();
} catch (Exception e) {
//打印日志
e.printStackTrace();
//回滚
transaction.rollback();
} finally {
//释放资源
session.close();
sessionFactory.close();
}
}
//删除
@Test
public void delete() {
//创建sessionFactory创建session
//创建一个新的session
Session session = sessionFactory.openSession();
//开启事务
Transaction transaction = session.beginTransaction();
try {
//根据主键删除
CstCustomer cstCustomer = new CstCustomer();
cstCustomer.setCustId(95l);
session.delete(cstCustomer);
//提交事务
transaction.commit();
} catch (Exception e) {
//打印日志
e.printStackTrace();
//回滚
transaction.rollback();
} finally {
//释放资源
session.close();
sessionFactory.close();
}
}
}
总结(开发的步骤)
*创建Java工程,导入Hibernate框架需要的所有的jar包
* 创建数据库的表结构,编写JavaBean的类
* 编写表结构和类的映射的配置文件(名称:类名.hbm.xml 存放在类所在的包下)
* 编写Hibernate框架核心的配置文件(名称:hibernate.cfg.xml 存放在src的目录下)
* 编写代码
* 加载所有的配置文件
* 获取SessionFactorty对象,创建session的对象
* 获取Session的对象
* 开启事务
* 数据操作(增删改查所有的操作)
* 提交事务
* 释放资源