hibernate之简单CRUD操作

hibernate中的增删改参数都是对象,查则略微不同,要求Object.class和ID具体用法如下:
package com.dimples.service;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.dimples.dao.User;
import com.dimples.util.SessionFactoryUtils;

public class Test2 {
	//测试保存一条记录
	@Test
	public void saveUser() {
		User user = new User();
		user.setUsername("赵六");
		user.setPassword("123456");
		Session session = SessionFactoryUtils.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
		
	}
	
	//测试查询一条记录
	@Test
	public void getUser() {
	Session session = SessionFactoryUtils.getSessionFactory().openSession();
	Transaction tx = session.beginTransaction();
	User user = session.get(User.class, Integer.parseInt("6"));//这个地方的第二个参数要保持与定义的Javabean中id属性的类型一致
	System.out.println(user.toString());
	tx.commit();
	session.close();
	}
	
	//测试更新一条数据
	@Test
	public void updateUser() {
		Session session = SessionFactoryUtils.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		User user = session.get(User.class, Integer.parseInt("6"));
		user.setPassword("666666");
		session.update(user);
		tx.commit();
		session.close();
	}
	
	//测试删除一条数据
	@Test
	public void deleteUser() {
		Session session = SessionFactoryUtils.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		User user = session.get(User.class, Integer.parseInt("6"));
		session.delete(user);
		tx.commit();
		session.close();
	}
	
	//测试查询多条数据
	@Test
	public void getAll() {
		Session session = SessionFactoryUtils.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		SQLQuery sqlquery = session.createSQLQuery("select * from user");
		List list = sqlquery.list();//如果打印出来是 Ljava.lang.Object;@2a139a55 这样的东西,代表它是个Object[]
		for(Object[] objs : list) {
			for(Object obj : objs) {
				System.out.println(obj.toString());
			}
		}
		tx.commit();
		session.close();
	}
}

你可能感兴趣的:(Hibernate&JPA)