1. 引入jar包:
2. 根目录下创建spring.xml配置信息:
3. 建立接口:
package com.sinosoft.manage;
public interface UserManage {
public static final String uname="XSY";
public abstract void testHib();
}
4. 实现接口:
package com.sinosoft.manage.impl;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import com.sinosoft.manage.UserManage;
import com.sinosoft.po.User;
@Service
public class UserManageImpl extends HibernateDaoSupport implements UserManage {
@Autowired
public void setSF(SessionFactory sessionFactory){
//给父类复制
setSessionFactory(sessionFactory);
}
@Override
public void testHib() {
//获取父类的方法 hibernate中的
Session session = getSession();
List list = session.createQuery(" from User").list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUname());
}
//三个hibernate特有的方法
// List users = getHibernateTemplate().find(" from User");
// long count = (Long) getHibernateTemplate().find("select count(*) from User where id < ?",6).get(0);
// long count1 = (Long) session.createQuery("select count(*) from User where id < ?").setInteger(0, 6).uniqueResult();
User user = new User();
user.setUname("xsy");
session.save(user);
//发生错误信息 事物回退 不进行提交操作
int i = 1/0;
}
}
5. 建立pojo实体对象:
package com.sinosoft.po;
public class User {
private String uname;
private String pwd;
private String sex;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String uname, String pwd, String sex) {
super();
this.uname = uname;
this.pwd = pwd;
this.sex = sex;
}
//get set 方法
}
6. 在pojo同一级别创建映射文件 TbUser.hbm.xml
7. 测试:
package test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.sinosoft.manage.UserManage;
import com.sinosoft.manage.impl.UserManageImpl;
public class SpringTest {
@Autowired
private UserManage userManage = new UserManageImpl();
@Test
public void test(){
userManage.testHib();
}
}