概述
项目结构:
--------------------------------------
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>web-ll</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- #############spring mvc 拦截器配置 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 激活Tomcat的defaultServlet来处理静态文件=放行css js -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.xml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.swf</url-pattern>
</servlet-mapping>
<!--
<error-page>
<error-code>400</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.html</location>
</error-page>
-->
<!-- ############### -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:config/spring-servlet.xml
</param-value>
</context-param>
<!-- ###############配置字符编码 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
----------------------------------------------
/ll/src/config/applicationContext-common.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/server.properties"></property>
</bean>
<!-- data source -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass"><value>${jdbc.driverClassName}</value></property>
<property name="jdbcUrl"><value>${jdbc.url}</value></property>
<property name="user"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
<property name="minPoolSize"><value>10</value></property>
<property name="maxPoolSize"><value>20</value></property>
<property name="maxIdleTime"><value>600</value></property>
<property name="acquireIncrement"><value>2</value></property>
<property name="maxStatements"><value>0</value></property>
<property name="maxStatementsPerConnection"><value>20</value></property>
<property name="initialPoolSize"><value>20</value></property>
<property name="idleConnectionTestPeriod"><value>600</value></property>
<property name="acquireRetryAttempts"><value>30</value></property>
<property name="breakAfterAcquireFailure"><value>false</value></property>
<property name="testConnectionOnCheckout"><value>false</value></property>
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ipt.model" />
<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">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--启动注解用注解来管理事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
------------------------
/ll/src/config/base-config.properties
#数据库配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ll
jdbc.username=root
jdbc.password=root
--------------------------------------------
/ll/src/config/spring-common.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!-- properties文件解析器 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:config/base-config.properties</value>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" destroy-method="close" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接池时连接数量为5个 -->
<property name="initialPoolSize" value="5" />
<!-- 允许最小连接数量为5个 -->
<property name="minPoolSize" value="5" />
<!-- 允许最大连接数量为20个 -->
<property name="maxPoolSize" value="20" />
<!-- 允许连接池最大生成100个PreparedStatement对象 -->
<property name="maxStatements" value="100" />
<!-- 连接有效时间,连接超过3600秒未使用,则该连接丢弃 -->
<property name="maxIdleTime" value="3600" />
<!-- 连接用完时,一次产生的新连接步进值为2 -->
<property name="acquireIncrement" value="2" />
<!-- 获取连接失败后再尝试10次,再失败则返回DAOException异常 -->
<property name="acquireRetryAttempts" value="10" />
<!-- 获取下一次连接时最短间隔600毫秒,有助于提高性能 -->
<property name="acquireRetryDelay" value="600" />
<!-- 检查连接的有效性,此处小弟不是很懂什么意思 -->
<property name="testConnectionOnCheckin" value="true" />
<!-- 每个1200秒检查连接对象状态 -->
<property name="idleConnectionTestPeriod" value="1200" />
<!-- 获取新连接的超时时间为10000毫秒 -->
<property name="checkoutTimeout" value="10000" />
</bean>
<bean id="mSessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- 注解方式配置 -->
<property name="packagesToScan">
<list>
<value>com.junit.pojo</value>
</list>
</property>
</bean>
<!-- org.springframework.orm.hibernate5.HibernateTransactionManager org.springframework.transaction.jta.JtaTransactionManager -->
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mSessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<!-- 通过<tx:advice/>标签设置了“所有以get开始的方法需要使用read-only事务管理策略,而其它方法使用默认的
事务管理策略”。transaction-manager属性用于指定具体的PlatformTransactionManager实现,txAdvice需要
使用txManager驱动具体的事务管理过程。因此,pointcut标明需要添加事务代理的方法,通过advice配置了事务属性和
事务管理者,当需要事务支持的方法被调用时,aop使用advice找到PlatformTransactionManager,
而PlatformTransactionManager使用底层的具体事务管理架构,最终实现事务管理功能。
-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="register*" propagation="REQUIRED" />
<tx:method name="all" propagation="REQUIRED" />
<tx:method name="changePassword*" propagation="REQUIRED" />
<tx:method name="restPassword*" propagation="REQUIRED" />
<tx:method name="authorize*" propagation="REQUIRED" />
<tx:method name="send*" propagation="REQUIRED" />
<tx:method name="init*" propagation="REQUIRED" />
<tx:method name="*" rollback-for="Exception" /> <!-- 配置一个检测的异常回滚;默认情况下,Spring只会对方法中的未检测运行异常回滚,而被检测的异常不会导致事务回滚 -->
<!-- <tx:method name="*" read-only="true"/> 所有方法(可指定方法,如也get开头的,表示为name="get*")需要使用read-only事务管理策略,而其它方法使用默认的事务管理策略-->
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.junit.service.serviceImpl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
--------------------------------------
/ll/src/config/spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<description>Spring MVC Configuration</description>
<!-- 对静态资源文件的访问,交给default servlet handler处理 在web里配置了这里可注释掉-->
<!-- <mvc:default-servlet-handler/> -->
<!-- 开启MVC注解,并设置返回json的字符编码 -->
<mvc:annotation-driven>
<!--
<mvc:message-converters register-defaults="true">
<bean class="com.junit.global.MyStringHttpMessageConverter"/>
</mvc:message-converters>
-->
</mvc:annotation-driven>
<!-- 包(自动注入) =注释资源扫描包路径-->
<context:component-scan base-package="com.junit"/>
<!--
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
-->
<!-- JSP视图文件解析配置 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/page/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="2"/>
</bean>
-->
<!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
<!-- 配置拦截器, 多个拦截器,顺序执行 -->
<!-- 引入的相关配置 -->
<import resource="classpath:config/spring-common.xml"/>
</beans>
==========================
java controller:
package com.junit.controller;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.junit.pojo.User;
import com.junit.service.UserService;
@Controller
public class DemoController {
@Resource
UserService userservice;
// 首页
@RequestMapping("/index")
// @ResponseBody
public String index(HttpServletRequest request) {
return "index";
}
// 头部
@RequestMapping("/header")
// @ResponseBody
public String header(HttpServletRequest request) {
return "header";
}
// 基于css的下拉菜单
@RequestMapping("/downMenuCSS")
public String downMenuCSS(HttpServletRequest request) {
return "downMenuCSS";
}
// 基于css的下拉菜单
@RequestMapping("/downMenuCSSAndJS")
public String downMenuCSSAndJS(HttpServletRequest request) {
return "downMenuCSSAndJS";
}
// 添加
@RequestMapping("/add")
@ResponseBody
@Test
public String add() {
ModelAndView mav = new ModelAndView();
// User u1 = new User();
// u1.setName("Ying Ma");
// u1.setPassword("123");
// u1.setAge(24);
// u1.setSex("女");
// u1.setBorth(null);
// u1.setDesc("qwsaa");
// userservice.addUser(u1);
userservice.addUser();
return "result";
}
@RequestMapping("/getmav")
public ModelAndView getInfo() {
ModelAndView mav = new ModelAndView(); // populating bean properties
mav.addObject("title", "Return ModelAndView"); // 传String =Add an
// attribute to the
// model.
User user = new User("陆立均", 26); // 传Object
mav.addObject("user", user);
List<User> list = new ArrayList<User>(); // 传List
list.add(new User("赵", 12));
list.add(new User("钱", 24));
list.add(new User("周", 34));
list.add(new User("武", 45));
mav.addObject("list", list);
Map<String, String> map = new HashMap<String, String>(); // 传Map
map.put("name", "wayne");
map.put("age", "24");
mav.addObject("map", map);
mav.setViewName("result");
return mav;
}
@RequestMapping("/string")
public String getInfo(Model model) {
model.addAttribute("title", "Return String"); // 传String
User user = new User("wayne", 24); // 传Object
model.addAttribute("user", user);
List<User> list = new ArrayList<User>(); // 传List
list.add(new User("wayne1", 12));
list.add(new User("wayne2", 24));
list.add(new User("wayne3", 34));
list.add(new User("wayne4", 45));
model.addAttribute("list", list);
Map<String, String> map = new HashMap<String, String>(); // 传Map
map.put("name", "wayne");
map.put("age", "24");
model.addAttribute("map", map);
return "result";
}
@RequestMapping("/strparam")
public String getInfo(@RequestParam("name") String name, @RequestParam("age") String age, Model model) {
// 传String
model.addAttribute("title", "Return String @RequestParam");
// 传Object
User user = new User(name, Integer.valueOf(age));
model.addAttribute("user", user);
// 传List
List<User> list = new ArrayList<User>();
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
model.addAttribute("list", list);
// 传Map
Map<String, String> map = new HashMap<String, String>();
map.put("name", "wayne");
map.put("age", "24");
model.addAttribute("map", map);
return "result";
}
@RequestMapping("/strparam/{name}")
public String getInfor(@PathVariable("name") String name, @RequestParam("age") String age, Model model) {
model.addAttribute("title", "Return String @PathVariable"); // 传String
User user = new User(name, Integer.valueOf(age)); // 传Object
model.addAttribute("user", user);
List<User> list = new ArrayList<User>(); // 传List
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
list.add(new User(name, Integer.valueOf(age)));
model.addAttribute("list", list);
Map<String, String> map = new HashMap<String, String>(); // 传Map
map.put("name", name);
map.put("age", age);
model.addAttribute("map", map);
return "result";
}
}
-----------------------------------
service:
package com.junit.service;
import java.util.List;
import com.junit.pojo.User;
public interface UserService {
/**
* 添加用户信息/
*/
void addUser(User u);
/**
*
*/
void addUser();
/**
* 查询用户信息
* @return List<User>
*/
List<User> getPersons();
}
serviec实现:
package com.junit.service.serviceImpl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.junit.dao.daoImp.BaseDaoImp;
import com.junit.pojo.User;
import com.junit.service.UserService;
//@Transactional
@Service("userservice")
public class UserServiceImp implements UserService{
@Resource
private BaseDaoImp<User> baseDao; //dao
@Override
//@Transactional(rollbackFor={Exception.class})
public void addUser(User u) {
baseDao.addEntity(u);
}
@Override
//@Transactional(rollbackFor={Exception.class})
public void addUser() {
System.out.println("service- addUser方法");
User u1 = new User();
u1.setName("Ying Ma");
u1.setPassword("123");
u1.setAge(24);
u1.setSex("女");
u1.setBorth(null);
u1.setDesc("qwsaa");
baseDao.addEntity(u1);
}
@Override
//@Transactional(readOnly=true) //readOnly=true表明所注解的方法或类只是读取数据。readOnly=false表明所注解的方法或类是增删改数据。
public List<User> getPersons() {
// TODO Auto-generated method stub
return null;
}
}
---------------------
dao:
package com.junit.dao;
import java.io.Serializable;
import java.util.List;
public interface BaseDao<T> {
/**
* 清除一级缓存的数据
*/
public void clear();
/**
* 添加
*/
public void addEntity(T o) throws Exception;
/**
* 更新
*/
public void updateEntity(T o) throws Exception;
/**
* 删除
*/
public void deleteEntity(T o) throws Exception;
/**
* 根据id获取实体
*
* @param clazz
* @param id
* @return
* @throws Exception
*/
public T findById(Class<T> clazz, Serializable id) throws Exception;
/**
* 通用无条件查询总数
*
* @param clazz
* @return
*/
public int getCount(Class<T> clazz);
/**
* 通用无条件查询列表
*
* @param clazz
* @param startIndex
* 开始位置
* @param size
* 条数
* @return
*/
public List<T> getList(Class<T> clazz, int startIndex, int size);
/**
* 通用根据HQL语句查询总数
*
* @param hqlString
* hql语句
* @param parameters
* 占位符参数
* @return
*/
public int getCountByHql(String hqlString, List<Object> parameters);
/**
* 通用根据HQL语句查询列表
*
* @param hqlString
* hql语句
* @param startIndex
* 开始位置
* @param size
* 条数
* @param parameters
* 占位符参数
* @return
*/
public List<T> getListByHql(String hqlString, int startIndex, int size, List<Object> parameters);
/**
* 通用根据HQL语句查询列表(任意字段查询)
*
* @param hqlString
* hql语句
* @param startIndex
* 开始位置
* @param size
* 条数
* @param parameters
* 占位符参数
* @return
*/
public List<Object[]> getObjectArrayByHql(String hqlString, int startIndex, int size, List<Object> parameters);
/**
* 通用根据SQL语句查询列表(任意字段查询)
*
* @param hqlString
* Sql语句
* @param parameters
* 占位符参数
* @return
*/
public List<Object[]> getObjectArrayBySql(String sqlString, List<Object> parameters);
}
-------------------
dao实现:
package com.junit.dao.daoImp;
import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.junit.dao.BaseDao;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
@Repository("baseDao")
@Scope("singleton")
@SuppressWarnings("unchecked")
public class BaseDaoImp<T> extends HibernateDaoSupport implements BaseDao<T>{
@Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
@Override
public void clear() {
}
public void addEntity(T o){
try {
getHibernateTemplate().persist(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void updateEntity(T o){
try {
getHibernateTemplate().update(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteEntity(T o){
try {
getHibernateTemplate().delete(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public T findById(Class<T> clazz,Serializable id){
T t;
try {
t = getHibernateTemplate().get(clazz, id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return t;
}
@Override
public int getCount(Class<T> clazz) {
long count;
try {
count = (long) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery("select count(*) from "+clazz.getTypeName()+" t");
List list = query.list();
return list.get(0);
}
});
} catch (DataAccessException e) {
throw new RuntimeException(e);
}
return (int) count;
}
@Override
public List<T> getList(Class<T> clazz, int startIndex, int size) {
List<T> list;
try {
list = (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
return session.createQuery("select t from "+clazz.getTypeName()+" t").setFirstResult(startIndex).setMaxResults(size).list();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}
@Override
public int getCountByHql(String hqlString,List<Object> parameters) {
long count;
try {
count = (long) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(hqlString);
if(parameters!=null)
for(int i=0;i<parameters.size();i++){
query.setParameter(i, parameters.get(i));
}
return (long) query.list().get(0);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return (int) count;
}
@Override
public List<T> getListByHql(String hqlString, int startIndex, int size,List<Object> parameters) {
List<T> list;
try {
list = (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(hqlString);
if(parameters!=null)
for(int i=0;i<parameters.size();i++){
query.setParameter(i, parameters.get(i));
}
return query.setFirstResult(startIndex).setMaxResults(size).list();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}
@Override
public List<Object[]> getObjectArrayByHql(String hqlString, int startIndex, int size,List<Object> parameters) {
List<Object[]> list;
try {
list = (List<Object[]>) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(hqlString);
if(parameters!=null)
for(int i=0;i<parameters.size();i++){
query.setParameter(i, parameters.get(i));
}
return query.setFirstResult(startIndex).setMaxResults(size).list();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}
@Override
public List<Object[]> getObjectArrayBySql(String sqlString,List<Object> parameters) {
List<Object[]> list;
try {
list = (List<Object[]>) getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery(sqlString);
if(parameters!=null)
for(int i=0;i<parameters.size();i++){
query.setParameter(i, parameters.get(i));
}
return query.list();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}
}
最后
以上就是传统板凳为你收集整理的spring mvc注解环境搭建的全部内容,希望文章能够帮你解决spring mvc注解环境搭建所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复