Hibernate实现简单的CRUD

一:创建Hibernate的,如

Hibernate技术学习 https://www.itkc8.com

导入Hibernate的jar包
   -hibernate-->lib-->required
   -hibernate-->hiberate.jar
  -hibernate-->lib-->jpa
   -log4j
   -mysql-connector

二:创建相应的业务对象(User)

 

/**
 * @author HUXU
 *
 */
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private Integer id;
	private Integer myid;
	private String username;
	private String password;
	
	public Integer getId() {

省略set和get方法

 

三、创建Hibernate的配置文件
   -src-->hibernate.cfg.xml,在这个配置文件中进行相应的数据库连接设定

<!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>
	<!-- hibernate的方言,用来确定连接的数据库 -->
		<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
	<!-- 数据库的连接类 -->
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
	<!-- 数据库的连接字符串和用户名密码 -->
		<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<property name="hibernate.connection.username">goddog</property>
		<property name="hibernate.connection.password">goddog</property>
	<!-- 在使用hibernate时会显示相应的SQL -->
		<property name="show_sql">true</property>
	<!-- 会自动完成类到数据表的转换 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
	<!-- 加入实体类的映射文件 -->	
		<mapping resource="com/goddog/bean/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>


四:为相应的业务对象创建hbm的配置文件,在这个文件中说明与数据库的映射关系,如果为User对象创建就在User对象所在的包中创建一个User.hbm.xml文件

 

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.goddog.bean">
    <class name="com.goddog.bean.User" table="t_user">
        <id name="id">
            <generator class="sequence">
            	<param name="sequence">user_seq</param>
            </generator>
        </id>
		<property name="username"/>
		<property name="password"/>
		<property name="myid"/>
    </class>
</hibernate-mapping>


五:创建HibernateUtil工具类

 

 

/**
 * 
 */
package com.goddog.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author HUXU
 *
 */
public class HibernateUtil {
	
	private final static SessionFactory FACTORY = buildSessionFactory();

	/**
	 * 
	 */
	public HibernateUtil() {
		// TODO Auto-generated constructor stub
	}
	
	//创建工厂
	private static SessionFactory buildSessionFactory() {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		//cfg.buildSessionFactory();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
		return factory;
	}
	
	//得到工厂
	public static SessionFactory getSessionFactory(){
		return FACTORY;
	}
	
	//打开session
	public static Session openSession(){
		return FACTORY.openSession();
	}
	
	//关闭session
	public static void close(Session session){
		if(session != null) session.close();
	}

}


六:创建TestCRUD测试类

 

 

/**
 * 
 */
package com.goddog.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.goddog.bean.User;
import com.goddog.util.HibernateUtil;
import org.junit.Test;
/**
 * @author HUXU
 *
 */
public class TestCRUD {

	//增
	@Test
	public void testAdd(){
		Session session = null;
		try{
		session = HibernateUtil.openSession();//打开session
		session.beginTransaction();//开启事务
		
		User user = new User();
		user.setMyid(0);
		user.setUsername("cat");
		user.setPassword("111");
		session.save(user);//save
		
		session.getTransaction().commit();//提交事务
		}catch (HibernateException e) {
			// TODO: handle exception
			e.printStackTrace();
			if(session != null) session.getTransaction().rollback();
		}finally{
			HibernateUtil.close(session);
		}
	}
	
	//改
	@Test
	public void testUpdate(){
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			
			User user = (User)session.load(User.class, 28);//先load
			user.setUsername("gogo");
			session.update(user);//update
			
			session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			if(session != null) session.getTransaction().rollback();
		}finally{
			HibernateUtil.close(session);
		}
	}
	
	//删
	@Test
	public void testDelete(){
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			
			User user = new User();
			user.setId(1);//根据id删除
			session.delete(user);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			if(session != null) session.getTransaction().rollback();
		}finally{
			HibernateUtil.close(session);
		}
				
		
	}
	
	//查
	@Test
	public void testLoad(){
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			User user = (User)session.load(User.class, 1);//1为id
			System.out.println(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}finally{
			HibernateUtil.close(session);
		}
	}
	
	//list查询
	@SuppressWarnings("unchecked")
	@Test
	public void testList(){
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			List<User> users = session.createQuery("from User").list();
			for(User u : users){
				System.out.println(u);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			HibernateUtil.close(session);
		}		
	}
	
	//分页查询
	@SuppressWarnings("unchecked")
	@Test
	public void testPager(){
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			List<User> users = session.createQuery("from User").setFirstResult(2).setMaxResults(3).list();
			for(User u : users){
				System.out.println(u);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			HibernateUtil.close(session);
		}		
	}
	
	
	
	public TestCRUD() {
		// TODO Auto-generated constructor stub
	}

}

Hibernate技术学习 https://www.itkc8.com

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是基于 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 的过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值