hibernate入门
Hibernate 是一个开源的 ORM(对象关系映射)框架,它可以将 Java 对象与数据库表进行映射,从而实现面向对象的数据持久化。使用 Hibernate,可以避免手动编写 SQL 语句,从而提高开发效率,并且可以轻松地切换不同的数据库。基础概念
entity 实体类是映射到数据库表中的 Java 类,它包含了与数据库表中列相对应的属性,并且可以使用注解或 XML 文件进行映射。
MySql table 关系型数据库中的表格
https://img2023.cnblogs.com/blog/2089409/202308/2089409-20230809134143356-60105325.png
hibernate负责互相转换两者。将entity存入数据库,将数据库中的数据取出并创建实体类的实例提使用者。
依赖
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.7.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>配置类
maven项目将配置文件hibernate.cfg.xml放置再resource目录下即可
<?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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jpa_study?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">a1b2c3</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="current_session_context_class">thread</property>
<mapping />
</session-factory>
</hibernate-configuration>工具类
package org.example.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.function.Consumer;
import java.util.function.Function;
public class SessionFactoryUtil {
private static final SessionFactory sessionFactory;
static {
// 构建会话工厂(configure未指定参数默认查找classpath:hibernate.cfg.xml)
sessionFactory = new Configuration().configure().buildSessionFactory();
}
/**
* 执行sql操作
* @param callback 回调函数
*/
public static void execute(Consumer<Session> callback) {
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
try {
callback.accept(session);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
transaction.commit();
}
/**
* 执行sql查询操作
* @param callback 回调函数
* @return 回调函数的返回值
* @param <R> 回调函数的返回值
*/
public static <R> R query(Function<Session, R> callback) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
R r = callback.apply(session);
transaction.commit();
return r;
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
return null;
}
}
}Dao层
package org.example.dao;
import org.example.entity.User;
import org.example.util.SessionFactoryUtil;
import java.util.List;
public class UserDao {
public void save(User user) {
SessionFactoryUtil.execute(session -> session.persist(user));
}
public void update(User user) {
SessionFactoryUtil.execute(session -> session.merge(user));
}
public void delete(User user) {
SessionFactoryUtil.execute(session -> session.remove(user));
}
public User findById(Long id) {
return SessionFactoryUtil.query(session -> session.get(User.class, id));
}
public List<User> findAll() {
return SessionFactoryUtil.query(session -> session.createQuery("from User", User.class).list());
}
}测试
package org.example;
import org.example.dao.UserDao;
import org.example.entity.User;
public class Main {
public static void main(String[] args) {
User user = new User();
user.setName("zhangsan");
user.setEmail("zhangsan@qq.com");
UserDao userDao = new UserDao();
userDao.save(user);
System.out.println(userDao.findById(user.getId()));
userDao.findAll().forEach(System.out::println);
}
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]