学习记录,如作商用请注明出处 itcast
package cn.itcast.hibernate;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private HibernateUtil(){
}
static{
Configuration cfg = new Configuration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
}
public static Session getSession(){
return sessionFactory.openSession();
}
public static void add(Object entity){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(entity);
tx.commit();
}finally{
if(s!=null)
s.close();
}
}
public static void update(Object entity){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.update(entity);
tx.commit();
}finally{
if(s!=null)
s.close();
}
}
public static void delete(Object entity){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.delete(entity);
tx.commit();
}finally{
if(s!=null)
s.close();
}
}
public static Object get(Class clazz,Serializable id){
Session s = null;
try{
s = HibernateUtil.getSession();
Object obj = s.get(clazz, id);
return obj;
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.itcast.hibernate.domain.User;
public class Base {
public static void main(String[] args) {
User user = new User();
user.setBirthday(new Date());
user.setName("hefl");
addUser(user);
User u = getUser(user.getId());
System.out.println("name:"+u.getName());
System.out.println("end");
}
static void addUser(User user){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(user);
tx.commit();
}catch(HibernateException e){
if(tx!=null)
tx.rollback();
throw e;//要对异常做处理
}finally{
if(s!=null)
s.close();
}
}
static void addUser1(User user){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(user);
tx.commit();//HB会自动对异常进行处理
}finally{
if(s!=null)
s.close();
}
}
static User getUser(int id){
Session s = null;
try{
s = HibernateUtil.getSession();
User user = (User)s.get(User.class, id);
return user;
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.HashMap;
import java.util.Map;
import cn.itcast.hibernate.domain.User;
public class CacheDemo {
static Map cache = new HashMap();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User u = getUser(1);
System.out.println("---------");
User u1 = getUser(1);
}
public static void update(User user){
updateDB(user);
String key = User.class.getName()+user.getId();
cache.remove(key);
}
private static void updateDB(User user) {
// TODO Auto-generated method stub
}
public static User getUser(int id){
String key = User.class.getName()+id;
User user = (User) cache.get(key);
if(user!=null)
return user;
user = getFromDB();
cache.put(key, user);
return user;
}
private static User getFromDB() {
// TODO Auto-generated method stub
return null;
}
}
package cn.itcast.hibernate;
import java.util.Date;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import cn.itcast.hibernate.domain.User;
public class CacheTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = addUser();
System.out.println("----------------");
getUser(user.getId());
}
static User getUser(int id){
Session s = null;
try{
s = HibernateUtil.getSession();
Class userClass = User.class;
User user = (User) s.get(userClass, id);
System.out.println(user.getClass());
user = (User) s.get(userClass, id);
System.out.println(user.getClass());
return user;
}finally{
if(s!=null)
s.close();
}
}
public static User addUser(){
User user = new User();
user.setBirthday(new Date());
user.setName("cachetest");
HibernateUtil.add(user);
return user;
}
}
package cn.itcast.hibernate;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import cn.itcast.hibernate.domain.User;
public class Cri {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User();
user.setBirthday(new Date());
user.setName("zhangsan");
HibernateUtil.add(user);
cri("zhangsan");
}
static void cri(String name){
Session s = null;
try{
s = HibernateUtil.getSession();
Criteria c = s.createCriteria(User.class);
c.add(Restrictions.eq("name", name));
c.add(Restrictions.lt("birthday", new Date()));
c.setFirstResult(0);
c.setMaxResults(10);
List<User> list = c.list();
User u = (User) c.uniqueResult();
System.out.println(u);
for(User user:list){
System.out.println(user.getName());
}
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.itcast.hibernate.domain.Teacher;
import cn.itcast.hibernate.domain.Student;
public class Many2Many {
public static void main(String[] args) {
add();
query(1);
}
static void query(int id){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Teacher t = (Teacher) s.get(Teacher.class, id);
System.out.println("students:"+t.getStudents().size());
tx.commit();
}finally{
if(s!=null)
s.close();
}
}
static void add(){
Session s = null;
Transaction tx = null;
try{
Set<Teacher> ts = new HashSet<Teacher>();
Teacher t1 = new Teacher();
t1.setName("t1name");
ts.add(t1);
Teacher t2 = new Teacher();
t2.setName("t2name");
ts.add(t2);
Set<Student> ss = new HashSet<Student>();
Student s1 = new Student();
s1.setName("s1name");
ss.add(s1);
Student s2 = new Student();
s2.setName("s2name");
ss.add(s2);
t1.setStudents(ss);
t2.setStudents(ss);
// s1.setTeachers(ts);//many-to-many情况下默认会再向数据库插入值导致出错,
// s2.setTeachers(ts);//可以在配置xml是将维护属性关闭一端也可以将此注释打开
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(t1);
s.save(t2);
s.save(s1);
s.save(s2);
tx.commit();
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.itcast.hibernate.domain.Department;
import cn.itcast.hibernate.domain.Employee;
import cn.itcast.hibernate.domain.Sales;
import cn.itcast.hibernate.domain.Skiller;
public class Many2One {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Department depart = add();
System.out.println("----------------");
Employee emp = query(2,true);
System.out.println("depart name:"+emp.getDepart().getName());
queryDepart(depart.getId());
}
static Department queryDepart(int departId){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Department depart = (Department) s.get(Department.class, departId);
System.out.println("emp size:"+depart.getEmps().size());
// Hibernate.initialize(depart.getEmps());
tx.commit();
return depart;
}finally{
if(s!=null)
s.close();
}
}
static Employee query(int empId,boolean includeDepart){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Employee emp = (Employee) s.get(Employee.class, empId);
System.out.println(emp.getClass());
// System.out.println("depart name:"+emp.getDepart().getName());
if(includeDepart)
Hibernate.initialize(emp.getDepart());
tx.commit();
System.out.println(emp.getDepart());
return emp;
}finally{
if(s!=null)
s.close();
}
}
static Department add(){
Session s = null;
Transaction tx = null;
try{
Department depart = new Department();
depart.setName("depart name");
Employee emp1 = new Employee();
emp1.setDepart(depart);//对象模型:建立两个对象的关联
emp1.setName("emp name1");
Skiller emp2 = new Skiller();
emp2.setDepart(depart);//对象模型:建立两个对象的关联
emp2.setName("emp name2");
emp2.setSkill("skill");
Sales emp3 = new Sales();
emp3.setDepart(depart);
emp3.setName("emp name3");
emp3.setSell(100);
Set<Employee> emps = new HashSet<Employee>();
emps.add(emp1);
emps.add(emp2);
depart.setEmps(emps);
s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(depart);
s.save(emp1);
s.save(emp2);
s.save(emp3);
tx.commit();
System.out.println(emp1.getDepart());
return depart;
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.itcast.hibernate.domain.IdCard;
import cn.itcast.hibernate.domain.Person;
public class One2One {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
add();
query(1);
queryIdCard(1);
}
static Person queryIdCard(int id){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
IdCard idCard = (IdCard) s.get(IdCard.class, id);
System.out.println(idCard.getPerson().getName());
tx.commit();
return null;
}finally{
if(s!=null)
s.close();
}
}
static Person query(int id){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Person p = (Person) s.get(Person.class, id);//只查询主对象时也会将从对象查出,因为主对象不知道从对象到底有值与否,不能简单用hibernate生成的代理来替代
System.out.println(p.getIdCard().getUsefulLife());//one-to-one 查主对象不能懒加载,查从对象时可以懒加载,one-to-many时从性能计就都使用懒加载,将hibernate生成的代理赋给many端从对象
tx.commit();
return p;
}finally{
if(s!=null)
s.close();
}
}
static Person add(){
Session s = null;
Transaction tx = null;
try{
s = HibernateUtil.getSession();
IdCard idCard = new IdCard();
idCard.setUsefulLife(new Date());
Person p = new Person();
p.setName("p1");
p.setIdCard(idCard);//注释掉可以,主对象不依赖从对象
idCard.setPerson(p);//注释掉就不能运行,从对象依赖主对象
tx = s.beginTransaction();
s.save(p);
s.save(idCard);
tx.commit();
return p;
}finally{
if(s!=null)
s.close();
}
}
}
package cn.itcast.hibernate;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import cn.itcast.hibernate.domain.User;
public class QueryTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User();
user.setBirthday(new Date());
user.setName("lisi");
HibernateUtil.add(user);
query(user.getName());
}
static void query(String name){
Session s = null;
try{
s = HibernateUtil.getSession();
String hql = "from User as user where user.name=?";// from Object;1另可以用:name来替代?
Query query = s.createQuery(hql);
query.setString(0, name);//对应上面注释1则0要改为name
query.setFirstResult(0);//可以实现分页
query.setMaxResults(10);
List<User> list = query.list();//类似ps.executeQuery();
User obj = (User) query.uniqueResult();//若有多个结果会报异常
System.out.println(obj.getName());
for(User user:list){
System.out.println(user.getName());
System.out.println(user.getId());
System.out.println(user.getBirthday());
}
}finally{
if(s!=null)
s.close();
}
}
}
hibernate business logical class record
最新推荐文章于 2025-07-28 23:27:29 发布