在这里实现Spring+SpringMVC+Hibernate的一个小Demo,内容包含一些增删改查。
pom.xml先奉上:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>hibernate_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.1.4.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<jackson.version>2.5.0</jackson.version>
</properties>
<packaging>war</packaging>
<name>baike.common.tools Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- 使用SpringMVC需配置 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- 二级缓存ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- c3p0数据源 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5-pre10</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc_hibernate_demo</finalName>
<plugins>
<!-- Run the JUnit unit tests in an isolated classloader -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
</configuration>
</plugin>
<!-- generate java doc -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<configuration>
<javadocDirectory>target/javadoc</javadocDirectory>
<reportOutputDirectory>target/javadoc</reportOutputDirectory>
<charset>UTF-8</charset>
<encoding>UTF-8</encoding>
<docencoding>UTF-8</docencoding>
<show>private</show>
</configuration>
</plugin>
</plugins>
</build>
</project>
一:连接数据库,因为使用的是Hibernate,所以需要写一些数据库相关的配置信息,新建config,properties.xml,将你的数据库相关的配置信息填写好。
## 引入Spring配置 application configs##
#jdbc c3p0 config##
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://这里写的是服务器地址:3306/这里是数据库名称?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root
#hibernate config##
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
二:Hibernate是包含一级和二级缓存,一级缓存是默认开启的,二级缓存就需要手动开启,所以这里也把缓存的配置写上去,创建一个名为ehcache.xml文件,配置缓存信息。
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="D:/ehcache" />
<!-- DefaultCache setting. -->
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="1000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
<!-- Special objects setting. -->
<cache
name="org.andy.work.entity.AcctUser"
maxElementsInMemory="2"
memoryStoreEvictionPolicy="LRU"
eternal="true"
diskPersistent="false"
overflowToDisk="false"
maxElementsOnDisk="1000000" />
</ehcache>
三:书写Hibernate的配置文件,创建一个名为spring-hibernate.xml的xml文件,配置一些bean实体(很重要)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<!-- 配置数据源 c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 请求超时时间 -->
<property name="checkoutTimeout" value="30000" />
<!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
<property name="idleConnectionTestPeriod" value="30" />
<!-- 连接数据库连接池最大空闲时间 -->
<property name="maxIdleTime" value="30" />
<!-- 连接池初始化连接数 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
<property name="acquireIncrement" value="5" />
</bean>
<!-- 配置过滤器-->
<bean name="myInterceptior" class="org.liang.work.filter.MyInterceptor"/>
<!-- 配置hibernate的SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 注入数据源 相关信息看源码 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置过滤器 -->
<property name="entityInterceptor" ref="myInterceptior"></property>
<!-- hibernate配置信息 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<!--开启二级缓存 ehcache-->
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}</prop>
</props>
</property>
<!-- 扫描hibernate注解配置的entity -->
<property name="packagesToScan" value="org.liang.work.entity" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务增强处理Bean,指定事务管理器 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<!-- 配置详细事务处理语义 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="load*" propagation="SUPPORTS" read-only="true" />
<!-- 其他采用默认事务方式 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- Spring aop事务管理 -->
<aop:config>
<!-- <!– 配置切入点 –>-->
<aop:pointcut id="transactionPointcut"
expression="execution(* org.liang.work.service..*Impl.*(..))" />
<!--<!– 指定在txAdvice切入点应用txAdvice事务增强处理 –>-->
<aop:advisor pointcut-ref="transactionPointcut"
advice-ref="transactionAdvice" />
</aop:config>
</beans>
四:编写spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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">
<!-- 自动扫描@Controller注入为bean -->
<context:component-scan base-package="org.liang.work.controller" />
<!-- 以下为SpringMVC配置 -->
<mvc:annotation-driven>
<!-- 返回json数据,@response使用 -->
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
五:编写spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:config.properties"/>
<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="org.liang.work.service,org.liang.work.dao,org.liang.work.service.impl,org.liang.work.dao.impl" />
</beans>
六:编写web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>springmvc_demo</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- openSessionInView配置 作用是延迟session关闭到view层 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处配置的是SpringMVC的配置文件 -->
<param-value>classpath:spring-mvc.xml</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>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.htmls</url-pattern>
</filter-mapping>
<!-- 配置session超时时间,单位分钟 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
</web-app>
以上,框架的各种配置文件基本搭建完成,我这里省略了日志配置文件。接下来就是代码的编写:
结构如下图中;
重点内容
我这里直接贴上各层代码,接口层的就不贴了,直接贴他的实现类:
1,controller
package org.liang.work.controller;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.jboss.logging.annotations.Param;
import org.liang.work.dto.ResponseWrapper;
import org.liang.work.entity.AcctUser;
import org.liang.work.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* Created by rcc on 2018/1/11.
*/
// http://localhost:8100/user/saveInfo
@Controller
@RequestMapping("/user")
public class UserController {
private static final Logger logger = Logger.getLogger(UserController.class);
@Autowired
private SessionFactory sessionFactory;
Transaction tx = null;
@Autowired
private UserService userService;
@RequestMapping("/saveInfo")
@ResponseBody
public String saveInfo(){
AcctUser user = new AcctUser();
String userId = UUID.randomUUID().toString();
user.setId(userId);
user.setNickName("姜子牙");
user.setRegisterTime(new Date());
user.setTelephone("18770001234");
String id = userService.save(user);
logger.info("==================》用户插入成功!!");
return id;
}
@RequestMapping("/findAll")
@ResponseBody
public ResponseWrapper findAll(){
List<AcctUser> userList = userService.findAll();
return ResponseWrapper.markSuccessAndMsg(userList,"查询成功!!");
}
@RequestMapping("/persistInsert")
@ResponseBody
public ResponseWrapper persistInsert(){
AcctUser user = new AcctUser();
user.setId(UUID.randomUUID().toString());
user.setNickName("云清");
user.setRegisterTime(new Date());
user.setTelephone("18700001944");
userService.persist(user);
return ResponseWrapper.markSuccess("插入成功!!");
}
@RequestMapping("/saveOrUpdate")
@ResponseBody
public ResponseWrapper saveOrUpdate(){
AcctUser user = new AcctUser();
user.setId(UUID.randomUUID().toString());
user.setNickName("将敬夫");
user.setRegisterTime(new Date());
user.setTelephone("18875642314");
userService.saveOrUpdate(user);
return ResponseWrapper.markSuccess("更新成功!!");
}
@RequestMapping("/flush")
@ResponseBody
public ResponseWrapper flush(){
userService.flush();
return ResponseWrapper.markSuccess("刷新成功!!");
}
@RequestMapping("/getNameById")
@ResponseBody
public ResponseWrapper getNameByName(@RequestParam("id") String id){
List<AcctUser> userList = userService.findUserById(id);
return ResponseWrapper.markSuccess(userList,"查询成功!!");
}
@RequestMapping("/updateById")
@ResponseBody
public ResponseWrapper update(@RequestParam("id") String id,
@RequestParam("name")String name){
Integer count = userService.updateById(id, name);
return ResponseWrapper.markSuccess(count,"修改成功!!");
}
@RequestMapping("/deleteById")
@ResponseBody
public ResponseWrapper deleteById(@RequestParam("id")String id){
Integer count = userService.deleteById(id);
return ResponseWrapper.markSuccess(count,"删除成功!!");
}
@RequestMapping("/criteriaTest")
@ResponseBody
public ResponseWrapper criteriaTest(@RequestParam("name")String name){
List<AcctUser> userList= userService.criteriaTest(name);
return ResponseWrapper.markSuccess(userList,"查询成功!!");
}
//分页
@RequestMapping("/getPage")
@ResponseBody
public ResponseWrapper getPage(){
List<AcctUser> userList = userService.getPage();
return ResponseWrapper.markSuccess(userList,"查询成功!!");
}
//测试拦截器
@RequestMapping("/testIntercepter")
@ResponseBody
public ResponseWrapper testInterceptor(){
//add
AcctUser user = new AcctUser();
user.setId(UUID.randomUUID().toString());
user.setNickName("丫头");
user.setTelephone("18876542187");
user.setRegisterTime(new Date());
String count = userService.testInterceptorAdd(user);
return ResponseWrapper.markSuccess(count,"插入成功!!");
}
}
2,serviceImpl
package org.liang.work.service.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.liang.work.dao.UserDao;
import org.liang.work.entity.AcctUser;
import org.liang.work.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by rcc on 2018/1/15.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private SessionFactory sessionFactory;
public String save(AcctUser user) {
return userDao.save(user);
}
public List<AcctUser> findAll() {
return userDao.findAll();
}
public void persist(AcctUser user) {
userDao.persist(user);
}
public void saveOrUpdate(AcctUser user) {
userDao.saveOrUpdate(user);
}
public void flush() {
userDao.flush();
}
public List<AcctUser> findUserById(String userId) {
return userDao.findUserById(userId);
}
public Integer updateById(String id, String name) {
Integer count = userDao.updateById(id, name);
return count;
}
public Integer deleteById(String id) {
return userDao.deleteById(id);
}
public List<AcctUser> criteriaTest(String name) {
return userDao.criteriaTest(name);
}
public List<AcctUser> getPage() {
return userDao.getPage();
}
public String testInterceptorAdd(AcctUser user) {
Session session = sessionFactory.openSession();
Transaction tx = null;
String count = null;
try{
tx = session.beginTransaction();
count = userDao.save(user);
tx.commit();
}catch (Exception e){
if(tx!=null) tx.rollback();
session.close();
return null;
}
return count;
}
}
3,daoImpl
package org.liang.work.dao.impl;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.liang.work.dao.UserDao;
import org.liang.work.entity.AcctUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* Created by rcc on 2018/1/11.
*/
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return this.sessionFactory.getCurrentSession();
}
public AcctUser load(String userId) {
return (AcctUser) this.getCurrentSession().get(AcctUser.class,userId);
}
public String save(AcctUser acctUser) {
return (String) this.getCurrentSession().save(acctUser);
}
@SuppressWarnings("unchecked")
public List<AcctUser> findAll() {
Session session = sessionFactory.openSession();
String sql = "from AcctUser";
Query query = session.createQuery(sql);
query.setCacheable(true);
query.setCacheRegion("acctuser");
System.out.print("在进行查询");
return query.list();
}
public void persist(AcctUser user) {
this.getCurrentSession().persist(user);
}
public void saveOrUpdate(AcctUser user) {
this.getCurrentSession().saveOrUpdate(user);
}
public void flush() {
this.getCurrentSession().flush();
}
@SuppressWarnings("unchecked")
public List<AcctUser> findUserById(String userId) {
Session session = sessionFactory.openSession();
String hql = "from AcctUser as a where a.id = :userId";
Query query = session.createQuery(hql);
query.setParameter("userId",userId);
return query.list();
}
@SuppressWarnings("unchecked")
public Integer updateById(String id, String name) {
Session session = sessionFactory.openSession();
String hql = "UPDATE AcctUser set nickName = :name " +
"WHERE id = :id";
Query query = session.createQuery(hql);
query.setParameter("id",id);
query.setParameter("name",name);
int i = query.executeUpdate();
return i;
}
@SuppressWarnings("unchecked")
public Integer deleteById(String id) {
Session session = sessionFactory.openSession();
String hql = "delete from AcctUser where id=:id";
Query query = session.createQuery(hql);
query.setParameter("id",id);
int count = query.executeUpdate();
return count;
}
public List<AcctUser> criteriaTest(String name) {
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(AcctUser.class);
criteria.add(Restrictions.eq("nickName",name));
List<AcctUser> list = criteria.list();
return list;
}
public List<AcctUser> getPage() {
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(AcctUser.class);
criteria.setFirstResult(0);
criteria.setMaxResults(2);
return criteria.list();
}
}
4,entity
package org.liang.work.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
import static org.hibernate.annotations.CacheConcurrencyStrategy.NONSTRICT_READ_WRITE;
/**
* Created by rcc on 2018/1/11.
*/
@Entity
@Table(name = "acct_user")
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
@Cache(usage =NONSTRICT_READ_WRITE )
public class AcctUser implements Serializable{
private static final long serialVersionUID = 1L;
private String id;
private String nickName;
private String telephone;
private Date registerTime;
@Id
@Column(name = "id" , unique = true , nullable = false,length = 36)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "nick_name",nullable = false)
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Column(name = "telephone" ,nullable = false)
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "register_time" ,length = 19)
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
@Override
public String toString() {
return "AcctUser{" +
"id='" + id + '\'' +
", nickName='" + nickName + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
'}';
}
}
5,通用数据返回层dto
package org.liang.work.dto;
import com.sun.org.apache.xpath.internal.operations.Bool;
/**
* Created by rcc on 2018/1/12.
*/
//数据封装返回类
public class ResponseWrapper {
private Boolean success;
private Boolean openLoginFrom;
private String message;
private String resUrl;
private Object data;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Boolean getOpenLoginFrom() {
return openLoginFrom;
}
public void setOpenLoginFrom(Boolean openLoginFrom) {
this.openLoginFrom = openLoginFrom;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResUrl() {
return resUrl;
}
public void setResUrl(String resUrl) {
this.resUrl = resUrl;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static ResponseWrapper markError(String message){
ResponseWrapper wrapper = new ResponseWrapper();
wrapper.success = false;
wrapper.message = message;
return wrapper;
}
public static ResponseWrapper markOpenLoginFrom(String message){
ResponseWrapper wrapper = new ResponseWrapper();
wrapper.openLoginFrom = true;
wrapper.message = message;
return wrapper;
}
public static ResponseWrapper markSuccess(Object data){
ResponseWrapper wrapper = new ResponseWrapper();
wrapper.success = true;
wrapper.data = data;
return wrapper;
}
public static ResponseWrapper markSuccess(Object data,String resUrl){
ResponseWrapper wrapper = new ResponseWrapper();
wrapper.success = true;
wrapper.data = data;
wrapper.resUrl = resUrl;
return wrapper;
}
public static ResponseWrapper markSuccessAndMsg(Object data,String msg) {
ResponseWrapper responseVo = new ResponseWrapper();
responseVo.success = true;
responseVo.data = data;
responseVo.message = msg;
return responseVo;
}
}
6,拦截器
package org.liang.work.filter;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.liang.work.entity.AcctUser;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Iterator;
/**
* Created by rcc on 2018/1/16.
*/
@Component
public class MyInterceptor extends EmptyInterceptor{
private int updates;
private int creates;
private int loads;
public void onDelete(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
// do nothing
}
// This method is called when Employee object gets updated.
public boolean onFlushDirty(Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) {
if ( entity instanceof AcctUser) {
System.out.println("Update Operation");
return true;
}
return false;
}
public boolean onLoad(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
// do nothing
return true;
}
// This method is called when Employee object gets created.
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
if ( entity instanceof AcctUser ) {
System.out.println("Create Operation");
return true;
}
return false;
}
//called before commit into database
public void preFlush(Iterator iterator) {
System.out.println("preFlush");
}
//called after committed into database
public void postFlush(Iterator iterator) {
System.out.println("postFlush");
}
}