eclipse使用hibernate连接mysql的crup

package com.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.SQLException;

import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder;

import org.junit.After; import org.junit.Before;

public class Test { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ Configuration config=new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //创建会话工厂对象 sessionFactory=config.buildSessionFactory(serviceRegistry); //会话对象 session=sessionFactory.openSession(); //启动事物 transaction= session.beginTransaction();

}
@After
public void destory(){
 transaction.commit();
 session.close();
 sessionFactory.close();
}


@org.junit.Test
public void test() {
	Students s =new Students("16","12");
	session.doWork(new Work() {
		public void execute(Connection connection) throws SQLException {
			// TODO Auto-generated method stub
			connection.setAutoCommit(true);
		}
	});
	Address address=new Address("12","45");
	s.setAddress(address);
	session.save(s);
	//把sql语句输出
	session.flush();	
}

@org.junit.Test
public void QuryStudent(){
	Students s=(Students) session.get(Students.class,"16");
    System.out.println(s);	
}

@org.junit.Test
public void updateStudent(){
	Students s=(Students) session.get(Students.class,"16");
    s.setPass("55");
    session.update(s);
}

@org.junit.Test
public void deleteStudent(){
	Students s=(Students) session.get(Students.class,"16");
    session.delete(s);;
}

可以上面的get处换为load get方法立即执行 load方法是执行时调用 load返回的是代理对象 get查询空返回null load没有返回,报Object错误

转载于:https://my.oschina.net/u/2511906/blog/841649

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值