Hibernate实现CRUD(附项目源码)

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
return category;

} catch (SQLException e) {

throw new RuntimeException(e);

}

}

@Override

public List getAllCategory() {

QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

String sql = “SELECT * FROM category”;

try {

List categories = (List) queryRunner.query(sql, new BeanListHandler(Category.class));

return categories;

} catch (SQLException e) {

throw new RuntimeException(e);

}

}

}

其实使用DbUtils时,DAO层中的代码编写是很有规律的。

当插入数据的时候,就将Javabean对象拆分,拼装成SQL语句

当查询数据的时候,用SQL把数据库表中的列组合,拼装成Javabean对象

Javabean对象和数据库表中的列存在映射关系!如果程序能够自动生成SQL就好了,hibernate应运而生。

三、hibernate快速入门

===============

学习一个框架无非就是三步:

  • 引入jar包

  • 配置XML文件

  • 熟悉API

1、引入jar包


我们使用的是Hibernate5.4的版本

hibernate5.jar核心 + required 必须引入的(6个) + jpa 目录 + 数据库驱动包

2、配置XML文件


(1)编写一个Entity对象->Employee.java

编写对象映射->Employee.hbm.xml。一般它和JavaBean对象放在同一目录下

在上面的模板上修改~下面会具体讲解这个配置文件!

<?xml version="1.0"?>

(2)主配置文件hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

org.hibernate.dialect.OracleDialect

oracle.jdbc.driver.OracleDriver

mine

mine

jdbc:oracle:thin:@127.0.0.1:1521:orcl

true

update

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xmlns:aop=“http://www.springframework.org/schema/aop”

xmlns:context=“http://www.springframework.org/schema/context”

xmlns:tx=“http://www.springframework.org/schema/tx”

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<context:property-placeholder location=“classpath:db.properties” ignore-unresolvable=“true”/>

<bean id=“sessionFactory”

class=“org.springframework.orm.hibernate5.LocalSessionFactoryBean”>

com/ssh/entities/Department.hbm.xml

com/ssh/entities/Employee.hbm.xml

hibernate.cfg.xml

org.hibernate.dialect.OracleDialect

update

true

true

<tx:annotation-driven transaction-manager=“transactionManager”/>

applicationContext-beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd”>

struts.xml

<?xml version="1.0" encoding="UTF-8" ?> false

/WEB-INF/views/emp-list.jsp

text/html inputStream

/WEB-INF/views/emp-input.jsp

/emp-list

3、类文件


EmployeeAction

package com.ssh.actions;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionSupport;

import com.opensymphony.xwork2.ModelDriven;

import com.opensymphony.xwork2.Preparable;

import com.ssh.entities.Employee;

import com.ssh.service.DepartmentService;

import com.ssh.service.EmployeeService;

public class EmployeeAction extends ActionSupport implements RequestAware,

ModelDriven,Preparable{

private static final long serialVersionUID = 1L;

private EmployeeService employeeService;

public void setEmployeeService(EmployeeService employeeService) {

this.employeeService = employeeService;

}

private DepartmentService departmentService;

public void setDepartmentService(DepartmentService departmentService) {

this.departmentService = departmentService;

}

public String list() {

request.put(“employees”,employeeService.getAll());

return “list”;

}

private Integer id;

public void setId(Integer id) {

this.id = id;

}

public InputStream inputStream;

public InputStream getInputStream() {

return inputStream;

}

public String delete() {

try {

employeeService.delete(id);

inputStream = new ByteArrayInputStream(“1”.getBytes(“UTF-8”));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return SUCCESS;

}

public String input() {

request.put(“departments”, departmentService.getAll());

return INPUT;

}

public void prepareInput() {

if(id!=null) {

model = employeeService.get(id);

}

}

public String save() {

if(id == null) {

model.setCreateTime(new Date());

}

employeeService.saveOrUpdate(model);

System.out.println(“model”);

return SUCCESS;

}

public void prepareSave() {

if(id == null) {

model = new Employee();

}else {

model = employeeService.get(id);

}

}

private Map<String,Object> request;

@Override

public void setRequest(Map<String, Object> arg0) {

this.request = arg0;

}

@Override

public void prepare() throws Exception {}

private Employee model;

@Override

public Employee getModel() {

return model;

}

}

EmployeeService

package com.ssh.service;

import java.util.List;

import com.ssh.dao.EmployeeDao;

import com.ssh.entities.Employee;

public class EmployeeService {

private EmployeeDao employeeDao;

public void setEmployeeDao(EmployeeDao employeeDao) {

this.employeeDao = employeeDao;

}

public void saveOrUpdate(Employee employee) {

employeeDao.saveOrUpdate(employee);

}

public void delete(Integer id) {

employeeDao.delete(id);

}

public List getAll(){

List employees = employeeDao.getAll();

return employees;

}

public Employee get(Integer id) {

return employeeDao.get(id);

}

}

EmployeeDao

package com.ssh.dao;

import java.util.List;

import com.ssh.entities.Employee;

public class EmployeeDao extends BaseDao{

public void delete(Integer id) {

String hql = “DELETE From Employee e where e.id=?0”;

getSession().createQuery(hql).setParameter(0,id).executeUpdate();

}

public List getAll() {

//String hql = “From Employee e LEFT OUTER JOIN FETCH e.department”;

String hql = “From Employee”;

return getSession().createQuery(hql).list();

}

public void saveOrUpdate(Employee employee) {

getSession().saveOrUpdate(employee);

}

public Employee get(Integer id) {

return (Employee)getSession().get(Employee.class,id);

}

}

emp-list.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8”

pageEncoding=“UTF-8”%>

<%@ taglib prefix=“s” uri=“/struts-tags”%>

Insert title here
Employee List Page

<s:if test=“#request.employees == null||#request.employees.size() == 0”>

没有任何员工信息

</s:if>

<s:else>

ID LASTNAME EMAIL BIRTH CREATETIME delete edit

<s:iterator value=“#request.employees”>

${id } ${lastName } ${email } ${birth } ${createTime }

Delete

写在最后

学习技术是一条慢长而艰苦的道路,不能靠一时激情,也不是熬几天几夜就能学好的,必须养成平时努力学习的习惯。所以:贵在坚持!

最后再分享的一些BATJ等大厂20、21年的面试题,把这些技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,上面只是以图片的形式给大家展示一部分。

蚂蚁金服三面直击面试官的Redis三连,Redis面试复习大纲在手,不慌

Mybatis面试专题

蚂蚁金服三面直击面试官的Redis三连,Redis面试复习大纲在手,不慌

MySQL面试专题

蚂蚁金服三面直击面试官的Redis三连,Redis面试复习大纲在手,不慌

并发编程面试专题

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
.employees.size() == 0">

没有任何员工信息

</s:if>

<s:else>

ID LASTNAME EMAIL BIRTH CREATETIME delete edit

<s:iterator value=“#request.employees”>

${id } ${lastName } ${email } ${birth } ${createTime }

Delete

写在最后

学习技术是一条慢长而艰苦的道路,不能靠一时激情,也不是熬几天几夜就能学好的,必须养成平时努力学习的习惯。所以:贵在坚持!

最后再分享的一些BATJ等大厂20、21年的面试题,把这些技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,上面只是以图片的形式给大家展示一部分。

[外链图片转存中…(img-kObO75GQ-1714643763976)]

Mybatis面试专题

[外链图片转存中…(img-Ohxe1KlL-1714643763976)]

MySQL面试专题

[外链图片转存中…(img-8WCy5uv1-1714643763976)]

并发编程面试专题

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是基于 Hibernate 框架创建 Student 类实现 CRUD: 1. 首先创建一个 Student 类,包含 id、name 和 age 三个属性,并在类上添加 `@Entity` 注解,用于将该类映射为数据库表。 ```java @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private int age; // 构造方法、getter 和 setter 方法省略 } ``` 2. 在 `hibernate.cfg.xml` 配置文件中配置数据库连接信息和 Hibernate 相关属性。 ```xml <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration> ``` 3. 创建一个 DAO(数据访问对象)类,用于对 Student 对象进行 CRUD 操作。在该类中通过 `SessionFactory` 获取 `Session` 对象,然后通过 `Session` 对象进行数据库操作。 ```java public class StudentDAO { private final SessionFactory sessionFactory; public StudentDAO(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void save(Student student) { Session session = sessionFactory.openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(student); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } public Student get(int id) { Session session = sessionFactory.openSession(); Student student = null; try { student = session.get(Student.class, id); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return student; } public void update(Student student) { Session session = sessionFactory.openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); session.update(student); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } public void delete(int id) { Session session = sessionFactory.openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Student student = session.get(Student.class, id); session.delete(student); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } } ``` 4. 在应用程序中使用 StudentDAO 类进行 CRUD 操作。 ```java public class Application { public static void main(String[] args) { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); StudentDAO studentDAO = new StudentDAO(sessionFactory); // 创建 Student 对象并保存到数据库 Student student = new Student("Tom", 18); studentDAO.save(student); // 根据 id 获取 Student 对象并更新其 age 属性 student = studentDAO.get(1); student.setAge(19); studentDAO.update(student); // 根据 id 删除 Student 对象 studentDAO.delete(1); } } ``` 以上就是使用 Hibernate 框架创建 Student 类实现 CRUD 的过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值