前面在 http://blog.youkuaiyun.com/yongzhian/article/details/40619479中已经介绍了jpa入门,这里直接已重点代码予以说明:
项目地址:http://download.youkuaiyun.com/detail/yongzhian/8113627 如项目代码与本文有冲突请以本文为准
/jpa/src/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="mysqlJPA" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="admins" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.connection.url" value="jdbc:mysql://10.6.0.204:3306/commonuser" />
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
/jpa/src/com/bean/Person.java
/**
* @Project: jpa
* @Title: Person.java
* @Package com.bean
* @author yongzhian
* @date 2014-10-30 下午2:20:23
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @ClassName Person
* @Description 模块描述
* @author yongzhian
* @Date 2014-10-30
*/
@Entity
@Table(name="user_baseinfo")
public class Person implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "info_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "info_name")
private String name;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id 要设置的 id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name 要设置的 name
*/
public void setName(String name) {
this.name = name;
}
}
/jpa/src/com/base/dao/BaseDao.java
/**
* @Project: jpa
* @Title: DaoUtil.java
* @Package com.base.dao
* @author yongzhian
* @date 2014-10-30 下午3:23:22
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.base.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.bean.Person;
/**
* @ClassName DaoUtil
* @Description 模块描述
* @author yongzhian
* @Date 2014-10-30
*/
public interface BaseDao {
public void save(Person p);
}
/jpa/src/com/base/dao/UserDaoImpl.java
/**
* @Project: jpa
* @Title: UserDaoImpl.java
* @Package com.base.dao
* @author yongzhian
* @date 2014-10-30 下午4:05:54
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.base.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bean.Person;
/**
* @ClassName UserDaoImpl
* @Description 模块描述
* @author yongzhian
* @Date 2014-10-30
*/
@Repository("userDao") //注入一个bean到spring容器中
public class UserDaoImpl implements BaseDao {
@PersistenceContext
private EntityManager em;
/**
@PersistenceContext 注入的是实体管理器,执行持久化操作的,需要配置文件persistence.xml。
会将spring容器中的EntityManagerFactory自动注入进来
@Resource 是注入容器提供的资源对象,比如SessionContext MessageDrivenContext。或者你那个name指定的JNDI对象
*/
@Transactional
public void save(Person p){
//getReference 会报session 失效的错误
Person person = em.find(Person.class, 2);
System.out.println(person.getName()); // 真正调用时才查找数据
}
}
测试
public static void main(String[] args){
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
BaseDao userDao = ctx.getBean("userDao", BaseDao.class);
userDao.save(null);
}
下面附上实际项目中的配置:
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:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>bylxproject.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/config/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-*.xml
</param-value>
</context-param>
<filter>
<filter-name>Spring character encoding filter</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>
</filter>
<filter-mapping>
<filter-name>Spring character encoding filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>sql filter</filter-name>
<filter-class>
com.yineng.base.interceptor.SqlFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sql filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<display-name>ynedut web app context loader</display-name>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>struts</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/c.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
<taglib-location>/WEB-INF/fmt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/sql</taglib-uri>
<taglib-location>/WEB-INF/sql.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/x</taglib-uri>
<taglib-location>/WEB-INF/x.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://www.yineng.com/limit</taglib-uri>
<taglib-location>/WEB-INF/taglib_limit.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://www.yineng.com/codetable</taglib-uri>
<taglib-location>/WEB-INF/taglib_codetable.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.fckeditor.net</taglib-uri>
<taglib-location>/WEB-INF/FCKeditor.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://www.yineng.com/enumvalue</taglib-uri>
<taglib-location>/WEB-INF/enumvalue.tld</taglib-location>
</taglib>
</jsp-config>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/pages/login/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="HibernateJPAPU" transaction-type="RESOURCE_LOCAL">
</persistence-unit>
</persistence>
src/main/resources/config/database.properties
jdbc.drive=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://10.6.0.200\:3306/bylxproject?characterEncoding\=UTF-8&characterSetResults\=UTF-8&profileSQL\=true
jdbc.user=admins
jdbc.password=root
src/main/resources/applicationContext-hibernate.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!--JPA自动注入-->
<context:annotation-config/>
<context:component-scan base-package="com.yineng" />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/database.properties</value>
</list>
</property>
</bean>
<!-- 数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.drive}">
</property>
<property name="url" value="${jdbc.url}">
</property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="10" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="200" />
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="50" />
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="10" />
<!-- #运行判断连接超时任务的时间间隔,单位为毫秒,默认为-1,即不执行任务。 -->
<property name="timeBetweenEvictionRunsMillis" value="3600000" />
<!-- #连接的超时时间,默认为半小时。 -->
<property name="minEvictableIdleTimeMillis" value="3600000" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.drive}">
</property>
<property name="url" value="${jdbc.url}">
</property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="defaultAutoCommit" value="false"></property>
</bean> -->
<bean id="jdbcTemplet"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--JPA entiyFactory Seting-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"></property>
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="com.yineng.base.util.DialectForInkfish"/>
</bean>
</property>
<property name="jpaDialect">
<bean class="com.yineng.base.util.HibernateExtendedJpaDialect"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 事务通知类 -->
<bean id="profiler"
class="com.yineng.base.exception.DealBusnissException">
<!-- order 值可以决定通知的先后顺序 ,与后面的order的值的大小,决定了是先通知再执行,还是先执行再通知-->
<property name="order" value="2" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="batch*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="import*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="remove*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="del*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="get*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="query*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="Save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="batchSave*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="look*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="productServiceMethods"
expression="execution(* com.yineng.*.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
<aop:aspect id="profilingAspect" ref="profiler">
<!-- 通知类型为after-throwing 表示发生异常时通知,还有其他选择-->
<aop:around method="profile"
pointcut-ref="productServiceMethods"/>
</aop:aspect>
</aop:config>
<!--配置struts2 拦截器-->
<bean id="logininterceptor" class="com.yineng.base.interceptor.LoginInterceptor"/>
</beans>
src/main/resources/com/yineng/base/templatedao/TemplateDao.java
package com.yineng.base.templatedao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
/**
* 泛型dao的接口
* @author desert
*/
public interface TemplateDao<T extends Serializable, PK extends Serializable> {
public void setEntityClass(Class<T> entityClass);
/**
* 设置查询实体
* @param em
*/
public void setEntityManager(EntityManager em);
public EntityManager getEntityManager();
/**
* 按分页查询出对应的实体(有条件)
* @param queryStr 查询的hql
* @param params 参数数组
* @param begin 开始页数
* @param max 每页显示的条数
* @author desert
* @return List<T>
*/
public List<T> findEntityByPageConditionList(final Map<Object,Object> map,
final int begin, final int max) ;
/**
* 按分页查询出对应的实体(无条件)
* @param queryStr 查询的hql
* @param params 参数数组
* @param begin 开始页数
* @param max 每页显示的条数
* @author desert
* @return List<T>
*/
public List<T> findEntityByPageConditionList(final int begin, final int max);
/**
* 不按分页查询出对应的实体(有条件)
* @param queryStr 查询的hql
* @param params 参数数组
* @author desert
* @return List<T>
*/
public List<T> findEntityByConditionList(final Map<Object,Object> map);
/**
* 查询出实体的条数
* @param queryStr 查询的hql
* @param params 参数数组(有条件)
* @author desert
* @return List<T>
*/
public Integer getALLEntityByCountInteger(final Map<Object,Object> map);
/**
* 满足任意hql输入
* @param hql
* @return List<Object>
*/
@SuppressWarnings("rawtypes")
public List getEntityByHQLCondition(String hql);
/**
* 获取所有的实体(没有条件)
* @return List<T>
*/
public List<T> getALLEntityList();
/**
* 获取实体所有的记录数目(没有条件)
* @return Integer Entity count
*/
public Integer getAllEntityByCountInteger();
// 根据主键获取实体。如果没有相应的实体,返回 null。
public T get(PK id);
// 更新实体
public void saveOrupdate(T entity);
// 存储实体到数据库
public void save(T entity);
// 增加或更新集合中的全部实体
public void saveOrUpdateAll(List<T> entities);
// 删除指定的实体
public void delete(T entity);
//删除所有的实体
public void deleteAll(List<T> entities);
//-------------------------------- SQL ----------------------------------
/**
* 执行sql query
* @param nnq query string
* @return List
*/
@SuppressWarnings("rawtypes")
public List getQuerySQLList(final String nnq);
/**
* 执行原生 sql 删除
* @param sql
*/
public void deleteBySQL(final String sql);
/**
* 执行原生 sql 删除
* @param sql
*/
public void updateBySQL(final String sql);
/**
* 分页查询出对应的实体(有条件)
* wanglin
* @param sql
* @param paramterMap sql值设置键值对集合
* @param begin 此参数不为null,则执行分页查询
* @param max
* @return
*/
@SuppressWarnings("rawtypes")
public List findEntityListBySql(String sql,final Map<Object, Object> paramterMap,final Integer begin, final Integer max);
/**
* 分页查询出对应的实体(有条件)
* wanglin
* @param sql
* @return
*/
@SuppressWarnings("rawtypes")
public List findEntityListBySql(String sql);
// -------------------------------- Others ---------------------------------
// 加锁指定的实体
public void lock(T entity, LockModeType lock);
// 强制立即更新缓冲数据到数据库(否则仅在事务提交时才更新)
public void flush();
/**
* 增加集合中的全部实体
* @param entities
*/
public void saveAll(List<T> entities);
}
package com.yineng.base.templatedao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
* TemplateDaoImpl 继承 TemplateDao,简单封装 HibernateTemplate 各项功能, 简化基于Dao 的编写。
* @version 1.0
* @author desert
*/
public class TemplateDaoImpl<T extends Serializable, PK extends Serializable>
implements TemplateDao<T, PK> {
@PersistenceContext
protected EntityManager em;
private Class<T> entityClass;// 实体类类型(由构造方法自动赋值)
/**
* service 中动态设置实体
*/
public void setEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
}
public EntityManager getEntityManager() {
return em;
}
// 构造方法,根据实例类自动获取实体类类型
@SuppressWarnings({ "unchecked", "rawtypes" })
public TemplateDaoImpl(){
this.entityClass = null;
Class c = getClass();
Type t = c.getGenericSuperclass();
if (t instanceof ParameterizedType) {
Type[] p = ((ParameterizedType) t).getActualTypeArguments();
this.entityClass = (Class<T>) p[0];
// System.out.println("$$$$$$$$$$$$$" + entityClass.toString());
}
}
// 构造方法二
@SuppressWarnings({ "rawtypes", "unchecked" })
public TemplateDaoImpl(Class obj) {
this.entityClass = obj;
System.out.println(this.entityClass.toString());
}
/**
* 设置查询实体
* @param em
*/
public void setEntityManager(EntityManager em) {
this.em = em;
}
// -------------------- 基本检索、增加、修改、删除操作 --------------------
/**
* 查询出实体的条数
* @param queryStr
* 查询的hql
* @param params
* 参数数组(有条件)
* @author desert
* @return List<T>
*/
public Integer getALLEntityByCountInteger(final Map<Object, Object> map) {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select count(*) from ");
sb.append(clazzName).append(" obj where 1=1 ");
Set<Object> set = map.keySet();
Iterator<Object> keyit = set.iterator();
while (keyit.hasNext()) {
Object key = keyit.next();
Object value= map.get(key);
String linksign = "=";
boolean state = true;
if(value.toString().indexOf("like ")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf(">")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("not in")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("in")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("is null")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("is not null")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<>")!=-1){
linksign ="";
state = false;
}
if((value instanceof String)&&state){
value="'"+value+"'";
}
if(key.toString().indexOf("order by")==-1){
sb.append(" and obj." +key+""+linksign+" "+value+" ");
}
// parameterIndex++;
}
Query query = this.em.createQuery(sb.toString());
//map.clear();// 释放内存
// set.clear();// 释放内存
Object obj = query.getSingleResult();
if (obj != null) {
return Integer.valueOf(obj.toString());
} else {
return 0;
}
}
/**
* 按分页查询出对应的实体(有条件)
* @param queryStr
* 查询的hql
* @param params
* 参数数组
* @param begin
* 开始页数
* @param max
* 每页显示的条数
* @author desert
* @return List<T>
*/
@SuppressWarnings("unchecked")
public List<T> findEntityByPageConditionList(final Map<Object, Object> map,
final int begin, final int max) {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select obj from ");
sb.append(clazzName).append(" obj where 1=1 ");
StringBuffer orderbyString = new StringBuffer();
Set<Object> set = map.keySet();
Iterator<Object> keyit = set.iterator();
// int parameterIndex = 1;
while (keyit.hasNext()) {
Object key = keyit.next();
Object value= map.get(key);
String linksign = "=";
boolean state = true;
if(value.toString().indexOf("like ")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf(">")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("not in")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("in")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("is null")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("is not null")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<>")!=-1){
linksign ="";
state = false;
}
if(key.toString().indexOf("order by")!=-1){
linksign ="";
state = false;
}
if((value instanceof String)&&state){
value="'"+value+"'";
}
if(key.toString().indexOf("order by")==-1){
sb.append(" and obj." +key+""+linksign+" "+value+" ");
}else if(key.toString().indexOf("order by")!=-1){
orderbyString.append(" order by ");
String[] orderArray = value.toString().split(",");
for(int k =0;k<orderArray.length;k++){
String str = orderArray[k];
orderbyString.append("obj."+str);
if(k<(orderArray.length-1)){
orderbyString.append(",");
}
}
}
// parameterIndex++;
}
sb.append(orderbyString); //添加order by
Query query = this.em.createQuery(sb.toString());
// keyit = set.iterator();
// parameterIndex = 1;
// while (keyit.hasNext()) {
// query.setParameter(parameterIndex++, map.get(keyit.next()));
// }
// map.clear();// 释放内存
// set.clear();// 释放内存
if (begin >= 0 && max > 0) {
query.setFirstResult(begin);
query.setMaxResults(max);
}
List<T> ret = query.getResultList();
if (ret != null && ret.size() > 0) {
return ret;
} else {
return new ArrayList<T>();
}
}
/**
* 按分页查询出对应的实体(无条件)
* @param queryStr
* 查询的hql
* @param params
* 参数数组
* @param begin
* 开始页数
* @param max
* 每页显示的条数
* @author desert
* @return List<T>
*/
@SuppressWarnings("unchecked")
public List<T> findEntityByPageConditionList(final int begin, final int max) {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select obj from ");
sb.append(clazzName).append(" obj");
Query query = this.em.createQuery(sb.toString());
if (begin >= 0 && max > 0) {
query.setFirstResult(begin);
query.setMaxResults(max);
}
List<T> ret = query.getResultList();
if (ret != null && ret.size() >= 0) {
return ret;
} else {
return new ArrayList<T>();
}
}
/**
* 不按分页查询出对应的实体(有条件)
* @param queryStr
* 查询的hql
* @param params
* 参数数组
* @author desert
* @return List<T>
*/
@SuppressWarnings("unchecked")
public List<T> findEntityByConditionList(final Map<Object, Object> map) {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select obj from ");
sb.append(clazzName).append(" obj where 1=1 ");
Set<Object> set = map.keySet();
Iterator<Object> keyit = set.iterator();
// int parameterIndex = 1;
while (keyit.hasNext()) {
Object key = keyit.next();
Object value= map.get(key);
String linksign = "=";
boolean state = true;
if(value.toString().indexOf("like ")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf(">")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("in ")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("not in ")!=-1){
linksign ="";
state = false;
}
if(value.toString().indexOf("<>")!=-1){
linksign ="";
state = false;
}
if((value instanceof String)&&state){
value="'"+value+"'";
}
if (key.toString().indexOf("order by") == -1) {
sb.append(" and obj." + key + "" + linksign + " " + value
+ " ");
}
}
Query query = this.em.createQuery(sb.toString());
/* keyit = set.iterator();
parameterIndex = 1;
while (keyit.hasNext()) {
query.setParameter(parameterIndex++, map.get(keyit.next()));
}*/
// map.clear();// 释放内存
// set.clear();// 释放内存
List<T> ret = query.getResultList();
if (ret != null && ret.size() >= 0) {
return ret;
} else {
return new ArrayList<T>();
}
}
/**
* 获取所有的实体(没有条件)
* @return List<T>
*/
@SuppressWarnings("unchecked")
public List<T> getALLEntityList() {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select obj from ");
sb.append(clazzName + " obj");
Query query = this.em.createQuery(sb.toString());
List<T> ret = query.getResultList();
if (ret != null && ret.size() >= 0) {
return ret;
} else {
return new ArrayList<T>();
}
}
/**
* 获取实体所有的记录数目(没有条件)
* @return Integer Entity count
*/
public Integer getAllEntityByCountInteger() {
String clazzName = entityClass.getName();
StringBuffer sb = new StringBuffer("select count(*) from ");
sb.append(clazzName + " obj");
Query query = this.em.createQuery(sb.toString());
Object obj = query.getSingleResult();
if (obj != null) {
return Integer.valueOf(obj.toString());
} else {
return 0;
}
}
/**
* 满足任意hql输入
* @param hql
* @return List<Object>
*/
@SuppressWarnings("rawtypes")
public List getEntityByHQLCondition(String hql) {
Query query = this.em.createQuery(hql);
return query.getResultList();
}
// 根据主键获取实体。如果没有相应的实体,返回 null。
public T get(PK id) {
T t = null;
try{
t = this.em.find(entityClass, id);
}catch(Exception e){
t = null;
}
return t ;
}
// 更新实体
public void saveOrupdate(T entity) {
this.em.merge(entity);
}
// 存储实体到数据库
public void save(T entity) {
this.em.persist(entity);
}
// 增加或更新集合中的全部实体
public void saveOrUpdateAll(List<T> entities) {
if (entities != null) {
for (int i = 0; i < entities.size(); i++) {
this.em.merge(entities.get(i));
if (i % 10 == 0) {
this.em.flush();
}
}
}
}
// 增加全部实体
public void saveAll(List<T> entities) {
if (entities != null) {
for (int i = 0; i < entities.size(); i++) {
this.em.persist(entities.get(i));
if (i % 10 == 0) {
this.em.flush();
}
}
}
}
// 删除指定的实体
public void delete(T entity) {
this.em.remove(this.em.merge(entity));
}
// 删除所有的实体
public void deleteAll(List<T> entities) {
if (entities != null) {
for (int i = 0; i < entities.size(); i++) {
this.em.remove(entities.get(i));
if (i % 5 == 0) {
this.em.flush();
}
}
}
}
// -------------------------------- SQL ----------------------------------
/**
* 执行sql query
* @param nnq
* query string
* @return List
*/
@SuppressWarnings("rawtypes")
public List getQuerySQLList(final String nnq) {
Query query = this.em.createNativeQuery(nnq);
Object ret = query.getResultList();
return (List) ret;
}
/**
* 执行原生 sql 删除
* @param sql
*/
public void deleteBySQL(final String sql) {
Query query = this.em.createNativeQuery(sql);
query.executeUpdate();
}
/**
* 执行原生 sql 删除
* @param sql
*/
public void updateBySQL(final String sql) {
Query query = this.em.createNativeQuery(sql);
query.executeUpdate();
}
/**
* 分页查询出对应的实体(有条件)
* wanglin
* @param sql
* @param paramterMap sql值设置键值对集合
* @param begin 此参数不为null,则执行分页查询
* @param max
* @return
*/
@SuppressWarnings("rawtypes")
public List findEntityListBySql(String sql,final Map<Object, Object> paramterMap,final Integer begin, final Integer max) {
Set<Object> set = paramterMap.keySet();
Iterator<Object> keyit = set.iterator();
Query query = this.em.createNativeQuery(sql);
while (keyit.hasNext()) {
String key = keyit.next().toString();
Object value= paramterMap.get(key);
query.setParameter(key, value);
}
if(begin!=null&&max!=null){
query.setFirstResult(begin);
query.setMaxResults(max);
}
paramterMap.clear();// 释放内存
List ret = query.getResultList();
if (ret != null && ret.size() >= 0) {
return ret;
} else {
return new ArrayList(0);
}
}
/**
* 分页查询出对应的实体(有条件)
* wanglin
* @param sql
* @return
*/
@SuppressWarnings("rawtypes")
public List findEntityListBySql(String sql){
Query query = this.em.createNativeQuery(sql);
List ret = query.getResultList();
if (ret != null && ret.size() >= 0) {
return ret;
} else {
return new ArrayList(0);
}
}
// -------------------------------- Others --------------------------------
// 加锁指定的实体
public void lock(T entity, LockModeType lock) {
this.em.lock(entity, lock);
}
// 强制立即更新缓冲数据到数据库(否则仅在事务提交时才更新)
public void flush() {
this.em.flush();
}
}
/**
* @Project: bylxproject
* @Title: NoticeDaoImpl.java
* @Package com.yineng.notice.dao
* @author DengYuSheng
* @date 2014-8-12 下午3:05:19
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.yineng.notice.dao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import com.yineng.base.templatedao.TemplateDaoImpl;
import com.yineng.base.util.LinkDataBaseName;
import com.yineng.bean.Notice;
/**
* @ClassName NoticeDaoImpl
* @Description 通知公告Dao实现
* @author DengYuSheng
* @Date 2014-8-12
*/
@Repository
public class NoticeDaoImpl extends TemplateDaoImpl<Notice, Integer> implements NoticeDao{
public void saveObject(Object obj){
this.em.persist(obj);
}
/* (non-Javadoc)
* <p>Title: findOrgsByUserId</p>
* <p>Description: 获取用户的组织机构</p>
* @param uSER_ID
* @return
* @see com.yineng.notice.dao.NoticeDao#findOrgsByUserId(java.lang.Integer)
*/
@SuppressWarnings("rawtypes")
@Override
public Integer findOrgsByUserId(Integer uSER_ID) {
String sql = "SELECT e.orgman_id " +
" FROM commonuser.user_baseinfo b " +
" LEFT JOIN commonuser.school_orgstutea c ON c.info_id = b.info_id " +
" LEFT JOIN commonuser.school_orgclass d ON d.orgclass_id = c.orgclass_id " +
" LEFT JOIN commonuser.school_orgmanager e " +
" ON e.orgman_id = d.orgman_id " +
" WHERE b.info_id = " + uSER_ID;
List list = this.getQuerySQLList(sql);
if(list != null && list.size()==1){
return (Integer) list.get(0);
}
return null;
}
/* (non-Javadoc)
* <p>Title: findVisibleNoticeNewVoList</p>
* <p>Description: 根据条件查询通知信息,过滤不满足条件的记录,学生教师带管理域</p>
* @param map
* @param beginRecords
* @param maxRecords
* @return
* @see com.yineng.notice.dao.NoticeDao#findVisibleNoticeNewVoList(java.util.Map, int, int)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public List<Object[]> findVisibleNoticeNewVoList(Map<Object, Object> map,
int beginRecord, int maxRecord) {
StringBuffer sb = new StringBuffer("SELECT DISTINCT N.notice_id,N.title,N.publish_date,N.user_id,N.user_name,N.visible_type,N.visible_orgs, IFNULL(NR.isread,0) AS isread")
.append(" FROM (SELECT * FROM commonuser.notice WHERE type_id= ").append(map.get("typeId"));
if (map.get("publishDate_begin") != null) {
sb.append(" AND publish_date >= '" + map.get("publishDate_begin")+" 00:00:00'");
}
if (map.get("publishDate_end") != null) {
sb.append(" AND publish_date <= '" + map.get("publishDate_end")+" 23:59:59'");
}
if (map.get("title") != null) {
sb.append(" AND title " + map.get("title"));
}
if (map.get("createUserName") != null) {
sb.append(" AND user_name " + map.get("createUserName"));
}
sb.append(")N");
sb.append(" LEFT JOIN commonuser.notice_user_record NR ON (NR.notice_id=N.notice_id AND NR.info_id = ")
.append(map.get("userId"))
.append(")")
.append(" WHERE (N.visible_type=1 AND N.visible_orgs LIKE '%@").append(map.get("orgId")).append("@%' ) ");
if(map.get("roleType") != null && map.get("roleType").equals(3)){//对于学生查询专业是否存在通知
//获取用户的年级ID
String sql = "SELECT d.grade_id FROM commonuser.user_baseinfo b " +
" LEFT JOIN commonuser.school_orgstutea c ON c.info_id = b.info_id " +
" LEFT JOIN commonuser.school_orgclass d " +
" ON d.orgclass_id = c.orgclass_id " +
" WHERE c.orgstutea_state =3 AND b.info_id = " + map.get("userId");
Integer gradeId = null;
List list = this.getQuerySQLList(sql);
if(list != null && list.size()==1){
gradeId = (Integer) list.get(0);
}
//先获取用户的专业ID
sql = "SELECT d.specialty_id FROM commonuser.user_baseinfo b " +
" LEFT JOIN commonuser.school_orgstutea c ON c.info_id = b.info_id " +
" LEFT JOIN commonuser.school_orgclass d " +
" ON d.orgclass_id = c.orgclass_id " +
" WHERE c.orgstutea_state =3 AND b.info_id = " + map.get("userId");
Integer specialtyId = null;
list = this.getQuerySQLList(sql);
if(list != null && list.size()==1){
specialtyId = (Integer) list.get(0);
}
if(gradeId!=null && specialtyId != null){
sb.append(" OR (N.visible_type = 2 AND N.visible_orgs like '%@").append(specialtyId).append("@%' AND N.visible_grades like '%@").append(gradeId).append("@%') ");
}
}
if(map.get("order by").equals("publishDate desc")){
sb.append(" ORDER BY publish_date desc");
}
String sql = sb.toString().replace("database",LinkDataBaseName.commonuser);
Query query = this.em.createNativeQuery(sql);
if (beginRecord >= 0 && maxRecord > 0) {
query.setFirstResult(beginRecord);
query.setMaxResults(maxRecord);
}
return query.getResultList();
}
/* (non-Javadoc)
* <p>Title: findUserLastlogintime</p>
* <p>Description: 方法描述</p>
* @param object
* @return
* @see com.yineng.notice.dao.NoticeDao#findUserLastlogintime(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public Date findUserLastlogintime(Integer userId) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sql = "";
List<Object> list = this.em.createNativeQuery("SELECT UL.time FROM "+LinkDataBaseName.commonuser+".user_lastlogintime UL WHERE UL.userid=:userid")
.setParameter("userid", userId)
.getResultList();
if(list.size()>0){
String lasttime = list.get(0).toString();
try {
return sdf.parse(lasttime);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}