hibernate HQL
package com.h3c.zgc.user.po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="student") public class Student { @Id @Column(name="id") private int id; @Column(name="student_name") private String studentName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } }
package com.h3c.zgc.base; import java.util.Map; public interface BaseDao<T> { long findCount(String hql,Map<String, Object> params); }
package com.h3c.zgc.base; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; @Repository public class BaseDaoHibernate4<T> implements BaseDao<T>{ @Resource private SessionFactory sessionFactory; public Session getSession(){ return this.sessionFactory.getCurrentSession(); } @Override public long findCount(String hql, Map<String, Object> params) { Query query = this.getSession() .createQuery(hql); Set<Entry<String, Object>> ens = params.entrySet(); for(Entry<String,Object> ent:ens){ query.setParameter(ent.getKey(), ent.getValue()); } return (long) query.list().get(0); } }
package com.h3c.zgc.user.service; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.h3c.zgc.user.dao.StudentDao; import com.h3c.zgc.user.po.Student; @Service public class StudentService { @Resource private StudentDao studentDao; @Transactional public long getCount(Student s){ String hql ="select count(id) from Student where studentName =:name"; Map<String,Object> params = new HashMap<String, Object>(); params.put("name", s.getStudentName()); return this.studentDao.getTotalCount(hql, params); } }
package com.h3c.zgc.user.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.h3c.zgc.user.po.Student; import com.h3c.zgc.user.service.StudentService; public class TestSpring { @Test public void test1(){ ApplicationContext wac = new ClassPathXmlApplicationContext("spring/mvc/action-servlet.xml"); StudentService ss = (StudentService) wac.getBean("studentService"); Student s = new Student(); s.setStudentName("name"); System.out.println(ss.getCount(s)); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。