ssh三大框架整合(3)

来源:互联网 发布:apache的配置文件 编辑:程序博客网 时间:2024/05/16 17:40

解释:在ssh三大框架整合(2)的基础上增加增删改

1、运行insert方法,会报以下错误

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
解释:大概意思就是:写入的操作是不容许在read-only模式下运行了,因为不被spring的事务所管理,默认都是read-only,只能查看不能修改表结构,需要配置spring的aop功能,

配置事物管理器:我的其他博客有详细讲解:在此我就直接贴了:

<!-- 配置事物管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"></bean><!-- 配置那些方法需要事物需要通知:advice开启通知--><tx:advice transaction-manager="transactionManager" id="txAdvice"><tx:attributes><!-- 那些方法需要事务管理 --><tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/><tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/><tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/><tx:method name="*" read-only="true"/></tx:attributes></tx:advice><!-- 确定横切面 --><aop:config><aop:pointcut expression="execution(* com.bjsxt.*.service.impl.*.*(..)) " id="pointcut"/><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/></aop:config>
注:只需要将事务管理器配置到applicationContext_common.xml之中即可

2、继续运行程序之后,会报缺少dateSource的错误

出现错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file 、[D:\work\project\ssh_demo\build\classes\com\bjsxt\user\service\impl\UserServiceImpl.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'txAdvice': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in file [D:\work\project\ssh_demo\build\classes\spring\applicationContext_common.xml]: Invocation of init method failed; nested exception is org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to requested type [javax.sql.DataSource]
异常最下面

引起异常的原因

Caused by: org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to requested type [javax.sql.DataSource]

缺少一个dataSource

解释:在hibernate5之前是不需要配置dataSource的,在hibernate5之后,当spring整合hibernate之后,需要将datasourece也交给spring来管理

3、添加dataSource

<!-- 配置datesource --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ssh"/><property name="password" value="root"/><property name="username" value="root"/></bean>
解释:id--为下面事物管理器的属性,所缺少的属性

class:事物管理器的数据源

其他属性,均是从DriverManagerDataSource中的属性

4、添加运行添加功能即可以正常使用

5、整合spring/hibernate(将hibernate的其他属性也整合到spring中)---可以不必整合

<!-- 支持hibernate --><bean id="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><!-- 引入hibernate的配置文件 --><property name="configLocations" value="classpath:hibernate.cfg.xml" /><!-- 配置其他属性 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop></props></property><!-- 配置映射文件 --><property name="mappingResources"><array><value>/com/bjsxt/user/pojo/AUser.hbm.xml</value></array></property></bean>
解释:所有的name都是从localSessionFacoryBean中找到的,

           由于hibernateProperties属性是properties所以用prop的标签为其设置值

           mappingResources属性是Array数组,利用array标签为其赋值

配置完毕。即可将hibernate的配置文件去掉了

6、将其他的方法填充完毕(没有设置关联-----其中用的到分页工具类在我其他文章中可以找到)

IBasicDao

package com.bjsxt.commom.dao;import java.util.List;import java.util.Map;import com.bjsxt.commom.Util.PageInfoUtil;public interface IBasicDao<T>{/** * 保存一个对象 * @param t * @return 返回的为主键,若等于0 为失败 */int insert(T t);/** * 更新一个记录 * @param t * @return */int update(T t);/** * 删除一条记录 * @param condMap * @return */int delete(T t);/** * 查询一条记录 * @param condMap * @return */T findOne(String hql,Map<String,Object> condMap);/** *查询多条记录分页 * @param condMap * @return */List<T> findList(PageInfoUtil pageInfoUtil,String type,Map<String,Object> condMap);}
BasicDaoImpl

package com.bjsxt.commom.dao.impl;import java.util.List;import java.util.Map;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.query.Query;import org.springframework.orm.hibernate5.HibernateCallback;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.bjsxt.commom.Util.PageInfoUtil;import com.bjsxt.commom.dao.IBasicDao;public abstract class BasicDaoImpl<T> extends HibernateDaoSupport implements IBasicDao<T>{@Overridepublic int update(T t){try{this.getHibernateTemplate().update(t);return 1;} catch (Exception e){}return 0;}@Overridepublic int delete(T t){try{this.getHibernateTemplate().delete(t);return 1;} catch (Exception e){}return 0;}/* * 保存一个对象 * */@Overridepublic int insert(T t){return (int) this.getHibernateTemplate().save(t);}/* * 抽象方法要求继承的子类重写,为自己的findone写条件 * */@Overridepublic abstract T findOne(String type,Map<String,Object> sourceMap);@Overridepublic abstract List<T> findList(PageInfoUtil pageInfoUtil,String type,Map<String,Object> condMap);protected List<T> findListDao(String hql,Map<String, Object> condMap){return (List<T>) this.getHibernateTemplate().execute(new HibernateCallback<List<T>>(){@Overridepublic List<T> doInHibernate(Session session) throws HibernateException{Query query = session.createQuery(hql);query.setProperties(condMap);return (List<T>)query.getResultList();}});}protected List<T> findPageListDao(PageInfoUtil pageInfoUtil,String hql,Map<String, Object> condMap){return (List<T>) this.getHibernateTemplate().execute(new HibernateCallback<List<T>>(){@Overridepublic List<T> doInHibernate(Session session) throws HibernateException{/* 开始分页查询 *//* 查询总记录数 */String sqlCount = "select count(*) ";String start = "from";String end = "order by";sqlCount += hql.substring(hql.indexOf(start), hql.indexOf(end));Query query = session.createQuery(sqlCount);query.setProperties(condMap);Long count = (Long) query.getSingleResult();pageInfoUtil.setTotalRecord(count.intValue());/* 开始查询数据 */query = session.createQuery(hql);query.setProperties(condMap);/* 设置分页信息 */query.setFirstResult(pageInfoUtil.getCurrRecord());query.setMaxResults(pageInfoUtil.getPageSize());return (List<T>)query.getResultList();}});}/* * 查询一条记录 * */protected T findOneDao(String hql,Map<String, Object> condMap){return this.getHibernateTemplate().execute(new HibernateCallback<T>(){@Overridepublic T doInHibernate(Session session) throws HibernateException{/*  * session = connection  一个链接 *  * 获得一个query对象 == preparedStatement  * */try{Query<T> query = session.createQuery(hql);/* 设置参数 */query.setProperties(condMap);return query.getSingleResult();} catch (Exception e){return null;}}});}}
userDao

package com.bjsxt.user.dao.impl;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.stereotype.Repository;import com.bjsxt.commom.Util.PageInfoUtil;import com.bjsxt.commom.dao.impl.BasicDaoImpl;import com.bjsxt.user.dao.IAUserDao;import com.bjsxt.user.pojo.AUser;@Repository("userDao")public class AUserDaoImpl extends BasicDaoImpl<AUser>  implements IAUserDao {/** * 为父类的方法拼接条件 */@Overridepublic AUser findOne(String type, Map<String, Object> sourceMap){Map<String,Object> condMap  = new HashMap<String,Object>();StringBuffer hqlsb = new StringBuffer();hqlsb.append(" from AUser au where 1 = 1 ");if(!"".equalsIgnoreCase(sourceMap.get("id")+"") && sourceMap.get("id")!= null){hqlsb.append(" and id = :id  ");condMap.put("id", Byte.valueOf(sourceMap.get("id")+""));}else if(!"".equalsIgnoreCase(sourceMap.get("password")+"") && sourceMap.get("password")!= null && "".equalsIgnoreCase(sourceMap.get("email")+"") && sourceMap.get("email")!= null){hqlsb.append(" and email = :email and password = :password ");condMap.put("email", sourceMap.get("email"));condMap.put("password", sourceMap.get("password"));}else{return null;}hqlsb.append(" order by au.createTime desc");return this.findOneDao(hqlsb.toString(), condMap);}@Overridepublic List<AUser> findList(PageInfoUtil pageInfoUtil,String type, Map<String, Object> sourceMap){Map<String,Object> condMap = new HashMap<String,Object>();/* 拼接hql语句 */StringBuffer hqlsb = new StringBuffer();hqlsb.append("from AUser au where 1 =1 ");if(!"".equalsIgnoreCase(sourceMap.get("keyword")+"") && sourceMap.get("keyword")!=null){hqlsb.append(" and ((name like :keyword) or (email like :keyword)) ");condMap.put("keyword","%"+sourceMap.get("keyword")+"%");}if(!"".equalsIgnoreCase(sourceMap.get("status")+"") && sourceMap.get("status")!=null){hqlsb.append(" and status = :status");condMap.put("status", Byte.valueOf(sourceMap.get("status")+""));}if(sourceMap.get("startTime") instanceof Date && sourceMap.get("endTime") instanceof Date){hqlsb.append(" and createTime >= :startTime and createTime < :endTime");condMap.put("startTime", sourceMap.get("startTime"));condMap.put("endTime", sourceMap.get("endTime"));}hqlsb.append(" order by au.createTime desc");if(pageInfoUtil == null){/* 不分页 */ return  this.findListDao(hqlsb.toString(), condMap);}return this.findPageListDao(pageInfoUtil, hqlsb.toString(),condMap);}}
serviceimpl:

package com.bjsxt.user.service.impl;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.alibaba.fastjson.JSONObject;import com.bjsxt.commom.Util.PageInfoUtil;import com.bjsxt.user.dao.IAUserDao;import com.bjsxt.user.pojo.AUser;import com.bjsxt.user.service.IUserService;@Service("userService")public class UserServiceImpl implements IUserService{@Resourceprivate IAUserDao userDao;@Overridepublic AUser findUserService(String type, Map<String, Object> sourceMap){return this.userDao.findOne(type, sourceMap);}/** * @return code:1 表示成功 0 表示失败 *  */@Overridepublic JSONObject insertUserService(AUser user){JSONObject jsonObject = new JSONObject();int insert = this.userDao.insert(user);if(insert>0){jsonObject.put("code", "1");jsonObject.put("info", "用户添加成功");JSONObject data = new JSONObject();data.put("id", insert);jsonObject.put("data", data);}else{jsonObject.put("code", "0");jsonObject.put("info", "用户添加失败");}return jsonObject;}@Overridepublic JSONObject deleteUserService(AUser user){JSONObject jsonObject = new JSONObject();int delete = this.userDao.delete(user);if(delete>0){jsonObject.put("code", "1");jsonObject.put("info", "用户删除成功");JSONObject data = new JSONObject();data.put("id", delete);jsonObject.put("data", data);}else{jsonObject.put("code", "0");jsonObject.put("info", "用户删除失败");}return jsonObject;}@Overridepublic JSONObject updateUserService(AUser user){JSONObject jsonObject = new JSONObject();int update = this.userDao.update(user);if(update>0){jsonObject.put("code", "1");jsonObject.put("info", "用户更新成功");JSONObject data = new JSONObject();data.put("id", update);jsonObject.put("data", data);}else{jsonObject.put("code", "0");jsonObject.put("info", "用户更新失败");}return jsonObject;}@Overridepublic List<AUser> findUserListService(PageInfoUtil pageInfoUtil, Map<String, Object> sourceMap){return this.userDao.findList(pageInfoUtil, "", sourceMap);}}
测试类
package com.bjsxt.user.test;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.junit.Before;import org.junit.Test;import com.alibaba.fastjson.JSONObject;import com.bjsxt.commom.Util.PageInfoUtil;import com.bjsxt.commom.Util.constantFinalUtil;import com.bjsxt.commom.test.BasicTest;import com.bjsxt.user.pojo.AUser;import com.bjsxt.user.service.IUserService;public class TestUserService extends BasicTest{private IUserService userService;@Beforepublic void info(){userService = (IUserService) this.applicationContext.getBean("userService");}@Testpublic void test(){constantFinalUtil.LOGGER.info("--test--{}",userService);}@Testpublic void findUserService(){Map<String, Object> sourceMap = new HashMap<String,Object>();;sourceMap.put("id", 1);AUser user = this.userService.findUserService("", sourceMap );constantFinalUtil.LOGGER.info("--user--{}",user);}@Testpublic void insertUserService(){Map<String, Object> sourceMap = new HashMap<String,Object>();;sourceMap.put("id", 1);AUser user = this.userService.findUserService("", sourceMap );user.setEmail("bbb");//JSONObject jsonObject = this.userService.insertUserService(user);JSONObject jsonObject = this.userService.updateUserService(user);constantFinalUtil.LOGGER.info("---jsonObject--{}",jsonObject);}@Testpublic void findUserListService(){Map<String, Object> sourceMap = new HashMap<String, Object>();sourceMap.put("keyword", "b");sourceMap.put("status", 1);PageInfoUtil pageInfoUtil = new PageInfoUtil();pageInfoUtil.setCurrentPage(0);pageInfoUtil.setPageSize(1);List<AUser> list = this.userService.findUserListService(pageInfoUtil , sourceMap);System.out.println(pageInfoUtil);for (Iterator iterator = list.iterator(); iterator.hasNext();){AUser user = (AUser) iterator.next();System.out.println(user);}}}





2 0
原创粉丝点击