采用spring + hibernate + freemaker+ maven搭建起来的一个hibernate增删查改和
类似mybatis动态sql查询的一个案例
20) >
and age > 20
<#else>
and age < 20
#if>
]]>
${age}
]]>
${age}
]]>
${age}
]]>
${age}
]]>
package test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.business.entity.User;
import com.business.service.UserService;
import com.business.service.impl.UserServiceImpl;
import com.system.hibernate.StatementTemplate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml"})
public class TestUserService {
@Resource(name="userService")
private UserServiceImpl userService;
/**
* 保存单个用户方法
* */
@Test
public void testSave(){
User u = new User("zhangsan",new Date() );
this.userService.save(u);
}
/**
* 批量保存多个用户方法
* */
@Test
public void testSaveAll(){
List list = new ArrayList();
for(int i = 0 ; i < 20000 ; i++){
User user = new User("zhansan"+i,new Date());
list.add(user);
}
this.userService.saveAll(list);
}
/**
* 根据多个id查询
* */
@Test
public void testGetByIds(){
List idsList = new ArrayList();
for(int i = 0 ; i < 100 ; i++){
idsList.add(39100+i);
}
List userList = this.userService.get(User.class, idsList);
for(int i = 0 ; i < userList.size() ; i++){
System.out.println(" i = "+i+" user name = " + userList.get(i).getName() );
}
}
/**
* 取得对象的主键名.
*/
@Test
public void testGetIdName() {
String idName = this.userService.getIdName(User.class);
System.out.println("idName = " + idName);
}
/**
* 删除所有对象
* */
@Test
public void testDeleteAll() {
List idsList = new ArrayList();
for(int i = 0 ; i < 100 ; i++){
idsList.add(29100+i);
}
List userList = this.userService.get(User.class, idsList);
this.userService.deleteAll(userList);
}
/**
* 更新对象
* */
@Test
public void testUpdate() {
int id = 39100;
User user = (User) this.userService.get(User.class,id);
user.setName("update name");
this.userService.update(user);
}
/**
* 根据id查询
* */
@Test
public void testGetById() {
int id = 39100;
User user = (User) this.userService.get(User.class,id);
System.out.println("name = " + user.getName() );
}
/**
* 更新所有对象
* */
@Test
public void testUpdateAll(){
List ids = new ArrayList();
ids.add(1);ids.add(2);ids.add(3);ids.add(4);ids.add(5);
ids.add(39101);ids.add(7);ids.add(39300);ids.add(1);ids.add(39400);
List userList = (List) this.userService.get(User.class, ids);
for(int i = 0 ; i < userList.size() ;i ++ ){
User user = userList.get(i);
user.setName("update username"+i );
}
this.userService.updateAll(userList);
}
/**
* 保存或更新
* */
@Test
public void testSaveOrUpdate(){
User u = new User("zhangsan2",new Date() );
u.setId(1);
this.userService.saveOrUpdate(u);
}
/**
* 保存或更新所有实体
* */
@Test
public void testSaveOrUpdateAll(){
List ids = new ArrayList();
ids.add(1);ids.add(2);ids.add(3);ids.add(4);ids.add(5);
ids.add(39101);ids.add(7);ids.add(39300);ids.add(1);ids.add(39400);
List userList = (List) this.userService.get(User.class, ids);
User newUser = new User("saveOrdate new user",new Date());
for(int i = 0 ; i < userList.size() ; i++){
User user = userList.get(i);
user.setName("saveOrUpdateAll name"+i);
}
userList.add(newUser);
this.userService.saveOrUpdateAll(userList);
}
/**
* 根据原生sql语句进行查询,返回对象集合
* String sql 原生sql语句
* String[] fields 必需为对象字段属性
* 例子: Sql : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* 返回格式 list = { user1,user2,user3... }
*
* */
@Test
public void testFindBySql1() {
String sql = "SELECT name,birthday,age,address FROM USER WHERE NAME LIKE 'zhansan100%'";
String[] fields = { "name","birthday","age","address" };
List
实现原理参考以下博客
http://blog.csdn.net/crazycoder2010/article/details/7414152
4.0.0
02_curd
curd
war
0.0.1-SNAPSHOT
curd Maven Webapp
http://maven.apache.org
4.1.6.RELEASE
4.1.10.Final
2.2.2
log4j
log4j
1.2.17
javax.mail
mail
1.4.1
junit
junit
4.9
test
org.hibernate
hibernate-core
${hibernate.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-orm
${spring.version}
org.aspectj
aspectjweaver
1.5.4
org.springframework
spring-aspects
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-core
${spring.version}
mysql
mysql-connector-java
5.1.18
com.alibaba
druid
1.0.14
javax.persistence
persistence-api
1.0
cglib
cglib
2.2
org.freemarker
freemarker
2.3.20
net.sf.ehcache
ehcache
1.2.3
net.sourceforge.jtds
jtds
1.2.4
org.slf4j
slf4j-log4j12
1.5.8
commons-lang
commons-lang
2.6
org.springframework
spring-test
${spring.version}
curd
compile
classpath*:com/business/dynamicXml/*-dynamicHibernateSql.xml
org.hibernate.dialect.MySQLDialect
true
update
org.springframework.orm.hibernate4.SpringSessionContext
package com.system.hibernate;
import java.util.Collection;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.InitializingBean;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Repository("baseDao")
public class BaseDaoImpl implements InitializingBean{
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;
@Autowired
private HibernateTemplate hibernateTemplate;
private final int BATCH_NUMBER = 100;//批量操作数
/**
* 模板缓存
*/
protected Map templateCache;
@Autowired
protected DynamicHibernateStatementBuilder dynamicStatementBuilder;
// ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
private ThreadLocal session = null;
/**
* 创建session,需要手动关闭
* */
public Session openSession() {
return sessionFactory.openSession();
}
/**
* 根据sql插入或者更新
* */
public void insertOrUpdateBySql(String sql){
if(sql==null) return ;
try{
this.getCurrentSession().createSQLQuery(sql).executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 保存对象
* */
public boolean save(Object obj) {
if(obj==null) return false;
try {
this.hibernateTemplate.save(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 保存所有对象
* */
public boolean saveAll(Collection col) {
if(col==null||col.size()==0) return false;
Session session = this.openSession();
Transaction tx = session.beginTransaction(); // 开启事物
int count = 0;
try {
Iterator iterator = col.iterator();
while(iterator.hasNext()){
count++;
session.save(iterator.next());
if(count%this.BATCH_NUMBER==0){ //以每BATCH_NUMBER个数据作为一个处理单元
session.flush(); //保持与数据库数据的同步
session.clear();//清除内部缓存的全部数据,及时释放出占用的内存
}
}
tx.commit(); // 提交事物
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
return false;
}
this.closeSession(session);
return true;
}
/**
* 删除对象
* */
public boolean delete(Object obj) {
try {
this.hibernateTemplate.delete(obj);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 按id删除对象.
*/
public boolean delete(Class clazz,Serializable id) {
try {
this.hibernateTemplate.delete( this.get(clazz, id) );
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 按id列表获取对象列表.
*/
public List get(Class clazz,Collection ids) {
if(clazz==null||ids==null||ids.size()==0) return null;
return find(clazz,Restrictions.in(getIdName(clazz), ids));
}
/**
* 按Criteria查询对象列表.
*
* @param criterions 数量可变的Criterion.
*/
@SuppressWarnings("unchecked")
public List find(Class clazz,final Criterion... criterions) {
return createCriteria(clazz,criterions).list();
}
/**
* 根据Criterion条件创建Criteria.
* 与find()函数可进行更加灵活的操作.
* @param criterions 数量可变的Criterion.
*/
public Criteria createCriteria(Class clazz,final Criterion... criterions) {
Criteria criteria = this.getCurrentSession().createCriteria(clazz);
for (Criterion c : criterions) {
criteria.add(c);
}
return criteria;
}
/**
* 取得对象的主键名.
*/
public String getIdName(Class clazz) {
if(clazz==null) return null;
ClassMetadata meta = this.sessionFactory.getClassMetadata(clazz);
return meta.getIdentifierPropertyName();
}
/**
* 删除所有对象
* */
public boolean deleteAll(Collection col) {
if(col==null||col.size()==0) return false;
Session session = this.openSession();
Transaction tx = session.beginTransaction(); // 开启事物
int count = 0;
try {
Iterator iterator = col.iterator();
while(iterator.hasNext()){
count++;
session.delete(iterator.next());
if(count%this.BATCH_NUMBER==0){ //以每BATCH_NUMBER个数据作为一个处理单元
session.flush(); //保持与数据库数据的同步
session.clear();//清除内部缓存的全部数据,及时释放出占用的内存
}
}
tx.commit(); // 提交事物
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
return false;
}
this.closeSession(session);
return true;
}
/**
* 更新对象
* */
public boolean update(Object obj) {
if(obj==null) return false;
try {
this.hibernateTemplate.update(obj);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 更新所有对象
* */
public boolean updateAll(Collection col) {
if(col==null||col.size()==0) return false;
Session session = this.openSession();
Transaction tx = session.beginTransaction(); // 开启事物
int count = 0;
try {
Iterator iterator = col.iterator();
while(iterator.hasNext()){
count++;
session.update(iterator.next());
if(count%this.BATCH_NUMBER==0){ //以每BATCH_NUMBER个数据作为一个处理单元
session.flush(); //保持与数据库数据的同步
session.clear();//清除内部缓存的全部数据,及时释放出占用的内存
}
}
tx.commit(); // 提交事物
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
return false;
}
this.closeSession(session);
return true;
}
/**
* 保存或更新
* */
public boolean saveOrUpdate(Object obj) {
try {
this.hibernateTemplate.saveOrUpdate(obj);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 保存或更新所有实体
* */
public boolean saveOrUpdateAll(Collection col) {
Session session = this.openSession();
Transaction tx = session.beginTransaction(); // 开启事物
int count = 0;
try {
Iterator iterator = col.iterator();
while(iterator.hasNext()){
count++;
session.saveOrUpdate(iterator.next());
if(count%this.BATCH_NUMBER==0){ //以每BATCH_NUMBER个数据作为一个处理单元
session.flush(); //保持与数据库数据的同步
session.clear();//清除内部缓存的全部数据,及时释放出占用的内存
}
}
tx.commit(); // 提交事物
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
return false;
}
this.closeSession(session);
return true;
}
/**
* 得到Session ,spring自动管理session,不需要手动关闭
* */
public Session getCurrentSession() throws HibernateException {
// return this.hibernateTemplate.getSessionFactory().getCurrentSession();
return this.hibernateTemplate.getSessionFactory().openSession();
}
/**
* 根据原生sql语句进行查询,返回对象集合
* String sql 原生sql语句
* Class clazz 为类 String[] fields
* 必需为对象字段属性
* 例子: Sql : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* 返回格式 list = { user1,user2,user3... }
*
* */
public List findBySql(String sql, Class clazz, String[] fields) {
return parseObjectToList(this.getCurrentSession().createSQLQuery(sql).list(), clazz, fields);
}
/**
* 根据原生sql语句进行查询,返回对象集合
* String sql 原生sql语句
* String[] fields 可以不为对象字段属性
* 例子:
* Sql : select username ,userage from user;
* fields = { "name","age" };
* 返回
* map1 = { name="张三",age=30}; map2 = { name="李四",age=18};
* list = { map1 ,map2}
*
* */
public List> findBySql(String sql, String[] fields) {
return parseObjectToMap(this.getCurrentSession().createSQLQuery(sql).list(), fields);
}
/**
* 对hibernate查询到object[]数组进行解析,并返回List集合
* */
private List parseObjectToMap(List dataList, String[] fields) {
if (dataList == null || dataList.size() == 0 || fields == null
|| fields.length == 0)
return null;
try {
List list = new ArrayList();
if (dataList != null && dataList.size() > 0) {
for (int i = 0; i < dataList.size(); i++) {
Map map = new HashMap();
if(! dataList.get(i).getClass().isArray() ){
for (int j = 0; j < fields.length; j++) {
map.put(fields[j], dataList.get(i));
}
}else{
Object[] dataObj = (Object[]) dataList.get(i);
for (int j = 0; j < fields.length; j++) {
String currentValue = null;
try {
currentValue = dataObj[j] + "";
} catch (Exception e) {
currentValue = null;
}
if (fields.length > j && fields[j] != null) {
map.put(fields[j], currentValue);
}
}
}
list.add(map);
}
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 对hibernate查询到object[]数组进行解析,并返回List集合
* */
private List parseObjectToList(List dataList, Class clazz, String[] fields) {
if(dataList==null||dataList.size()==0||clazz==null||fields==null||fields.length==0) return null;
try {
List list = new ArrayList();
if (dataList != null && dataList.size() > 0) {
for (int i = 0; i < dataList.size(); i++) {
Object clazzObj = clazz.newInstance();
if(! dataList.get(i).getClass().isArray() ){
Field field = clazz.getDeclaredField(fields[0]);
field.setAccessible(true);
Object currentValue = null;
try {
currentValue = dataList.get(i);
} catch (Exception e) {
currentValue = null;
}
this.setFiled(clazzObj, field, currentValue);
}else{
Object[] dataObj = (Object[]) dataList.get(i);
for (int j = 0; j < fields.length; j++) {
Field field = clazz.getDeclaredField(fields[j]);
field.setAccessible(true);
Object currentValue = null;
try {
currentValue = dataObj[j];
} catch (Exception e) {
currentValue = null;
}
// if (field.getGenericType().toString().equals("class java.lang.String")) {
// field.set(clazzObj, currentValue + "");
// } else if (field.getGenericType().toString().equals("class java.lang.Integer")) {
// field.set(clazzObj, currentValue == null ? null: Integer.parseInt(currentValue + ""));
// } else if (field.getGenericType().toString().equals("class java.lang.Double")) {
// field.set(clazzObj, currentValue == null ? null: Double.parseDouble(currentValue + ""));
// } else if (field.getGenericType().toString().equals("class java.util.Date")) {
// field.set(clazzObj,currentValue == null ? null: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(currentValue.toString()));
// } else if (field.getGenericType().toString().equals("class java.lang.Short")) {
// field.set(clazzObj, currentValue == null ? null: Short.parseShort(currentValue.toString()));
// } else {
// field.set(clazzObj, currentValue);
// }
this.setFiled(clazzObj, field, currentValue);
}
}
list.add(clazzObj);
}
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void setFiled(Object clazzObj,Field field,Object value){
if(clazzObj==null||field==null) return ;
try{
if (field.getGenericType().toString().equals("class java.lang.String")) {
field.set(clazzObj, value + "");
} else if (field.getGenericType().toString().equals("class java.lang.Integer")) {
field.set(clazzObj, value == null ? null: Integer.parseInt(value + ""));
} else if (field.getGenericType().toString().equals("class java.lang.Double")) {
field.set(clazzObj, value == null ? null: Double.parseDouble(value + ""));
} else if (field.getGenericType().toString().equals("class java.util.Date")) {
field.set(clazzObj,value == null ? null: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value.toString()));
} else if (field.getGenericType().toString().equals("class java.lang.Short")) {
field.set(clazzObj, value == null ? null: Short.parseShort(value.toString()));
} else {
field.set(clazzObj, value);
}
}catch(Exception e ){
e.printStackTrace();
}
}
/**
* 根据原生sql语句查询 entity必须为hibernate映射的实体
* */
public List findBySql(String sql, Class entity) {
return this.getCurrentSession().createSQLQuery(sql).addEntity(entity).list();
}
/**
* 根据hql查询
* */
public List findByHql(String hql) {
return this.hibernateTemplate.find(hql);
}
/**
* 根据id查询
* */
public Object get(Class c, Serializable id) {
if(c==null||id==null) return null;
return (Object) this.hibernateTemplate.get(c, id);
}
/**
* 根据id查询
* */
public Object load(Class c, Serializable id) {
return (Object) this.hibernateTemplate.load(c, id);
}
/**
* 根据Id更新对象指定的属性
* */
public boolean updateOneByProperty(Class clazz, Serializable id,
String pName, Object pValue) {
String hql = "update " + clazz.getName() + " entity set entity."
+ pName + " = '" + pValue + "' where entity.id = " + id;
try {
this.hibernateTemplate.bulkUpdate(hql);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据Id更新指定的多个属性
* */
public boolean updateOneByPropertys(Class clazz, Serializable id,
List pName, List pValue) {
if(clazz==null||id==null||pName==null||pName.size()==0||pValue==null||pValue.size()==0) return false;
String hql = "update " + clazz.getName() + " entity set entity.";
int maxIndex = pName.size() - 1;
for (int i = 0; i < maxIndex; i++) {
hql += pName.get(i) + " = '" + pValue.get(i) + "', entity.";
}
hql += pName.get(maxIndex) + " = '" + pValue.get(maxIndex)
+ "'where entity.id = " + id;
try {
this.hibernateTemplate.bulkUpdate(hql);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据id更新多个属性
* */
public boolean updateOneByPropertys(Class clazz, Serializable id,Map map) {
if(clazz==null||id==null||map==null||map.size()==0) return false;
// String[] clazzNameArray = clazz.getName().replace(".", "#").split("#");
// String clazzName = clazzNameArray[clazzNameArray.length-1];
String hql = "update " + clazz.getName() + " entity set entity.";
Set set = map.entrySet();
if (set != null) {
Iterator iterator = set.iterator();
int i = 0;
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
hql += key + " = '" + value + "' , entity.";
i++;
if(i==set.size()-1) break;
}
Entry entry = (Entry) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
hql += key + " = '" + value + "' ";
}
hql += " where entity.id = " + id;
try {
this.hibernateTemplate.bulkUpdate(hql);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 动态命名查询,返回对象集合
* final String queryName 为sql或者hql命名查询
* String[] fields 必需为查询字段
* 例子: queryName : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* Map parameters 为参数{name=zhangsan,age=3}
* 返回格式
* map1 = { name=zhangsan,age=1 }, map2 = { name=zhangsan2,age=2 }, map3 = { name=zhangsan3,age=3 }
* list = {map1,map2,map3}
*
* */
public List> findByNamedQuery(final String queryName, final String[] fields,final Map parameters) {
if( queryName==null || parameters==null || parameters.size()==0 ||fields==null||fields.length == 0) return null;
StatementTemplate statementTemplate = templateCache.get(queryName);
String statement = processTemplate(statementTemplate,parameters);
if(statementTemplate.getType() == StatementTemplate.TYPE.HQL){
return this.parseObjectToMap(this.findByHQL(statement), fields) ;
}
else{
return this.parseObjectToMap(this.findBySql(statement),fields);
}
}
/**
* 动态命名查询,返回对象集合
* final String queryName 为sql或者hql命名查询
* Class clazz 为类对象
* String[] fields 必需为查询字段
* Map parameters 为参数{name=zhangsan,age=3}
* 例子: queryName : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* 返回格式 list = { user1,user2,user3... }
*
* */
public List findByNamedQuery(final String queryName,Class clazz, final String[] fields,final Map parameters) {
if( queryName==null || clazz==null || fields==null || fields.length ==0 || parameters==null || parameters.size()==0 ) return null;
StatementTemplate statementTemplate = templateCache.get(queryName);
String statement = processTemplate(statementTemplate,parameters);
if(statementTemplate.getType() == StatementTemplate.TYPE.HQL){
return this.parseObjectToList(this.findByHQL(statement), clazz, fields);
}
else{
return this.parseObjectToList(this.findBySql(statement), clazz, fields);
}
}
private String processTemplate(StatementTemplate statementTemplate,Map parameters){
StringWriter stringWriter = new StringWriter();
try {
statementTemplate.getTemplate().process(parameters, stringWriter);
} catch (Exception e) {
e.printStackTrace();
}
return stringWriter.toString();
}
/**
* 按HQL查询对象列表.
*
* @param values 数量可变的参数,按顺序绑定.
*/
@SuppressWarnings("unchecked")
public List findByHQL(final String hql, final Object... values) {
List list = createHQLQuery(hql, values).list();
return list;
}
/**
* 按sql查询对象列表.
*
* @param values 命名参数,按名称绑定.
*/
@SuppressWarnings("unchecked")
public List findBySql(final String sql, final Object... values) {
return createSQLQuery(sql, values).list();
}
/**
* 根据查询SQL与参数列表创建Query对象.
* 与find()函数可进行更加灵活的操作.
* @param sqlQueryString sql语句
*
* @param values 数量可变的参数,按顺序绑定.
*/
private Query createSQLQuery(final String sqlQueryString, final Object... values) {
Query query = this.getCurrentSession().createSQLQuery(sqlQueryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}
/**
* 根据查询HQL与参数列表创建Query对象.
* 与find()函数可进行更加灵活的操作.
*
* @param values 数量可变的参数,按顺序绑定.
*/
private Query createHQLQuery(final String queryString, final Object... values) {
Query query = this.getCurrentSession().createQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}
/**
* 关闭session
* */
public void closeSession(Session session) {
if (session != null) {
try {
session.close();
} catch (Exception e) {
e.printStackTrace();
}
session = null;
}
}
@Override
public void afterPropertiesSet() throws Exception {
templateCache = new HashMap();
if(this.dynamicStatementBuilder == null){
this.dynamicStatementBuilder = new DefaultDynamicHibernateStatementBuilder();
}
dynamicStatementBuilder.init();
Map namedHQLQueries = dynamicStatementBuilder.getNamedHQLQueries();
Map namedSQLQueries = dynamicStatementBuilder.getNamedSQLQueries();
Configuration configuration = new Configuration();
configuration.setNumberFormat("#");
StringTemplateLoader stringLoader = new StringTemplateLoader();
for(Entry entry : namedHQLQueries.entrySet()){
stringLoader.putTemplate(entry.getKey(), entry.getValue());
templateCache.put(entry.getKey(), new StatementTemplate(StatementTemplate.TYPE.HQL,new Template(entry.getKey(),new StringReader(entry.getValue()),configuration)));
}
for(Entry entry : namedSQLQueries.entrySet()){
stringLoader.putTemplate(entry.getKey(), entry.getValue());
templateCache.put(entry.getKey(), new StatementTemplate(StatementTemplate.TYPE.SQL,new Template(entry.getKey(),new StringReader(entry.getValue()),configuration)));
}
configuration.setTemplateLoader(stringLoader);
}
}
package com.system.hibernate;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("baseService")
public class BaseServiceImpl {
@Resource(name="baseDao")
private BaseDaoImpl baseDao;
/**
* 根据sql插入或者更新
* */
public void insertOrUpdateBySql(String sql){
this.baseDao.insertOrUpdateBySql(sql);
}
/**
* 保存对象
* */
public boolean save(Object obj) {
return this.baseDao.save(obj);
}
/**
* 保存所有对象
* */
public boolean saveAll(Collection col) {
return this.baseDao.saveAll(col);
}
/**
* 删除对象
* */
public boolean delete(Object obj) {
return this.baseDao.delete(obj);
}
/**
* 按id删除对象.
*/
public boolean delete(Class clazz, Serializable id) {
return this.baseDao.delete(clazz, id);
}
/**
* 按id列表获取对象列表.
*/
public List get(Class clazz, Collection ids) {
return this.baseDao.get(clazz, ids);
}
/**
* 按Criteria查询对象列表.
*
* @param criterions 数量可变的Criterion.
*/
public List find(Class clazz, Criterion... criterions) {
return this.baseDao.find(clazz, criterions);
}
/**
* 根据Criterion条件创建Criteria.
* 与find()函数可进行更加灵活的操作.
* @param criterions 数量可变的Criterion.
*/
public Criteria createCriteria(Class clazz, Criterion... criterions) {
return this.baseDao.createCriteria(clazz, criterions);
}
/**
* 取得对象的主键名.
*/
public String getIdName(Class clazz) {
return this.baseDao.getIdName(clazz);
}
/**
* 删除所有对象
* */
public boolean deleteAll(Collection col) {
return this.baseDao.deleteAll(col);
}
/**
* 更新对象
* */
public boolean update(Object obj) {
return this.baseDao.update(obj);
}
/**
* 更新所有对象
* */
public boolean updateAll(Collection col) {
return this.baseDao.updateAll(col);
}
/**
* 保存或更新
* */
public boolean saveOrUpdate(Object obj) {
return this.baseDao.saveOrUpdate(obj);
}
/**
* 保存或更新所有实体
* */
public boolean saveOrUpdateAll(Collection col) {
return this.baseDao.saveOrUpdateAll(col);
}
/**
* 根据原生sql语句进行查询,返回对象集合
* String sql 原生sql语句
* Class clazz 为类 String[] fields
* 必需为对象字段属性
* 例子: Sql : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* 返回格式 list = { user1,user2,user3... }
*
* */
public List findBySql(String sql, Class clazz, String[] fields) {
return this.baseDao.findBySql(sql, clazz, fields);
}
/**
* 根据原生sql语句进行查询,返回对象集合
* String sql 原生sql语句
* String[] fields 可以不为对象字段属性
* 例子:
* Sql : select username ,userage from user;
* fields = { "name","age" };
* 返回
* map1 = { name="张三",age=30}; map2 = { name="李四",age=18};
* list = { map1 ,map2}
*
* */
public List> findBySql(String sql, String[] fields) {
return this.baseDao.findBySql(sql, fields);
}
/**
* 根据原生sql语句查询 entity必须为hibernate映射的实体
* */
public List findBySql(String sql, Class entity) {
return this.baseDao.findBySql(sql, entity);
}
/**
* 根据hql查询
* */
public List findByHql(String hql) {
return this.baseDao.findByHql(hql);
}
/**
* 根据id查询
* */
public Object get(Class c, Serializable id) {
return this.baseDao.get(c, id);
}
/**
* 根据id查询
* */
public Object load(Class c, Serializable id) {
return this.baseDao.load(c, id);
}
/**
* 根据Id更新对象指定的属性
* */
public boolean updateOneByProperty(Class clazz, Serializable id,
String pName, Object pValue) {
return this.baseDao.updateOneByProperty(clazz, id, pName, pValue);
}
/**
* 根据Id更新指定的多个属性
* */
public boolean updateOneByPropertys(Class clazz, Serializable id,
List pName, List pValue) {
return this.baseDao.updateOneByPropertys(clazz, id, pName, pValue);
}
/**
* 根据id更新多个属性
* */
public boolean updateOneByPropertys(Class clazz, Serializable id,
Map map) {
return this.baseDao.updateOneByPropertys(clazz, id, map);
}
/**
* 按HQL查询对象列表.
*
* @param values 数量可变的参数,按顺序绑定.
*/
public List findByHQL(String hql, Object... values) {
return this.baseDao.findByHQL(hql, values);
}
/**
* 根据sql查询
* */
public List findBySql(String sql, Object... values) {
return this.baseDao.findBySql(sql, values);
}
/**
* 动态命名查询,返回对象集合
* final String queryName 为sql或者hql命名查询
* Class clazz 为类对象
* String[] fields 必需为查询字段
* Map parameters 为参数{name=zhangsan,age=3}
* 例子: queryName : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* 返回格式 list = { user1,user2,user3... }
*
* */
public List findByNamedQuery(String queryName,
Class clazz, String[] fields, Map parameters) {
return this.baseDao.findByNamedQuery(queryName, clazz, fields, parameters);
}
/**
* 动态命名查询,返回对象集合
* final String queryName 为sql或者hql命名查询
* String[] fields 必需为查询字段
* 例子: queryName : select username as name ,userage as age from user;
* User : private String name , private int age
* clazz = User.class
* fields ={ "name","age" }; //注意 sql和fields必需一致,并且fields为User的字段属性
* Map parameters 为参数{name=zhangsan,age=3}
* 返回格式
* map1 = { name=zhangsan,age=1 }, map2 = { name=zhangsan2,age=2 }, map3 = { name=zhangsan3,age=3 }
* list = {map1,map2,map3}
*
* */
public List> findByNamedQuery(String queryName,
String[] fields, Map parameters) {
return this.baseDao.findByNamedQuery(queryName, fields, parameters);
}
}
package com.system.hibernate;
import java.io.IOException;
import java.util.Map;
/**
* 动态sql/hql语句组装器
* @author WangXuzheng
*
*/
public interface DynamicHibernateStatementBuilder {
/**
* hql语句map
* @return
*/
public Map getNamedHQLQueries();
/**
* sql语句map
* @return
*/
public Map getNamedSQLQueries();
/**
* 初始化
* @throws IOException
*/
public void init() throws IOException;
}
DynamicHibernateStatementBuilder.java
package com.system.hibernate;
import java.io.IOException;
import java.util.Map;
/**
* 动态sql/hql语句组装器
* @author WangXuzheng
*
*/
public interface DynamicHibernateStatementBuilder {
/**
* hql语句map
* @return
*/
public Map getNamedHQLQueries();
/**
* sql语句map
* @return
*/
public Map getNamedSQLQueries();
/**
* 初始化
* @throws IOException
*/
public void init() throws IOException;
}
package com.system.hibernate;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import org.hibernate.internal.util.ConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* hibernate动态sql dtd解析器
* @author WangXuzheng
*
*/
public class DynamicStatementDTDEntityResolver implements EntityResolver, Serializable{
private static final long serialVersionUID = 8123799007554762965L;
private static final Logger LOGGER = LoggerFactory.getLogger( DynamicStatementDTDEntityResolver.class );
private static final String HOP_DYNAMIC_STATEMENT = "http://localhost:8080/dtd/";
//
// public InputSource resolveEntity(String publicId, String systemId) {
// InputSource source = null; // returning null triggers default behavior
// if ( systemId != null ) {
// LOGGER.debug( "trying to resolve system-id [" + systemId + "]" );
// if ( systemId.startsWith( HOP_DYNAMIC_STATEMENT ) ) {
// LOGGER.debug( "recognized hop dyanmic statement namespace; attempting to resolve " );
// source = resolveOnClassPath( publicId, systemId, HOP_DYNAMIC_STATEMENT );
// }
// }
// return source;
// }
//
// private InputSource resolveOnClassPath(String publicId, String systemId, String namespace) {
// InputSource source = null;
// String path = systemId.substring( namespace.length() );
// InputStream dtdStream = resolveInHibernateNamespace( path );
// if ( dtdStream == null ) {
// LOGGER.debug( "unable to locate [" + systemId + "] on classpath" );
// if ( systemId.substring( namespace.length() ).indexOf( "2.0" ) > -1 ) {
// LOGGER.error( "Don't use old DTDs, read the Hibernate 3.x Migration Guide!" );
// }
// }
// else {
// LOGGER.debug( "located [" + systemId + "] in classpath" );
// source = new InputSource( dtdStream );
// source.setPublicId( publicId );
// source.setSystemId( systemId );
// }
// return source;
// }
protected InputStream resolveInHibernateNamespace(String path) {
return this.getClass().getClassLoader().getResourceAsStream( path );
}
protected InputStream resolveInLocalNamespace(String path) {
try {
return ConfigHelper.getUserResourceAsStream( path );
}
catch ( Throwable t ) {
return null;
}
}
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
// TODO Auto-generated method stub
return null;
}
}
package com.system.hibernate;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Reflections {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class
if cannot be determined
*/
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.
* 如public BookManager extends GenricManager
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
*/
public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
package com.system.hibernate;
import freemarker.template.Template;
public class StatementTemplate {
private Template template;
private TYPE type;
public StatementTemplate(TYPE type, Template template) {
this.template = template;
this.type = type;
}
public TYPE getType() {
return type;
}
public void setType(TYPE type) {
this.type = type;
}
public Template getTemplate() {
return template;
}
public void setTemplate(Template template) {
this.template = template;
}
public static enum TYPE {
HQL,SQL
}
}
package com.system.hibernate;
import java.io.IOException;
import java.util.Map;
/**
* 动态sql/hql语句组装器
* @author WangXuzheng
*
*/
public interface DynamicHibernateStatementBuilder {
/**
* hql语句map
* @return
*/
public Map getNamedHQLQueries();
/**
* sql语句map
* @return
*/
public Map getNamedSQLQueries();
/**
* 初始化
* @throws IOException
*/
public void init() throws IOException;
}
package com.business.dao;
import java.util.Collection;
import java.util.List;
import com.business.entity.User;
public interface UserDao {
}
package com.business.dao.impl;
import org.springframework.stereotype.Repository;
import com.business.dao.UserDao;
import com.business.entity.User;
import com.system.hibernate.BaseDaoImpl;
@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
}
package com.business.service;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import com.business.entity.User;
public interface UserService {
}
package com.business.service.impl;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.business.dao.UserDao;
import com.business.dao.impl.UserDaoImpl;
import com.business.entity.User;
import com.business.service.UserService;
import com.system.hibernate.BaseServiceImpl;
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
@Resource(name="userDao")
private UserDao userDao;
}
package com.business.entity;
import java.util.Date;
public class User {
private int id;
private String name; //姓名
private Date birthday; //生日
private String address ; //地址
private int age ; //年龄
public User(String name, Date birthday) {
this.name = name;
this.birthday = birthday;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
http://download.csdn.net/detail/jianfpeng241241/9686192